package com.zztrapp.zztrapp.ui.index.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Environment;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.github.gzuliyujiang.filepicker.FilePicker;
import com.github.gzuliyujiang.filepicker.annotation.ExplorerMode;
import com.github.gzuliyujiang.filepicker.contract.OnFilePickedListener;
import com.github.gzuliyujiang.wheelpicker.DatePicker;
import com.github.gzuliyujiang.wheelpicker.contract.OnDatePickedListener;
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity;
import com.github.gzuliyujiang.wheelpicker.widget.DateWheelLayout;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.utils.DateUtils;
import com.zztrapp.zztrapp.R;
import com.zztrapp.zztrapp.base.BaseActivity;
import com.zztrapp.zztrapp.bean.FileBean;
import com.zztrapp.zztrapp.bean.HttpResult;
import com.zztrapp.zztrapp.bean.RcrwPagelistBean;
import com.zztrapp.zztrapp.bean.UpLoadFileBean;
import com.zztrapp.zztrapp.databinding.ActivityAddDailyTasksBinding;
import com.zztrapp.zztrapp.download.TCallBackUtil;
import com.zztrapp.zztrapp.download.TOkhttpUtil;
import com.zztrapp.zztrapp.http.HttpApi;
import com.zztrapp.zztrapp.http.HttpMethods;
import com.zztrapp.zztrapp.http.ISubscriberOnNextListener;
import com.zztrapp.zztrapp.http.ProgressSubscriber;
import com.zztrapp.zztrapp.http.RxApiManager;
import com.zztrapp.zztrapp.ui.currency.adapter.GridImageAdapter;
import com.zztrapp.zztrapp.ui.currency.adapter.UpLoadFileAdapter;
import com.zztrapp.zztrapp.utilcode.mUtil.GlideEngine;
import com.zztrapp.zztrapp.utilcode.mUtil.MyGlideEngine;
import com.zztrapp.zztrapp.utilcode.util.SizeUtils;
import com.zztrapp.zztrapp.utilcode.util.ToastUtils;
import com.zztrapp.zztrapp.widget.DecimalDigitsInputFilter;
import com.zztrapp.zztrapp.widget.FullyGridLayoutManager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;
import top.zibin.luban.OnRenameListener;

public class AddDailyTasksActivity extends BaseActivity {

    private ActivityAddDailyTasksBinding binding;

    private int jumpType = 1;//0 添加 1 编辑 2详情
    private int type = 1;//1 黑臭水体 2 生活污水处理设施
    private String pid;//关联id、黑臭水体id/生活污水处理id
    private RcrwPagelistBean.RecordsBean detail;

    private UpLoadFileAdapter clscFileAdapter;//文件--现场材料上传
    //材料上传
    private List<UpLoadFileBean> clscFileList = new ArrayList<>();

    @Override
    public View getLayoutId() {
        return binding.getRoot();
    }

    @Override
    protected void initBinding() {
        binding = ActivityAddDailyTasksBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void init() {
        jumpType = getIntent().getIntExtra("jumpType", 0);
        pid = getIntent().getStringExtra("pid");
        binding.navView.navTitle.setText(getIntent().getStringExtra("navName"));
        binding.navView.navBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //文件--现场材料上传
        binding.rvClscFile.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        clscFileAdapter = new UpLoadFileAdapter(this, jumpType);
        binding.rvClscFile.setAdapter(clscFileAdapter);

        initSelectImage();//初始化上传图片相关

        binding.jd.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 6)});
        binding.wd.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(2, 6)});

        if (jumpType == 2) {//查看详情
            binding.rwmc.setEnabled(false);
            binding.rwr.setEnabled(false);
            binding.jd.setEnabled(false);
            binding.wd.setEnabled(false);
            binding.fxwt.setEnabled(false);
            binding.wtms.setEnabled(false);

            binding.clscBt.setVisibility(View.GONE);
            binding.bottomView.setVisibility(View.GONE);
        }


        if (jumpType != 0) {
            detail = (RcrwPagelistBean.RecordsBean) getIntent().getSerializableExtra("detail");
            binding.rwmc.setText(detail.getRwmc());
            binding.rwsj.setText(detail.getRwsj());
            binding.rwr.setText(detail.getRmr());
            binding.jd.setText(detail.getJd());
            binding.wd.setText(detail.getWd());
            binding.fxwt.setText(detail.getFxwt());
            binding.wtms.setText(detail.getWtms());
            //问题照片
            if (detail.getWtzpFile() != null && detail.getWtzpFile().size() > 0) {
                for (int i = 0; i < detail.getWtzpFile().size(); i++) {
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPath(detail.getWtzpFile().get(i).getFilePath());
                    localMedia.setFileName(detail.getWtzpFile().get(i).getFileName());
                    wtzpImgList.add(localMedia);
                }
                wtzpAdapter.setList(wtzpImgList);
                wtzpAdapter.notifyDataSetChanged();
            }
            //材料上传
            if (detail.getClscFile() != null && detail.getClscFile().size() > 0) {
                clscFileList = detail.getClscFile();
                clscFileAdapter.setData(clscFileList);
                clscFileAdapter.notifyDataSetChanged();
            }
        }

    }

    @Override
    protected void initOnClick() {
        binding.cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        binding.save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("rwmc", binding.rwmc.getText().toString());
                map.put("rmr", binding.rwr.getText().toString());//接口参数rmr m_w
                map.put("rwsj", binding.rwsj.getText().toString());
                map.put("jd", binding.jd.getText().toString());
                map.put("wd", binding.wd.getText().toString());
                map.put("fxwt", binding.fxwt.getText().toString());
                map.put("wtms", binding.wtms.getText().toString());
                map.put("type", type);
                map.put("pid", pid);
                //图片相关
                //问题照片
                wtzpFileList.clear();
                for (int i = 0; i < wtzpImgList.size(); i++) {
                    UpLoadFileBean upLoadFileBean = new UpLoadFileBean();
                    upLoadFileBean.setFilePath(wtzpImgList.get(i).getPath());
                    upLoadFileBean.setFileName(wtzpImgList.get(i).getFileName());
                    wtzpFileList.add(upLoadFileBean);
                }
                map.put("wtzpFile", wtzpFileList);
                map.put("clscFile", clscFileList);

                if (jumpType == 0) {
                    addRcrw(map);
                } else {//1
                    map.put("id", detail.getId());
                    editRcrw(map);
                }
            }
        });
        //时间选择
        binding.rwsjView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (jumpType == 2) {
                    return;
                }
                DatePicker picker = new DatePicker(AddDailyTasksActivity.this);
                DateWheelLayout wheelLayout = picker.getWheelLayout();
                String time = binding.rwsj.getText().toString();
                if (!TextUtils.isEmpty(time)) {
                    String[] split = time.split("-");
                    DateEntity dateEntity = new DateEntity();
                    dateEntity.setYear(Integer.parseInt(split[0]));
                    dateEntity.setMonth(Integer.parseInt(split[1]));
                    dateEntity.setDay(Integer.parseInt(split[2]));
                    wheelLayout.setDefaultValue(dateEntity);
                }
                picker.getWheelLayout().setResetWhenLinkage(false);
                picker.setOnDatePickedListener(new OnDatePickedListener() {
                    @Override
                    public void onDatePicked(int year, int month, int day) {
                        binding.rwsj.setText(year + "-" + month + "-" + day);
                    }
                });
                picker.show();
            }
        });

        //材料上传
        clscFileAdapter.setOnItemClickListener(new UpLoadFileAdapter.OnItemClickListener() {
            @Override
            public void onDelClick(int position) {
                clscFileList.remove(position);
                clscFileAdapter.notifyDataSetChanged();
            }

            @Override
            public void onDownloadClick(String filePath, String fileName) {
                downloadHintDialog(filePath, fileName);
            }
        });
        binding.clscBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openFileSelector();
            }
        });
    }

    //添加任务
    private void addRcrw(HashMap<String, Object> map) {
        ISubscriberOnNextListener<HttpResult<String>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<String>>() {

            @Override
            public void onNext(HttpResult<String> httpResult) {
                if (httpResult.getCode() == 200) {
                    finish();
                } else {
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<String>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, this, true);
        RxApiManager.get().add("addRcrw", httpResultProgressSubscriber);
        HttpMethods.getInstance(this).addRcrw(httpResultProgressSubscriber, map);
    }

    //编辑任务
    private void editRcrw(HashMap<String, Object> map) {
        ISubscriberOnNextListener<HttpResult<String>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<String>>() {

            @Override
            public void onNext(HttpResult<String> httpResult) {
                if (httpResult.getCode() == 200) {
                    finish();
                } else {
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<String>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, this, true);
        RxApiManager.get().add("editRcrw", httpResultProgressSubscriber);
        HttpMethods.getInstance(this).editRcrw(httpResultProgressSubscriber, map);
    }


    //--------------------------------上传文件相关---------------------------------
    //下载提示Dialog
    private void downloadHintDialog(String filePath, String fileName) {
        AlertDialog.Builder alertdialogbuilder = new AlertDialog.Builder(this);
        alertdialogbuilder.setMessage("是否下载该文件");
        alertdialogbuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                downLoadFile(filePath, fileName);
            }
        });
        alertdialogbuilder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        final AlertDialog alertdialog1 = alertdialogbuilder.create();
        alertdialog1.show();
    }

    /**
     * 打开本地文件器
     */
    private void openFileSelector() {
        FilePicker picker = new FilePicker(this);
//        picker.setInitDir(ExplorerMode.FILE,getExternalFilesDir(null));
        picker.setInitDir(ExplorerMode.FILE, new File(Environment.getExternalStorageDirectory().getAbsolutePath()));
        picker.setOnFilePickedListener(new OnFilePickedListener() {
            @Override
            public void onFilePicked(@NonNull File file) {
                uploadftp(file);
            }
        });
        picker.show();
    }

    //上传文件
    private void uploadftp(File file) {
        ISubscriberOnNextListener<HttpResult<FileBean>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<FileBean>>() {

            @Override
            public void onNext(HttpResult<FileBean> httpResult) {
                if (httpResult.getCode() == 200) {
                    UpLoadFileBean upLoadFileBean = new UpLoadFileBean();
                    upLoadFileBean.setFilePath(httpResult.getResult().getFileName());
                    upLoadFileBean.setFileName(httpResult.getResult().getOrgName());
                    clscFileList.add(upLoadFileBean);
                    clscFileAdapter.setData(clscFileList);
                } else {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<FileBean>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, this, true);
        RxApiManager.get().add("uploadftp", httpResultProgressSubscriber);
        HttpMethods.getInstance(this).uploadftp(httpResultProgressSubscriber, file);

    }

    //下载文件
    private void downLoadFile(String filePath, String fileName) {
        HashMap<String, String> map = new HashMap<>();
//        String appPath = Environment.getExternalStorageDirectory().getAbsolutePath();//手机内存的根目录
        String appPath = getApplicationContext().getFilesDir().getAbsolutePath();//此APP的files路径

        String p = "?filePath=";
        TOkhttpUtil.okHttpDownloadFile(HttpApi.BASE_URL + HttpApi.DOWNLOAD_FTP + p + filePath, map, new TCallBackUtil.TCallBackFile(appPath, fileName) {
            @Override
            public void onFailure(Call call, Exception e) {
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("打开失败,请稍后重试");
            }

            @Override
            public void onResponse(File response) {
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("下载成功，已保存到手机");
            }
        });
    }

    //--------------------------------上传文件相关-end---------------------------------


    //--------------------------------上传照片相关---------------------------------
    //问题照片
    private List<UpLoadFileBean> wtzpFileList = new ArrayList<>();
    private ArrayList<LocalMedia> wtzpImgList = new ArrayList<>();
    private GridImageAdapter wtzpAdapter;
    private List<LocalMedia> selectMediaPicList;//选择的相册图片
    private Dialog mDialog;

    //图片处理
    private void initSelectImage() {
        mDialog = initProgressDialog(this, "");
        //图片
        FullyGridLayoutManager xcfxwtzpManager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        binding.rvWtzpFile.setLayoutManager(xcfxwtzpManager);
        binding.rvWtzpFile.addItemDecoration(new GridSpacingItemDecoration(4, SizeUtils.dp2px(8), false));
//        binding.rvWtzpFile.addItemDecoration(new GridSpacingItemDecoration(4, ScreenUtils.dip2px(this, 8), false));
        wtzpAdapter = new GridImageAdapter(this, 8, jumpType);
        wtzpAdapter.setSelectMax(8);
        binding.rvWtzpFile.setAdapter(wtzpAdapter);
        wtzpAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onAddPicClick(int position) {
                if (position == 0) {
                    //从相册中选取图片
                    select_photo(8);
                }
                if (position == 1) {
                    //从相册中选取图片
                    select_photo(7);
                }
                if (position == 2) {
                    //从相册中选取图片
                    select_photo(6);
                }
                if (position == 3) {
                    //从相册中选取图片
                    select_photo(5);
                }
                if (position == 4) {
                    //从相册中选取图片
                    select_photo(4);
                }
                if (position == 5) {
                    //从相册中选取图片
                    select_photo(3);
                }
                if (position == 6) {
                    //从相册中选取图片
                    select_photo(2);
                }
                if (position == 7) {
                    //从相册中选取图片
                    select_photo(1);
                }
            }

            @Override
            public void onDelPicClick(int position) {
                wtzpImgList.remove(position);
                wtzpAdapter.notifyDataSetChanged();
            }

            @Override
            public void onPicClick(int position) {
                PictureSelector.create(AddDailyTasksActivity.this)
                        .openPreview()
                        .setImageEngine(MyGlideEngine.createGlideEngine())
                        .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
                            @Override
                            public void onPreviewDelete(int position) {

                            }

                            @Override
                            public boolean onLongPressDownload(LocalMedia media) {
                                return false;
                            }
                        }).startActivityPreview(0, false, wtzpImgList);

            }
        });
    }

    /**
     * 从相册中获取图片
     */
    public void select_photo(int maxSelectNum) {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())

                .setCompressEngine(new ImageFileCompressEngine())// 压缩
//                .openSystemGallery(SelectMimeType.ofImage())

                .setCameraImageFormat(PictureMimeType.JPG)// 相机图片格式后缀,默认.jpeg
                .setMaxSelectNum(maxSelectNum)// 最大图片选择数量

                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        selectMediaPicList = result;
                        if (!mDialog.isShowing()) {
                            mDialog.show();
                        }
                        uploadftp(0);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    /**
     * 自定义压缩
     */
    private static class ImageFileCompressEngine implements CompressFileEngine {

        @Override
        public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
            Luban.with(context).load(source).ignoreBy(100).setRenameListener(new OnRenameListener() {
                @Override
                public String rename(String filePath) {
                    int indexOf = filePath.lastIndexOf(".");
                    String postfix = indexOf != -1 ? filePath.substring(indexOf) : ".jpg";
                    return DateUtils.getCreateFileName("CMP_") + postfix;
                }
            }).setCompressListener(new OnNewCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(String source, File compressFile) {
                    if (call != null) {
                        call.onCallback(source, compressFile.getAbsolutePath());
                    }
                }

                @Override
                public void onError(String source, Throwable e) {
                    if (call != null) {
                        call.onCallback(source, null);
                    }
                }
            }).launch();
        }
    }

    //上传图片
    private void uploadftp(int index) {
        if (index == (selectMediaPicList.size())) {
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }
        } else {
            ISubscriberOnNextListener<HttpResult<FileBean>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<FileBean>>() {

                @Override
                public void onNext(HttpResult<FileBean> httpResult) {
                    if (httpResult.getCode() == 200) {
                        LocalMedia localMedia = new LocalMedia();
                        localMedia.setPath(httpResult.getResult().getFileName());
                        localMedia.setFileName(httpResult.getResult().getOrgName());
                        wtzpImgList.add(localMedia);
                        wtzpAdapter.setList(wtzpImgList);
                        wtzpAdapter.notifyDataSetChanged();
                        uploadftp(index + 1);
                    } else {
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                    }
                }

                @Override
                public void onError(int code, String message) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
                }
            };
            ProgressSubscriber<HttpResult<FileBean>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, this, true);
            RxApiManager.get().add("uploadftp", httpResultProgressSubscriber);
            HttpMethods.getInstance(this).uploadftp(httpResultProgressSubscriber, new File(selectMediaPicList.get(index).getCompressPath()));
        }
    }

    //加载提示Dialog
    public Dialog initProgressDialog(Context context, String title) {
        if (mDialog == null) {
            mDialog = new Dialog(context, R.style.LoadingDialogStyle);
            mDialog.setContentView(R.layout.layout_dialog);
            mDialog.setCancelable(true);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            TextView msg = mDialog.findViewById(R.id.id_tv_loadingmsg);
            msg.setText(title);
            msg.setVisibility(View.GONE);
            mDialog.setCancelable(false);
        }
        return mDialog;
    }

    //--------------------------------上传照片相关--end---------------------------------


    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
        RxApiManager.get().cancel("addRcrw");
        RxApiManager.get().cancel("editRcrw");
    }
}