package com.bjzc.bhzhgd.activity.qfgd;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.bjzc.bhzhgd.R;
import com.bjzc.bhzhgd.adapter.Q4ShowImagesGridAdapter;
import com.bjzc.bhzhgd.adapter.Q4UploadGridAdapter;
import com.bjzc.bhzhgd.base.BaseActivity3;
import com.bjzc.bhzhgd.bean.DeviceTreeBean;
import com.bjzc.bhzhgd.bean.Q4OptionBean;
import com.bjzc.bhzhgd.bean.ResultBeanQfSubmit;
import com.bjzc.bhzhgd.bean.XsRequestInfo;
import com.bjzc.bhzhgd.utils.CompressImageUtils;
import com.bjzc.bhzhgd.utils.NoProgresshttpUtils;
import com.bjzc.bhzhgd.weight.GlideEngine;
import com.bumptech.glide.Glide;
import com.bjzc.bhzhgd.bean.MessageEvent;
import com.bjzc.bhzhgd.bean.QxTjgdRequestBean;
import com.bjzc.bhzhgd.bean.UploadPhotosBean;
import com.bjzc.bhzhgd.contans.Contans;
import com.bjzc.bhzhgd.utils.GsonUtils;
import com.bjzc.bhzhgd.utils.HttpListener;
import com.bjzc.bhzhgd.utils.SPUtils;
import com.bjzc.bhzhgd.weight.InputLayout;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wanglu.photoviewerlibrary.PhotoViewer;
import com.yolanda.nohttp.FileBinary;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * Created by ruihong on 2018/4/17.
 */

public class TjqxdActivity extends BaseActivity3 {

    private int maxSelectNum = 6;
    //先定义
    private static final int REQUEST_EXTERNAL_STORAGE = 15;

    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.CAMERA"};

    private static final int REQUEST_AUDIO = 0;
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;


    private ArrayList<String> imagePaths = new ArrayList<>();
    ArrayList<String> finalList;
    ArrayList<File> uploadedFiles = new ArrayList<>();
    private Q4UploadGridAdapter gridAdapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private String qybh;
    private boolean isEdit = true;
    private String username;
    private String type = null;
    private QxTjgdRequestBean qxTjgdRequestBean;

    private ArrayList<Q4OptionBean.DataBean> statusOption = new ArrayList<>();
    private ArrayList<Q4OptionBean.DataBean> qxssbzOption = new ArrayList<>();
    private ArrayList<Q4OptionBean.DataBean> qxsszyOption = new ArrayList<>();
    private ArrayList<Q4OptionBean.DataBean> qkdjOption = new ArrayList<>();
    private ArrayList<Q4OptionBean.DataBean> qxdmOption = new ArrayList<>();
    private ArrayList<Q4OptionBean.DataBean> blgdOption = new ArrayList<>();
    private ArrayList<Q4OptionBean.DataBean> yqjOption = new ArrayList<>();


    GridView gridView;
    private Uri uri;
    InputLayout ilGdbh;
    //状态
    InputLayout ilStatus;
    //设备编号
    InputLayout ilSbbh;
    //设备名称
    InputLayout ilSbmc;
    //缺陷所属班组
    InputLayout ilQxsubz;
    //缺陷所属专业
    InputLayout ilQxzy;
    //许可地点
    InputLayout ilQkdj;
    //缺陷代码
    InputLayout ilQxdm;
    //是否为补录工单
    InputLayout ilBlgd;
    //优先级
    InputLayout ilYqj;
    //缺陷描述
    InputLayout etQxms;
    //工作内容
    InputLayout etGznz;
    //选择附件
    InputLayout ilXzfj;

    DeviceTreeBean.DataBean dataBean;
    private String status = "";
    private String sbbh = "";
    private String sbmc = "";
    private String qxssbz = "";
    private String qxsszy = "";
    private String qkdj = "";
    private String qxdm = "";
    private String blgd = "";
    private String yqj = "";
    static int imageTotals = 0;
    static int fileIndex = 0;
    private String DJID;
    private String DJMC;


    @Override
    public int getLayoutId() {
        return R.layout.activity_tjqxd;
    }

    @Override
    public void initView() {

        gridView = findViewById(R.id.gridView);
        ilGdbh = findViewById(R.id.il_gdbh);
        ilStatus = findViewById(R.id.il_status);
        ilSbbh = findViewById(R.id.il_sbbh);
        ilSbmc = findViewById(R.id.il_sbmc);
        ilQxsubz = findViewById(R.id.il_qxsubz);
        ilQxzy = findViewById(R.id.il_qxzy);
        ilQkdj = findViewById(R.id.il_qkdj);
        ilQxdm = findViewById(R.id.il_qxdm);
        ilBlgd = findViewById(R.id.il_blgd);
        ilYqj = findViewById(R.id.il_yqj);
        etQxms = findViewById(R.id.et_qxms);
        etGznz = findViewById(R.id.et_gznz);
        ilXzfj = findViewById(R.id.il_xzfj);


        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        isEdit = intent.getBooleanExtra("edit", true);
        type = intent.getStringExtra("type");
        username = (String) SPUtils.get(context, Contans.USERID, "");
        qybh = intent.getStringExtra("qybh");
        if (!isEdit) {
            initToolbar("提交缺陷工单", "", new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            qxTjgdRequestBean = intent.getParcelableExtra("bean");
        } else {
            initToolbar("提交缺陷工单", "提交", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TJTP("WK220627.0026");
                    TJ();
                }
            });
        }
    }

    @Override
    public void initData() {


        if (!isEdit) {
            ilStatus.setEnabled(false);
            ilSbbh.setEnabled(false);
            ilSbmc.setEnabled(false);
            ilQxsubz.setEnabled(false);
            ilQxzy.setEnabled(false);
            ilQkdj.setEnabled(false);
            ilQxdm.setEnabled(false);
            ilBlgd.setEnabled(false);
            ilYqj.setEnabled(false);
            etQxms.setEnabled(false);
            etGznz.setEnabled(false);
            if (qxTjgdRequestBean != null) {
                Log.i("app", "->>>>>>>>>>");
                Gson gson = new Gson();
                Log.i("app", gson.toJson(qxTjgdRequestBean));
                ilSbbh.setContent(qxTjgdRequestBean.getSBBH());
                ilSbmc.setContent(qxTjgdRequestBean.getSBMC());
                ilStatus.setContent(qxTjgdRequestBean.getSTATUS());
                ilQxsubz.setContent(qxTjgdRequestBean.getQXSSBZ());
                ilQxzy.setContent(qxTjgdRequestBean.getQXSSZY());
                ilQkdj.setContent(qxTjgdRequestBean.getQKDJ());
                ilQxdm.setContent(qxTjgdRequestBean.getQXDM());
                ilBlgd.setContent(qxTjgdRequestBean.getBLGD());
                ilYqj.setContent(qxTjgdRequestBean.getYQJ());
                etQxms.setContent(qxTjgdRequestBean.getQXMS());
                etGznz.setContent(qxTjgdRequestBean.getGZNZ());
            }
        } else {
            getOption("Q4GD_STATUS_GET");//状态
            getOption("Q4GD_QXSSBZ_GET");//缺陷所属班组
            getOption("Q4GD_QXSSZY_GET");//缺陷所属专业
            getOption("Q4GD_QKDJ_GET");//许可地点
            getOption("Q4GD_QXDM_GET");//缺陷代码
            getOption("Q4GD_BLGD_GET");//是否为补录工单
            getOption("Q4GD_YQJ_GET");//优先级
        }

        ilSbbh.setTvContentOnClickListener(new View.OnClickListener() {//设备名称
            @Override
            public void onClick(View v) {
                //DeviceTreeActivity
                //Intent intent = new Intent(TjqxdActivity.this, ComfirmSblistActivity.class);
                Intent intent = new Intent(TjqxdActivity.this, DeviceTreeActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        ilSbmc.setTvContentOnClickListener(new View.OnClickListener() {//设备名称
            @Override
            public void onClick(View v) {
                //DeviceTreeActivity
                //Intent intent = new Intent(TjqxdActivity.this, ComfirmSblistActivity.class);
                Intent intent = new Intent(TjqxdActivity.this, DeviceTreeActivity.class);
                startActivityForResult(intent, 1);
            }
        });

        //缺陷所属班组
        ilQxsubz.setTvContentOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TjqxdActivity.this, QfOptionActivity.class);
                intent.putExtra("optionType", "Q4GD_QXSSBZ_GET");
                intent.putParcelableArrayListExtra("options", qxssbzOption);
                startActivityForResult(intent, 2);
            }
        });
        //缺陷所属专业
        ilQxzy.setTvContentOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TjqxdActivity.this, QfOptionActivity.class);
                intent.putExtra("optionType", "Q4GD_QXSSZY_GET");
                intent.putParcelableArrayListExtra("options", qxsszyOption);
                startActivityForResult(intent, 3);
            }
        });

        //许可地点
        ilQkdj.setTvContentOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TjqxdActivity.this, QfOptionActivity.class);
                intent.putExtra("optionType", "Q4GD_QKDJ_GET");
                intent.putParcelableArrayListExtra("options", qkdjOption);
                startActivityForResult(intent, 4);
            }
        });

        //缺陷代码
        ilQxdm.setTvContentOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TjqxdActivity.this, QfOptionActivity.class);
                intent.putExtra("optionType", "Q4GD_QXDM_GET");
                intent.putParcelableArrayListExtra("options", qxdmOption);
                startActivityForResult(intent, 5);
            }
        });

        //优先级
        ilYqj.setTvContentOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TjqxdActivity.this, QfOptionActivity.class);
                intent.putExtra("optionType", "Q4GD_YQJ_GET");
                intent.putParcelableArrayListExtra("options", yqjOption);
                startActivityForResult(intent, 6);
            }
        });


        ilXzfj.setTvContentOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("audio/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, REQUEST_AUDIO);
            }
        });


        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);

        if (!isEdit) {
            if (qxTjgdRequestBean.getFiles() != null && qxTjgdRequestBean.getFiles().size() > 0) {

                imagePaths.clear();
                for (String imageUrl : qxTjgdRequestBean.getFiles()) {
                    imagePaths.add(imageUrl);
                }
                Q4ShowImagesGridAdapter gridShowImageAdapter = new Q4ShowImagesGridAdapter(imagePaths, TjqxdActivity.this);
                gridView.setAdapter(gridShowImageAdapter);

                gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        PhotoViewer.INSTANCE.setData(imagePaths).setCurrentPage(position).setImgContainer(gridView)
                                .setShowImageViewInterface((imageView, url) -> {
                                    //使用Glide显示图片
                                    Glide.with(TjqxdActivity.this)
                                            .load(Contans.Q4_MAGES_URL + url)
                                            .into(imageView);
                                }).start(TjqxdActivity.this);
                    }
                });
            }

        } else {
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String imgs = (String) parent.getItemAtPosition(position);
                    if ("paizhao".equals(imgs)) {
//                    PhotoPickerIntent intent = new PhotoPickerIntent(TjqxdActivity.this);
//                    intent.setSelectModel(SelectModel.MULTI);
//                    intent.setShowCarema(true); // 是否显示拍照
//                    intent.setMaxTotal(6); // 最多选择照片数量，默认为6
//                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
//                    startActivityForResult(intent, REQUEST_CAMERA_CODE);

                        //相册
                        PictureSelector.create(TjqxdActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(3)
                                .imageEngine(GlideEngine.createGlideEngine())
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);

//                    PictureSelector.create(TjqxdActivity.this)
//                            .openGallery(PictureMimeType.ofImage())
//                            .theme(R.style.picture_default_style)
//                            .imageEngine(GlideEngine.createGlideEngine())
//                            .forResult(PictureConfig.CHOOSE_REQUEST);

                    } else {
//                    PhotoPreviewIntent intent = new PhotoPreviewIntent(TjqxdActivity.this);
//                    intent.setCurrentItem(positionTemp);
//                    intent.setPhotoPaths(imagePaths);
//                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);

                        // 预览图片 可自定长按保存路径
                        //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                        PictureSelector.create(TjqxdActivity.this).externalPicturePreview(position, selectList, 0);
                    }
                }
            });

            imagePaths.add("paizhao");
            gridAdapter = new Q4UploadGridAdapter(imagePaths, TjqxdActivity.this, new Q4UploadGridAdapter.OnItemDelClickListener() {
                @Override
                public void onClick(int position) {
                    showToast(String.valueOf(position));
                }
            });
            gridView.setAdapter(gridAdapter);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) {
        ilSbmc.setContent(messageEvent.getMessage());
        ilSbbh.setContent(messageEvent.getMessageid());
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {
                        dataBean = bundle.getParcelable("dataBean");
                        if (dataBean != null && dataBean.getID() != null) {
                            ilSbbh.setContent(dataBean.getID());
                            sbbh = dataBean.getID();
                        }
                        if (dataBean != null && dataBean.getNNAME() != null) {
                            ilSbmc.setContent(dataBean.getNNAME());
                            sbmc = dataBean.getNNAME();
                        }
                    }
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    qxssbz = bundle.getString("XLID");
                    ilQxsubz.setContent(bundle.getString("XLMC"));
                }
                break;
            case 3:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    qxsszy = bundle.getString("XLID");
                    ilQxzy.setContent(bundle.getString("XLMC"));
                }
                break;
            case 4:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    qkdj = bundle.getString("XLID");
                    ilQkdj.setContent(bundle.getString("XLMC"));
                }
                break;
            case 5:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    qxdm = bundle.getString("XLID");
                    ilQxdm.setContent(bundle.getString("XLMC"));
                }
                break;
            case 6:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    yqj = bundle.getString("XLID");
                    ilYqj.setContent(bundle.getString("XLMC"));
                }
                break;
            case REQUEST_AUDIO:
                if (resultCode == RESULT_OK) {
//                    uri = data.getData();
//                    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
//                    cursor.moveToFirst();
//                    filePath = cursor.getString(1); // 文件路径
//                    file = new File(filePath);
//                    filetype = file.getName().substring(file.getName().lastIndexOf(".") + 1);
//
//                    if (filetype.equals("doc") || filetype.equals("docx") || filetype.equals("xls")
//                            || filetype.equals("xlsx") || filetype.equals("ppt") || filetype.equals("pptx") || filetype.equals("pdf")) {
//                        uploadfiletype = "10001";
//
//                    } else if (filetype.equals("flv") || filetype.equals("mp4")) {
//
//                        uploadfiletype = "10002";
//                    }
//
//                    try {
//                        fileSize = formetFileSize(getFileSize(file));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    ilXzfj.setContent(file.getName());
                }
                break;
//            case REQUEST_CAMERA_CODE:
//                if (resultCode == RESULT_OK) {
//                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
//                    loadAdpater(list);
//                }
//                break;
            case PictureConfig.CHOOSE_REQUEST:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> images = PictureSelector.obtainMultipleResult(data);
                    ArrayList<String> imagePathTemp = new ArrayList<>();
                    selectList.clear();
                    selectList.addAll(images);
                    for (LocalMedia localMedia : images) {
                        imagePathTemp.add(localMedia.getPath());
                    }
                    loadAdpater(imagePathTemp);
                }
                break;
//            case REQUEST_PREVIEW_CODE:
//                if (resultCode == RESULT_OK) {
//                    ArrayList<String> ListExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
//                    loadAdpater(ListExtra);
//                }
//                break;
        }
    }

    /**
     * ˙
     * 计算文件的大小
     *
     * @param fileS
     * @return
     */
    public String formetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    public static long getFileSize(File file) {
        if (file == null) {
            return 0;
        }
        long size = 0;
        try {
            if (file.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
            }
        } catch (Exception e) {
            size = 0;
        }
        return size;
    }

    private void TJ() {

        if (ilSbbh.getContent().equals("") || etQxms.getContent().equals("") || ilQxsubz.getContent().equals("") || ilQxzy.getContent().equals("") || ilQkdj.getContent().equals("")
                || ilQxdm.getContent().equals("") || ilBlgd.getContent().equals("") || ilYqj.getContent().equals("") || ilStatus.getContent().equals("") || etQxms.getContent().equals("")) {
            showToast("请填写好必填项");
        } else {

            final com.yolanda.nohttp.rest.Request<String> requset = NoHttp.createStringRequest(Contans.IP + Contans.TJQFGD, RequestMethod.POST);
            requset.setDefineRequestBodyForJson(createJson());
            NoProgresshttpUtils.getInstance().add(this, 0, requset, new HttpListener<String>() {
                @Override
                public void onSucceed(int what, com.yolanda.nohttp.rest.Response<String> response) {
                    try {
                        ResultBeanQfSubmit resultbean = GsonUtils.GsonToBean(response.get(), ResultBeanQfSubmit.class);
                        Log.i("app", new Gson().toJson(resultbean));
                        if (resultbean.getState() == 1) {
                            if (resultbean.getData() != null && resultbean.getData().size() > 0) {
                                TjqxdActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ResultBeanQfSubmit.DataBean bean = resultbean.getData().get(0);
                                        String gdid = bean.getGdid();
                                        finalList = new ArrayList<>();
                                        finalList.addAll(imagePaths);
                                        if (finalList.contains("paizhao")) {
                                            finalList.remove("paizhao");
                                        }
                                        if (finalList.size() > 0) {
                                            TJTP(gdid);
                                        } else {
                                            showToast("缺陷工单提交成功");
                                            finish();
                                        }
                                    }
                                });
                            }
                        } else {
                            showToast("提交失败,请稍后再试试");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailed(int what, com.yolanda.nohttp.rest.Response<String> response) {

                }
            });
        }
    }

    private void TJTP(String gdid) {

        finalList = new ArrayList<>();
        finalList.addAll(imagePaths);
        if (finalList.contains("paizhao")) {
            finalList.remove("paizhao");
        }

        uploadedFiles.clear();
        imageTotals = 0;
        fileIndex = 0;
        String substring = finalList.toString().substring(1, finalList.toString().length() - 1);

        Log.i("app", substring);

        if (substring.contains(",")) {

            CompressImageUtils.LoadingDialog.showDialog(this);
            String[] split = substring.split(",");

            for (String imagePath : split) {
                fileIndex++;
                String imagePathTemp = imagePath.trim();
                Uri uri = Uri.parse(imagePathTemp);
                String filePath = getRealPath(uri);
                Log.i("app", filePath);
                File fileImage = new File(filePath);

                String filetype = fileImage.getName().substring(fileImage.getName().lastIndexOf(".") + 1);
                Log.i("app", "---------------");
                Log.i("app", filetype);
                Log.i("app", filePath);
                Log.i("app", String.valueOf(fileImage.length()));
                Log.i("app", "--------------->");
                Luban.with(this)
                        .load(fileImage)                                   // 传人要压缩的图片列表
                        .ignoreBy(1024)                                  // 忽略不压缩图片的大小
                        .setTargetDir(CompressImageUtils.BitmapUtils.getFilePath())                        // 设置压缩后文件存储位置
                        .setCompressListener(new OnCompressListener() { //设置回调
                            @Override
                            public void onStart() {
                                // TODO 压缩开始前调用，可以在方法内启动 loading UI
                            }

                            @Override
                            public void onSuccess(File file) {
                                // TODO 压缩成功后调用，返回压缩后的图片文件

                                TjqxdActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // refresh ui 的操作代码
                                        Log.i("app", String.valueOf(file.length()));
                                        Log.i("app", file.getAbsolutePath());
                                        Log.i("app", file.getName());
                                        Log.i("app", "<--------------->");
                                        imageTotals++;
                                        uploadedFiles.add(file);
                                        if (imageTotals == split.length) {
                                            uploadCompressImages(gdid);
                                        }
                                    }
                                });
                            }

                            @Override
                            public void onError(Throwable e) {
                                // TODO 当压缩过程出现问题时调用
                            }
                        }).launch();    //启动压缩


//                    CompressImageUtils.ImageCompressTask compressTask = new CompressImageUtils.ImageCompressTask(context, new CompressImageUtils.ImageCompressTask.CompressListener() {
//                        @Override
//                        public void Success(String imagePath) {
//                            if (imagePath != null) {
//                                imageTotals++;
//
//                                File fileCompressImage = new File(imagePath);
//                                uploadedFiles.add(fileCompressImage);
//                                Log.i("app", fileCompressImage.getName());
//                                Log.i("app", String.valueOf(fileCompressImage.length()));
//                                Log.i("app","<--------------->");
//                                RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), fileCompressImage);
//                                builder.addFormDataPart("file" + fileIndex, fileCompressImage.getName(), imageBody);
//                                if (imageTotals == split.length) {
//                                    Log.i("app",String.valueOf(uploadedFiles.size()));
//                                    cursor.close();
//                                    CompressImageUtils.LoadingDialog.dismissDialog();
//                                    uploadCompressImages(builder, gdid);
//                                }
//                            }
//                        }
//
//                        @Override
//                        public void onProgressUpdate(Integer... values) {
//
//                        }
//                    });
//                    compressTask.execute(filePath, file.getName());


            }

        } else {

            CompressImageUtils.LoadingDialog.showDialog(this);
            Uri uri = Uri.parse(substring);
            String filePath = getRealPath(uri);
            Log.i("app", filePath);
            File fileImage = new File(filePath);

            Luban.with(this)
                    .load(fileImage)                                   // 传人要压缩的图片列表
                    .ignoreBy(1024)                                  // 忽略不压缩图片的大小
                    .setTargetDir(CompressImageUtils.BitmapUtils.getFilePath())                        // 设置压缩后文件存储位置
                    .setCompressListener(new OnCompressListener() { //设置回调
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        }

                        @Override
                        public void onSuccess(File file) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件

                            TjqxdActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // refresh ui 的操作代码
                                    Log.i("app", String.valueOf(file.length()));
                                    Log.i("app", file.getAbsolutePath());
                                    Log.i("app", file.getName());
                                    Log.i("app", "<--------------->");
                                    imageTotals++;
                                    uploadedFiles.add(file);
                                    CompressImageUtils.LoadingDialog.dismissDialog();
                                    uploadCompressImages(gdid);
                                }
                            });
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                        }
                    }).launch();    //启动压缩
        }
    }

    private String getRealPath(Uri fileUrl) {
        String filePath = "";
        if (fileUrl != null) {
            if (fileUrl.getScheme().toString().compareTo("content") == 0) // content://开头的uri
            {
                Cursor cursor = this.getContentResolver().query(fileUrl, null, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    try {
                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        filePath = cursor.getString(column_index); // 取出文件路径
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } finally {
                        cursor.close();
                    }
                }
            } else if (fileUrl.getScheme().compareTo("file") == 0) // file:///开头的uri
            {
                filePath = fileUrl.getPath();
            }
        }
        return filePath;
    }

    private void uploadCompressImages(String gdid) {

        Request<String> requset = NoHttp.createStringRequest(Contans.IP + Contans.Q4GD_IMG, RequestMethod.POST);
        requset.add("gdid", gdid);
        requset.add("action", "Q4GD_ADD");

        for (int i = 0; i < uploadedFiles.size(); i++) {
            File file = uploadedFiles.get(i);
            requset.add("file" + i, new FileBinary(file));
        }

        NoProgresshttpUtils.getInstance().add(this, 0, requset, new HttpListener<String>() {
            @Override
            public void onSucceed(int what, com.yolanda.nohttp.rest.Response<String> response) {
                try {
                    String result = response.get();
                    Log.i("app", result);
                    UploadPhotosBean uploadPhotosBean = GsonUtils.GsonToBean(result, UploadPhotosBean.class);
                    if (uploadPhotosBean.getState() == 1) {
                        TjqxdActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CompressImageUtils.LoadingDialog.dismissDialog();
                                showToast("上传数据成功");
                                finish();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {

            }
        });
    }

    private String createJson() {
        QxTjgdRequestBean info = new QxTjgdRequestBean();
        info.setAction("Q4GD_ADD");
        info.setSTATUS(status);
        info.setQybh(qybh);
        info.setSBBH(sbbh);
        info.setSBMC(sbmc);
        info.setQXSSBZ(qxssbz);
        info.setQXSSZY(qxsszy);
        info.setQKDJ(qkdj);
        info.setQXDM(qxdm);
        info.setBLGD(blgd);
        info.setYQJ(yqj);
        info.setTJR(username);
        info.setQXMS(etQxms.getContent());
        info.setGZNZ(etGznz.getContent());
        String json = GsonUtils.GsonString(info);
        Log.i("app", json);
        return json;
    }

    private String createJsonOptions(String type) {
        XsRequestInfo info = new XsRequestInfo();
        info.setAction(type);
        String json = GsonUtils.GsonString(info);
        Log.i("app", json);
        return json;
    }

    private void loadAdpater(ArrayList<String> paths) {
        if (imagePaths != null && imagePaths.size() > 0) {
            imagePaths.clear();
        }
        if (paths.contains("paizhao")) {
            paths.remove("paizhao");
        }
        paths.add("paizhao");
        imagePaths.addAll(paths);
//        if(imagePaths!=null&&imagePaths.size()>6){
//            ArrayList<String> pathsTemp = new ArrayList<>();
//            for(int i=0;i<imagePaths.size();i++){
//                if(i<6){
//                    pathsTemp.add(imagePaths.get(i));
//                }
//            }
//            imagePaths.clear();
//            imagePaths.addAll(pathsTemp);
//            imagePaths.add("paizhao");
//            showToast("上传照片不能超过6张");
//        }else{
//            imagePaths.add("paizhao");
//        }
        gridAdapter = new Q4UploadGridAdapter(imagePaths, TjqxdActivity.this, new Q4UploadGridAdapter.OnItemDelClickListener() {
            @Override
            public void onClick(int position) {
                if (selectList != null && selectList.size() > 0) {
                    if (imagePaths != null && imagePaths.size() > 0) {
                        String imagePath = imagePaths.get(position);
                        imagePaths.remove(position);
                        for (LocalMedia localMedia : selectList) {
                            if (localMedia.getPath().equals(imagePath)) {
                                selectList.remove(localMedia);
                                ArrayList<String> imagePathsTemp = new ArrayList<>();
                                imagePathsTemp.addAll(imagePaths);
                                loadAdpater(imagePathsTemp);
                                break;
                            }
                        }
                    }
                }
            }
        });
        gridView.setAdapter(gridAdapter);
    }

//    private class GridAdapter extends BaseAdapter {
//        private ArrayList<String> listUrls;
//        private LayoutInflater inflater;
//        private OnItemDelClickListener onItemDelClickListener;
//
//        public interface OnItemDelClickListener {
//            void onClick(int position);
//        }
//
//        public GridAdapter(ArrayList<String> listUrls) {
//            this.listUrls = listUrls;
//            if (listUrls.size() == 7) {
//                listUrls.remove(listUrls.size() - 1);
//            }
//            //这个意思就是 如果最后返回的列表有7哥 就把最后一个移除了
//            inflater = LayoutInflater.from(TjqxdActivity.this);
//        }
//
//        public int getCount() {
//            return listUrls.size();
//        }
//
//        @Override
//        public String getItem(int position) {
//            return listUrls.get(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            return position;
//        }
//
//        @Override
//        public View getView(int position, View convertView, ViewGroup parent) {
//            ViewHolder holder = null;
//            if (convertView == null) {
//                holder = new ViewHolder();
//                convertView = inflater.inflate(R.layout.sblcsave_item, parent, false);
//                holder.image = (ImageView) convertView.findViewById(R.id.imageView);
//                holder.ll_del = (LinearLayout) convertView.findViewById(R.id.ll_del);
//                convertView.setTag(holder);
//            } else {
//                holder = (ViewHolder) convertView.getTag();
//            }
//
//            final String path = listUrls.get(position);
//            //这里是如果取到path的值是paizhao  就显示加好  如果不是  就是返回的那个图片
//            if (path.equals("paizhao")) {
//                holder.image.setImageResource(R.mipmap.find_add_img);
//                holder.ll_del.setVisibility(View.GONE);
//            } else {
//                holder.ll_del.setVisibility(View.VISIBLE);
//                RequestOptions options = new RequestOptions()
//                        .centerCrop()
//                        .placeholder(R.color.color_f6)
//                        .diskCacheStrategy(DiskCacheStrategy.ALL);
//                Glide.with(TjqxdActivity.this)
//                        .load(path)
//                        .apply(options)
//                        .into(holder.image);
//
////
////                Glide.with(TjqxdActivity.this)
////                        .load(path)
////                        .placeholder(R.mipmap.default_error)
////                        .error(R.mipmap.default_error)
////                        .centerCrop()
////                        .into(holder.image);
//            }
//
//            holder.ll_del.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    //int index = holder.getAdapterPosition();
//                    // 这里有时会返回-1造成数据下标越界,具体可参考getAdapterPosition()源码，
//                    // 通过源码分析应该是bindViewHolder()暂未绘制完成导致，知道原因的也可联系我~感谢
//                    if (position >=0) {
//                        listUrls.remove(position);
//                        this.notify();
////                        gridView.n
////                        notifyItemRemoved(position);
////                        notifyItemRangeChanged(index, list.size());
////                        Log.i("delete position:", index + "--->remove after:" + list.size());
//                    }
//                }
//            });
//
//            return convertView;
//        }
//
//        class ViewHolder {
//            ImageView image;
//            LinearLayout ll_del;
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public static String StringFilter(String str) throws PatternSyntaxException {

        String regEx = "[`~!_@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    private void getOption(String type) {

        final com.yolanda.nohttp.rest.Request<String> requset = NoHttp.createStringRequest(Contans.IP + Contans.QFGETOPTION, RequestMethod.POST);
        requset.setDefineRequestBodyForJson(createJsonOptions(type));
        NoProgresshttpUtils.getInstance().add(this, 0, requset, new HttpListener<String>() {
            @Override
            public void onSucceed(int what, com.yolanda.nohttp.rest.Response<String> response) {
                try {
                    Q4OptionBean bean = GsonUtils.GsonToBean(response.get(), Q4OptionBean.class);
                    if (bean.getState() == 1) {
                        TjqxdActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (type.equals("Q4GD_STATUS_GET")) {
                                    //状态
                                    statusOption.clear();
                                    statusOption.addAll(bean.getData());
                                    if (statusOption.size() > 0) {
                                        ilStatus.setContent(statusOption.get(0).getXLMC());
                                        status = statusOption.get(0).getXLID();
                                    }
                                } else if (type.equals("Q4GD_QXSSBZ_GET")) {
                                    //缺陷所属班组
                                    qxssbzOption.clear();
                                    qxssbzOption.addAll(bean.getData());
                                    if (qxssbzOption.size() > 0) {
                                        ilQxsubz.setContent(qxssbzOption.get(0).getXLMC());
                                        qxssbz = qxssbzOption.get(0).getXLID();
                                    }
                                } else if (type.equals("Q4GD_QXSSZY_GET")) {
                                    //缺陷所属专业
                                    qxsszyOption.clear();
                                    qxsszyOption.addAll(bean.getData());
                                    if (qxsszyOption.size() > 0) {
                                        ilQxzy.setContent(qxsszyOption.get(0).getXLMC());
                                        qxsszy = qxsszyOption.get(0).getXLID();
                                    }
                                } else if (type.equals("Q4GD_QKDJ_GET")) {
                                    //许可地点
                                    qkdjOption.clear();
                                    qkdjOption.addAll(bean.getData());
                                    if (qkdjOption.size() > 0) {
                                        ilQkdj.setContent(qkdjOption.get(0).getXLMC());
                                        qkdj = qkdjOption.get(0).getXLID();
                                    }
                                } else if (type.equals("Q4GD_QXDM_GET")) {
                                    //缺陷代码
                                    qxdmOption.clear();
                                    qxdmOption.addAll(bean.getData());
                                    if (qxdmOption.size() > 0) {
                                        ilQxdm.setContent(qxdmOption.get(1).getXLMC());
                                        qxdm = qxdmOption.get(1).getXLID();
                                    }
                                } else if (type.equals("Q4GD_BLGD_GET")) {
                                    //是否为补录工单
                                    blgdOption.clear();
                                    blgdOption.addAll(bean.getData());
                                    if (blgdOption.size() > 0) {
                                        ilBlgd.setContent(blgdOption.get(0).getXLMC());
                                        blgd = blgdOption.get(0).getXLID();
                                    }
                                } else if (type.equals("Q4GD_YQJ_GET")) {
                                    //优先级
                                    yqjOption.clear();
                                    yqjOption.addAll(bean.getData());
                                    if (yqjOption.size() > 0) {
                                        ilYqj.setContent(yqjOption.get(0).getXLMC());
                                        yqj = yqjOption.get(0).getXLID();
                                    }
                                }
                            }
                        });
                    } else {
                        showToast("提交失败,请稍后再试试");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(int what, com.yolanda.nohttp.rest.Response<String> response) {

            }
        });
    }
}

