package com.zhilin.patrol.ui.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.zhilin.patrol.R;
import com.zhilin.patrol.adapter.QuestionImgAdapter;
import com.zhilin.patrol.adapter.UpImageAdapter;
import com.zhilin.patrol.adapter.UpImageAdapterRectify;
import com.zhilin.patrol.adapter.helper.GridItemDecoration;
import com.zhilin.patrol.adapter.helper.MyItemTouchCallback;
import com.zhilin.patrol.adapter.helper.OnRecyclerItemClickListener;
import com.zhilin.patrol.bean.AddressAreaEntity;
import com.zhilin.patrol.bean.LoginEntity;
import com.zhilin.patrol.bean.MapLocationInfo;
import com.zhilin.patrol.bean.PatrolFormEntity;
import com.zhilin.patrol.bean.QuestionKindEntity;
import com.zhilin.patrol.bean.RectifyFormEntity;
import com.zhilin.patrol.bean.RectifyUploadEntity;
import com.zhilin.patrol.http.HttpUrl;
import com.zhilin.patrol.tool.CheckPermissionUtils;
import com.zhilin.patrol.tool.Compresser;
import com.zhilin.patrol.tool.DensityUtil;
import com.zhilin.patrol.tool.DialogUtil;
import com.zhilin.patrol.tool.IpUtils;
import com.zhilin.patrol.tool.JsonUtils;
import com.zhilin.patrol.tool.LocationUtils;
import com.zhilin.patrol.tool.SPUtil;
import com.zhilin.patrol.tool.Utils;
import com.zhilin.patrol.views.AlertDialog;
import com.zhilin.patrol.views.CustomProgressDialog;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class RecifyUploadActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.img_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.img_question)
    RecyclerView mQuesImgView;
    @BindView(R.id.et_content)
    EditText mRemarkEt;//反馈
    @BindView(R.id.tv_questionStr)
    TextView mQuestionTv;
    @BindView(R.id.tv_content_num)
    TextView mContentNumTv;//备注长度
    @BindView(R.id.tv_img_num)
    TextView mImgNumTv;//图片数量
    @BindView(R.id.tv_location)
    TextView mLocationTv;

    private String TAG="PatrolUploadActivity";//打印日志

    //用户信息
    private LoginEntity.InfoListBean.UserInfoBean mUserInfo;
    private RectifyFormEntity.InfoListBean ryInfo;
    //选择图片适配器
    private UpImageAdapterRectify mAdapter;

    private QuestionImgAdapter mqAdapter;

    //上传图片
    public ArrayList<String> mDataList = new ArrayList<>();

    public ArrayList<String> imgList = new ArrayList<>();

    private ItemTouchHelper mItemTouchHelper;

    private CustomProgressDialog mProgressDialog;

    /** 客户文件目录 */
    private String mImageDir = Environment.getExternalStorageDirectory() + "/patrol/";

    String[] mPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE};
    /** 表单返回码 */
    private String mTkCode="1";
    private List imageList=new ArrayList();
    private String pbCode;
    private String maddress;
    private String mquestion;
    private int mType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recify_upload);
        ButterKnife.bind(this);
        mUserInfo = (LoginEntity.InfoListBean.UserInfoBean) getIntent().getSerializableExtra("userInfo");
        mType=getIntent().getIntExtra("mType",1);
        pbCode=getIntent().getStringExtra("pCode");
        maddress=getIntent().getStringExtra("address");
        mquestion=getIntent().getStringExtra("text");
        imgList=getIntent().getStringArrayListExtra("imgList");
        mProgressDialog = new CustomProgressDialog(this);
        if(mType==1){
            setTitle("整改反馈");
        }else {
            setTitle("复议申请");
        }
        setRightTv("提交");
        setRightClick(this);
        Log.i("question==",mquestion);
        mQuestionTv.setText(mquestion);

        mLocationTv.setText(maddress);
        mRemarkEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void afterTextChanged(Editable editable) {
                mContentNumTv.setText(mRemarkEt.getText().length() + "/200");
            }
        });
        setRecycler();
        setImageNum();
        checkPermissions();


    }


    @TargetApi(Build.VERSION_CODES.M)
    private void checkPermissions() {
        mPermissions = CheckPermissionUtils.getNeededPermission(this, mPermissions);
        if (mPermissions.length > 0) {
            requestPermissions(mPermissions, 999);
        }
        if (mPermissions.length == 0) {
            //申请过一次这里的permissions.length就为0 了
            //申请权限后创建图片文件夹
            Utils.createDir(mImageDir);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int i = 0; i < grantResults.length; i++) {
            if (PackageManager.PERMISSION_GRANTED != grantResults[i]) {
                new AlertDialog(RecifyUploadActivity.this).builder()
                        .setTitle(RecifyUploadActivity.this.getString(R.string.tv_tishi))
                        .setMsg("获取权限失败，是否重新尝试？")
                        .setPositiveButton("重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                checkPermissions();
                            }
                        })
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        }).show();
                return;
            }
        }
        //申请权限后创建图片文件夹
        Utils.createDir(mImageDir);
    }


    /**
     * 设置图片数量
     */
    public void setImageNum() {
        mImgNumTv.setText(Html.fromHtml("上传图片 <Small>" + mDataList.size() + "/9</Small>"));
    }

//    @OnClick({R.id.ll_location})//R.id.tv_last_location_use
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.tv_last_location_use://使用上次定位
//                if (mLastHasProblem != -1) {
//                    mHasProblem = mLastHasProblem;
//                    isQuestionJump = false;
//                    if (mHasProblem == 1) {//有问题
//                        mQuestionRg.check(R.id.rb_question_yes);
//                    } else {//没问题
//                        mQuestionRg.check(R.id.rb_question_no);
//                    }
//                }
//                mSelectBean = mLastSelectBean;
//                mMapLocationInfo = mLastMapLocationInfo;
//                mListBean = mLastListBean;
////                mLocationTv.setText(mMapLocationInfo.getAddress());
//                if (mSelectBean != null) {
//                    mQuestionTypeTv.setText(mSelectBean.getqName());
//                }
//                mLocationTv.setText(mLastListBean != null ? mLastListBean.getAddress() : mLastMapLocationInfo.getAddress());
//                break;
//            case R.id.tv_question://问题分类
//                toQuestionType();
//                break;
//            case R.id.ll_location://定位
//                if (mMapLocationInfo == null) {
//                    locationAddress();
//                } else {//选择小区
//                    toAddressSelect();
//                }
//                break;
            case R.id.tv_right://提交
                if (mDataList.size() < 1&&mType==1) {
                    Utils.showToast(this, "请拍摄图片");
                    return;
                }
                String remark = mRemarkEt.getText().toString().trim();
                if (TextUtils.isEmpty(remark)) {
                        Utils.showToast(this, "请输入说明信息");
                        return;
                }
                if (!TextUtils.isEmpty(mTkCode)) {
                    mProgressDialog.showDialog("正在提交...");
                    postPatrolImage();
                    return;
                }

//                String questionKind = "";
//                if (mHasProblem == 1) {
////                    StringBuilder sb = new StringBuilder();
////                    for (QuestionKindEntity.Bean bean : mSelectList) {
////                        sb.append(bean.getqCode()).append(",");
////                    }
////                    questionKind = sb.substring(0, sb.length() - 1);
//                    questionKind = mSelectBean.getqCode();
//                }

                break;
            default:
                break;
        }
    }


    /**
     * 提交巡查信息
     *
     * @param remark
     */
    private void postPatrol(String remark,List list){
        Log.i("imglist==", String.valueOf(list));
        Gson gson=new Gson();
        String jsonList=gson.toJson(list);
        Log.i("jsonlist=",jsonList);
        Log.i("content=",remark+"");
        Log.i("pbCode=",pbCode);
//        Response response=OkHttpUtils.post()
        if(mType==1){
            Log.i("fuyi","整改反馈上传");
            OkHttpUtils.post()
                    .url(HttpUrl.RECTIFY_POST)
                    .addParams("urls", jsonList)
                    .addParams("content", remark+"")
                    .addParams("pbCode",pbCode)
//                .build().execute();
                    .build().execute(new Callback<RectifyUploadEntity>() {
                @Override
                public RectifyUploadEntity parseNetworkResponse(Response response, int id) throws Exception {
                    String jsonStr = response.body().string();
                    Log.i("jsonStr=",jsonStr);
                    return (RectifyUploadEntity) JsonUtils.parseJson2Obj(jsonStr, RectifyUploadEntity.class);
                }
                @Override
                public void onError(Call call, Exception e, int id) {
                    mProgressDialog.dismiss();
                    DialogUtil.showNetFailDialog(RecifyUploadActivity.this);
                }
                @Override
                public void onResponse(RectifyUploadEntity entity, int id) {
                    if (entity == null) {
                        DialogUtil.showErrDialog(RecifyUploadActivity.this, "返回信息为空");
                        return;
                    }
                    if (!"1000".endsWith(entity.getReturnCode())) {
                        DialogUtil.showErrDialog(RecifyUploadActivity.this, entity.getReturnMsg());
                        return;
                    }
                    Utils.showToast(RecifyUploadActivity.this, "提交成功，请等待审核");
                    finish();
                }
            });
        }else {
            Log.i("fuyi","复议申请上传");
            OkHttpUtils.post()
                    .url(HttpUrl.RECHECK_POST)
                    .addParams("urls", jsonList)
                    .addParams("content", remark+"")
                    .addParams("pbCode",pbCode)
//                .build().execute();
                    .build().execute(new Callback<RectifyUploadEntity>() {
                @Override
                public RectifyUploadEntity parseNetworkResponse(Response response, int id) throws Exception {
                    String jsonStr = response.body().string();
                    Log.i("jsonStr=",jsonStr);
                    return (RectifyUploadEntity) JsonUtils.parseJson2Obj(jsonStr, RectifyUploadEntity.class);
                }
                @Override
                public void onError(Call call, Exception e, int id) {
                    mProgressDialog.dismiss();
                    DialogUtil.showNetFailDialog(RecifyUploadActivity.this);
                }
                @Override
                public void onResponse(RectifyUploadEntity entity, int id) {
                    if (entity == null) {
                        DialogUtil.showErrDialog(RecifyUploadActivity.this, "返回信息为空");
                        return;
                    }
                    if (!"1000".endsWith(entity.getReturnCode())) {
                        DialogUtil.showErrDialog(RecifyUploadActivity.this, entity.getReturnMsg());
                        return;
                    }
                    Utils.showToast(RecifyUploadActivity.this, "提交成功，请等待审核");
                    finish();
                }
            });
        }

//        if(response.isSuccessful()) {
//            String jsonStr = response.body().string();
//            Log.i(TAG,jsonStr+"=jsonStr");
//            RectifyUploadEntity entity = (RectifyUploadEntity) JsonUtils.parseJson2Obj(jsonStr, RectifyUploadEntity.class);
//            if (entity == null) {
//                Log.i(TAG,"entity=null");
//                DialogUtil.showErrDialog(RecifyUploadActivity.this, "返回信息为空");
//                return;
//            }
//            if (!"1000".endsWith(entity.getReturnCode())) {
//                DialogUtil.showErrDialog(RecifyUploadActivity.this, entity.getReturnMsg());
//                throw new IOException(entity.getReturnMsg());
//            }
//            finish();
//        }
    }

    /**
     * 上传图片
     */
    private void postPatrolImage() {
        new Thread() {
            @Override
            public void run() {
                ArrayList<String> list = new ArrayList(mDataList);
                for (String imgPath : list) {
                    try {
                        postPatrolImageSync(imgPath);
                    } catch (IOException e) {
                        Log.e("post_image", "图片上传失败");
                    }
                }
                list.clear();
                list = null;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mProgressDialog.dismiss();
                        if (mDataList.size() == 0) {
//                            Utils.showToast(RecifyUploadActivity.this, "提交成功，请等待审核");
                            String remark = mRemarkEt.getText().toString().trim();
                            postPatrol(remark,imageList);
//                            Utils.showToast(RecifyUploadActivity.this, "提交成功，请等待审核");
//                            finish();
                        } else {
                            Utils.showToast(RecifyUploadActivity.this, "图片上传失败，请点击提交重新上传");
                        }
                    }
                });
            }
        }.start();
    }

    /**
     * 提交图片
     */
    private void postPatrolImageSync(final String imagePath) throws IOException {
        Log.i(TAG,"提交巡查图片");
        File file = new File(imagePath);
        String fileName = file.getName();
        Response response = OkHttpUtils.post()
                .url(HttpUrl.RECTIFYIMG_POST)
                .addFile("imgFile", fileName, file)
                .build().execute();
        if (response.isSuccessful()) {
            String jsonStr = response.body().string();
            Log.i(TAG,jsonStr+"=jsonStr");
            RectifyFormEntity entity = (RectifyFormEntity) JsonUtils.parseJson2Obj(jsonStr, RectifyFormEntity.class);
            List<RectifyFormEntity.InfoListBean> list = entity.getInfoList();
            ryInfo=list.get(0);
            imageList.add(ryInfo.getUrl());
            if (!"1000".endsWith(entity.getReturnCode())) {
                DialogUtil.showErrDialog(RecifyUploadActivity.this, entity.getReturnMsg());
                throw new IOException(entity.getReturnMsg());
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDataList.remove(imagePath);
                        Utils.delSingleFile(imagePath);
                        mAdapter.notifyDataSetChanged();

                    }
                });
            }
        } else {
            throw new IOException(response.message());
        }
    }

    private void setRecycler() {
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        Log.i("mdataList", String.valueOf(mDataList));
        mAdapter = new UpImageAdapterRectify(this, mDataList, layoutManager.getSpanCount());

        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addItemDecoration(new GridItemDecoration(DensityUtil.dip2px(this, 8)));

        GridLayoutManager layoutManager2 = new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mqAdapter = new QuestionImgAdapter(this, imgList, layoutManager2.getSpanCount());
        mQuesImgView.setHasFixedSize(true);
        mQuesImgView.setLayoutManager(layoutManager2);
        mQuesImgView.setAdapter(mqAdapter);
        mQuesImgView.addItemDecoration(new GridItemDecoration(DensityUtil.dip2px(this, 8)));



        MyItemTouchCallback callback = new MyItemTouchCallback(mAdapter);
        mItemTouchHelper = new ItemTouchHelper(callback);
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);
        mRecyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(mRecyclerView) {
            @Override
            public void onLongClick(RecyclerView.ViewHolder vh) {
                if (vh.getLayoutPosition() != mDataList.size()) {
                    mItemTouchHelper.startDrag(vh);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKE_PICTURE) {
            //返回拍照的图片
            Log.i("path camera=",path);
            if (resultCode == -1 && !TextUtils.isEmpty(path) && Utils.fileIsExists(path)) {
                //压缩图片
                mProgressDialog.showDialog("正在压缩图片");
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            File compressFile = Compresser.getInstance()
                                    .compressImage(Compresser.THIRD_GEAR, new File(path),
                                            mImageDir);
                            if (compressFile != null && compressFile.exists()) {
                                mDataList.add(compressFile.getAbsolutePath());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mProgressDialog.dismiss();
                                        mAdapter.notifyDataSetChanged();
                                        setImageNum();
                                    }
                                });
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }

        }else if(requestCode==LOCAL_CROP) {
            Uri uri = data.getData();

            Log.i("uri zhaopian=", String.valueOf(uri));
            assert uri != null;
            path=uri.getPath();
            String[] data1=path.split("raw/");
            if(data1[0].equals("/")){
                Log.i("data[1]",data1[1]);
                path=data1[1];
            }

            Log.i("path zhaopian=",path);
            if (resultCode == -1 && !TextUtils.isEmpty(path) && Utils.fileIsExists(path)) {
                //压缩图片
                mProgressDialog.showDialog("正在压缩图片");
                new Thread() {
                    @Override
                    public void run() {
                        try {

                            File compressFile = Compresser.getInstance()
                                    .compressImage(Compresser.THIRD_GEAR, new File(path),
                                            mImageDir);
                            if (compressFile != null && compressFile.exists()) {
                                mDataList.add(compressFile.getAbsolutePath());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mProgressDialog.dismiss();
                                        mAdapter.notifyDataSetChanged();
                                        setImageNum();
                                    }
                                });
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        }

    }

    /** 拍照的文件地址 */
    private String path = "";
    /** 拍照请求码 */
    private static final int TAKE_PICTURE = 0x000003;
    private static final int  LOCAL_CROP= 0x000004;

    /**
     * 拍照
     */
    public void toCamera() {
        if (UpImageAdapter.MAX_IMAGE_SIZE <= 0) {
            Utils.showToast(this, "已达到上传图片上限!");
            return;
        }
        File vFile = new File(Environment.getExternalStorageDirectory()
                + "/myimage/", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                + ".jpg");

        if (!vFile.exists()) {
            File vDirPath = vFile.getParentFile();
            vDirPath.mkdirs();
        } else {
            if (vFile.exists()) {
                vFile.delete();
            }
        }
        path = vFile.getPath();
        /*获取当前系统的android版本号*/
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion < Build.VERSION_CODES.N) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(vFile));
            startActivityForResult(intent, TAKE_PICTURE);
        } else {
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, vFile.getAbsolutePath());
            Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, TAKE_PICTURE);
        }
    }
    public void toPhoto(){
        if (UpImageAdapter.MAX_IMAGE_SIZE <= 0) {
            Utils.showToast(this, "已达到上传图片上限!");
            return;
        }
//        File vFile = new File(Environment.getExternalStorageDirectory()
//                + "/myimage/", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
//                + ".jpg");
//        if (!vFile.exists()) {
//            File vDirPath = vFile.getParentFile();
//            vDirPath.mkdirs();
//        } else {
//            if (vFile.exists()) {
//                vFile.delete();
//            }
//        }
//        File vFile = new File(Environment.getExternalStorageDirectory(), "outputTest.jpg");
//        try {
//            if (vFile.exists()) {
//                vFile.delete();
//            }
//            vFile.createNewFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        path = vFile.getPath();
            // 创建Intent，用于打开手机本地图库选择图片
//            Intent intent1 = new Intent(Intent.ACTION_PICK);
//            intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(vFile));
//                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // 启动intent打开本地图库
//            startActivityForResult(intent1,LOCAL_CROP);
//        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
//        if (currentapiVersion < Build.VERSION_CODES.N) {
//            intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(vFile));
//            startActivityForResult(intent1, LOCAL_CROP);
//        } else {
//            ContentValues contentValues = new ContentValues(1);
//            contentValues.put(MediaStore.Images.Media.DATA, vFile.getAbsolutePath());
//            Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
//            intent1.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//            startActivityForResult(intent1, LOCAL_CROP);
//        }
//        Intent intent = new Intent("android.intent.action.GET_CONTENT");
//        intent.setType("image/*");
//        //允许裁剪
//        intent.putExtra("crop", true);
//        //允许缩放
//        intent.putExtra("scale", true);
//        图片的输出位置
        Intent intent1 = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, path);
        startActivityForResult(intent1,LOCAL_CROP);

    }
    public void takePhotoOrSelectPicture() {
        CharSequence[] items = {"拍照","图库"};// 裁剪items选项
        // 弹出对话框提示用户拍照或者是通过本地图库选择图片
        android.app.AlertDialog.Builder builder=new android.app.AlertDialog.Builder(RecifyUploadActivity.this);
//        new AlertDialog.Builder(RecifyUploadActivity.this)
        builder.setTitle("请选择");
        builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        switch (which){
                            // 选择了拍照
                            case 0:
                                toCamera();
                                break;
                            // 调用系统图库
                            case 1:

                                toPhoto();
                                break;

                        }

                    }
                });
        builder.create().show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //加载图片
    public Bitmap getURLimage(String url) {
        Bitmap bmp = null;
        try {
            URL myurl = new URL(url);
            // 获得连接
            HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
            conn.setConnectTimeout(6000);//设置超时
            conn.setDoInput(true);
            conn.setUseCaches(false);//不缓存
            conn.connect();
            InputStream is = conn.getInputStream();//获得图片的数据流
            bmp = BitmapFactory.decodeStream(is);//读取图像数据
            //读取文本数据
            //byte[] buffer = new byte[100];
            //inputStream.read(buffer);
            //text = new String(buffer);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bmp;
    }
}
