package com.casic.dcms.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.casic.dcms.R;
import com.casic.dcms.adapter.ImageGridViewAdapter;
import com.casic.dcms.adapter.NineGridImageAdapter;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.CaseDetailBean;
import com.casic.dcms.bean.CaseNextNodeBean;
import com.casic.dcms.databinding.ActivityPackageTodoBinding;
import com.casic.dcms.mvp.presenter.impl.CaseDetailPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.CaseHandlePresenterImpl;
import com.casic.dcms.mvp.presenter.impl.CaseNextNodePresenterImpl;
import com.casic.dcms.mvp.presenter.impl.PackageHandlePresenterImpl;
import com.casic.dcms.mvp.presenter.impl.UploadImagePresenterImpl;
import com.casic.dcms.mvp.view.ICaseDetailHandleView;
import com.casic.dcms.mvp.view.ICaseDetailView;
import com.casic.dcms.mvp.view.ICaseNextNodeView;
import com.casic.dcms.mvp.view.IPackageDetailHandleView;
import com.casic.dcms.mvp.view.IUploadFileView;
import com.casic.dcms.ui.fragment.threepkg.PackageHandledFragment;
import com.casic.dcms.ui.fragment.threepkg.PackageTodoFragment;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.TimeOrDateUtil;
import com.casic.dcms.utils.ToastHelper;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class PackageTodoDetailActivity extends AndroidxBaseActivity<ActivityPackageTodoBinding> implements View.OnClickListener,
        ICaseDetailView, IUploadFileView, ICaseNextNodeView, ICaseDetailHandleView, IPackageDetailHandleView {

    private static final String TAG = "PackageTodoDetail";
    private final Context context = this;
    private final ArrayList<String> handleRealPaths = new ArrayList<>();//真实图片路径
    private final ArrayList<String> punishRealPaths = new ArrayList<>();//真实图片路径
    private final List<String> handleImageList = new ArrayList<>();//上传到服务器的数据集
    private final List<String> punishImageList = new ArrayList<>();//上传到服务器的数据集
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();
    private CaseDetailPresenterImpl caseDetailPresenter;
    private QMUITipDialog submitDialog;
    private UploadImagePresenterImpl uploadImagePresenter;
    private NineGridImageAdapter handleImageAdapter;
    private NineGridImageAdapter punishImageAdapter;
    private CaseNextNodePresenterImpl caseNextNodePresenter;
    private String changeState;
    private String approvalResult;
    private String caseReason;
    private boolean isAddHandleImage = false;//区分是添加处理图片还是添加处罚图片
    private String id;//案卷id
    private CaseHandlePresenterImpl caseHandlePresenter;
    private String handleResult;
    private PackageHandlePresenterImpl packageHandlePresenter;
    private String punishOpinion;
    private String punishType;//处罚类型文字
    private String punishTime;

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText("待办案卷");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    public void initData() {
        id = getIntent().getStringExtra("id");
        caseDetailPresenter = new CaseDetailPresenterImpl(this);
        caseDetailPresenter.onReadyRetrofitRequest(id);
        submitDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("处理中，请稍后")
                .create();
        uploadImagePresenter = new UploadImagePresenterImpl(this);

        //案卷处理adapter，默认加载之前的处理图，但是依旧可以处理，然后显示最新的图
        handleImageAdapter = new NineGridImageAdapter(this);
        viewBinding.handleGridView.setLayoutManager(new GridLayoutManager(this, 2));
        viewBinding.handleGridView.setAdapter(handleImageAdapter);

        //处罚adapter
        punishImageAdapter = new NineGridImageAdapter(this);
        viewBinding.punishGridView.setLayoutManager(new GridLayoutManager(this, 2));
        viewBinding.punishGridView.setAdapter(punishImageAdapter);

        //下级结点
        caseNextNodePresenter = new CaseNextNodePresenterImpl(this);

        caseHandlePresenter = new CaseHandlePresenterImpl(this);
        packageHandlePresenter = new PackageHandlePresenterImpl(this);
    }

    @Override
    public void initEvent() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                String systemTime = TimeOrDateUtil.timestampToCompleteDate(System.currentTimeMillis());
                viewBinding.punishDateView.post(() -> viewBinding.punishDateView.setText(systemTime));
            }
        }, 0, 1000);

        viewBinding.locationMapView.setOnClickListener(this);
        viewBinding.caseHandleResultLayout.setOnClickListener(this);
        viewBinding.punishHandleLayout.setOnClickListener(this);
        viewBinding.handleLayout.setOnClickListener(this);
        viewBinding.submitButton.setOnClickListener(this);
        viewBinding.submitButton.setChangeAlphaWhenPress(true);

        //图片九宫格事件处理
        handleImageAdapter.setOnItemClickListener(new NineGridImageAdapter.OnItemClickListener() {
            @Override
            public void onAddImageClick() {
                isAddHandleImage = true;
                new QMUIDialog.MenuDialogBuilder(context)
                        .addItem("相册中选取", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                OtherUtils.selectPicture(PackageTodoDetailActivity.this);
                            }
                        })
                        .addItem("相机拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                OtherUtils.takePicture(PackageTodoDetailActivity.this);
                            }
                        })
                        .create().show();
            }

            @Override
            public void onItemClick(int position) {
                OtherUtils.showBigImage(context, position, handleRealPaths);
            }

            @Override
            public void onItemLongClick(View view, int position) {
                handleImageList.remove(position);
                handleImageAdapter.deleteImage(position);
            }
        });

        punishImageAdapter.setOnItemClickListener(new NineGridImageAdapter.OnItemClickListener() {
            @Override
            public void onAddImageClick() {
                isAddHandleImage = false;
                new QMUIDialog.MenuDialogBuilder(context)
                        .addItem("相册中选取", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                OtherUtils.selectPicture(PackageTodoDetailActivity.this);
                            }
                        })
                        .addItem("相机拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                OtherUtils.takePicture(PackageTodoDetailActivity.this);
                            }
                        })
                        .create().show();
            }

            @Override
            public void onItemClick(int position) {
                OtherUtils.showBigImage(context, position, punishRealPaths);
            }

            @Override
            public void onItemLongClick(View view, int position) {
                punishImageList.remove(position);
                punishImageAdapter.deleteImage(position);
            }
        });
    }

    @Override
    public void obtainCaseDetailData(CaseDetailBean resultBean) {
        if (resultBean.isSuccess()) {
            this.data = resultBean.getData().get(0);
            viewBinding.caseNumberView.setText(data.getCaseid());
            viewBinding.caseHandleStatusView.setText(data.getCaseStateName());
            viewBinding.caseTypeView.setText(data.getEorcName());
            viewBinding.caseLargeTypeView.setText(data.getCasetypeName());
            viewBinding.caseSmallTypeView.setText(data.getCasetypeDetailName());
            viewBinding.caseCommunityView.setText(data.getCommunityName().equals("") ? "社区信息未知" : data.getCommunityName());
            viewBinding.casePlaceView.setText(StringHelper.filterString(data.getFieldintro()));
            viewBinding.caseSituationView.setText(StringHelper.filterString(data.getDescription()));

            //最初始的案卷图片
            String verifyImages = data.getFileIdVerify();
            if (!TextUtils.isEmpty(verifyImages)) {
                ArrayList<String> urls = new ArrayList<>();
                String[] split = verifyImages.split(",");
                for (String s : split) {
                    if (s.endsWith(".jpg") || s.contains(".jpeg") || s.contains(".png")) {
                        urls.add(StringHelper.appendCompleteURL(s));
                    }
                }
                ImageGridViewAdapter imageAdapter = new ImageGridViewAdapter(this);
                imageAdapter.setImageList(urls);
                viewBinding.casePicGridView.setAdapter(imageAdapter);
                //九宫格点击事件
                viewBinding.casePicGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        OtherUtils.showBigImage(context, position, urls);
                    }
                });
            }

            //案卷处理时候上传的图片
            String images = data.getFileIdProcess();
            if (!TextUtils.isEmpty(images)) {
                ArrayList<String> urls = new ArrayList<>();
                String[] split = images.split(",");
                for (String s : split) {
                    if (s.contains("jpg") || s.contains("jpeg") || s.contains("png")) {
                        urls.add(StringHelper.appendCompleteURL(s));
                    }
                }
                ImageGridViewAdapter imageAdapter = new ImageGridViewAdapter(this);
                imageAdapter.setImageList(urls);
                viewBinding.casePicGridView.setAdapter(imageAdapter);
                //九宫格点击事件
                viewBinding.casePicGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                        OtherUtils.showBigImage(context, position, urls);
                    }
                });
            }
        }
    }

    @Override
    public void obtainDataFail() {
        ToastHelper.showToast("操作失败", ToastHelper.ERROR);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.locationMapView) {
            OtherUtils.displayOnMap(this, data.getEorcName(), data.getLng(), data.getLat());
        } else if (id == R.id.caseHandleResultLayout) {
            caseNextNodePresenter.onReadyRetrofitRequest(String.valueOf(data.getCaseState()));
        } else if (id == R.id.punishHandleLayout) {
            new QMUIBottomSheet.BottomListSheetBuilder(this)
                    .setTitle("处罚类型")
                    .addItem("劝导")//1
                    .addItem("警告")//2
                    .addItem("处罚")//3
                    .setGravityCenter(true)
                    .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                        @Override
                        public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                            dialog.dismiss();
                            viewBinding.punishTypeView.setText(tag);
                            viewBinding.punishTypeView.setTextColor(ContextCompat.getColor(context, R.color.textColor));
                        }
                    }).build().show();
        } else if (id == R.id.handleLayout) {
            OtherUtils.showCaseProcess(this, data.getProcessId());
        } else if (id == R.id.submitButton) {
            submitCase();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : selectList) {
                        File file = new File(media.getCompressPath());
                        if (file.length() <= Constant.IMAGE_MINUS_SIZE) {
                            ToastHelper.showToast("图片尺寸太小，请重新选择", ToastHelper.ERROR);
                            continue;
                        }
                        uploadImagePresenter.onReadyRetrofitRequest(file);
                    }
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    LocalMedia localMedia = PictureSelector.obtainMultipleResult(data).get(0);
                    uploadImagePresenter.onReadyRetrofitRequest(new File(localMedia.getCompressPath()));
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void showProgress() {
        submitDialog.show();
    }

    @Override
    public void hideProgress() {
        submitDialog.dismiss();
    }

    @Override
    public void obtainUploadAudioResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainUploadImageResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            PictureFileUtils.deleteAllCacheDirFile(this);
            /**
             * 系统路径static拼接图片返回路径
             * http://111.198.10.15:11409/static/2021-04/000bcf78345f4c1c86484efa3f9d68a2.jpeg
             */
            //2021-04\\000bcf78345f4c1c86484efa3f9d68a2.jpeg
            if (isAddHandleImage) {
                //处理图片
                if (handleImageAdapter.getItemCount() <= 2) {
                    String url = resultBean.getData();
                    handleImageList.add(url);
                    handleRealPaths.add(StringHelper.appendCompleteURL(url));
                    handleImageAdapter.setupImage(handleRealPaths);
                } else {
                    ToastHelper.showToast("最多只能上传2张图片", ToastHelper.WARING);
                }
            } else {
                //处罚图片
                if (punishImageAdapter.getItemCount() <= 2) {
                    String url = resultBean.getData();
                    punishImageList.add(url);
                    punishRealPaths.add(StringHelper.appendCompleteURL(url));
                    punishImageAdapter.setupImage(punishRealPaths);
                } else {
                    ToastHelper.showToast("最多只能上传2张图片", ToastHelper.WARING);
                }
            }
        }
    }

    @Override
    public void obtainUploadVideoResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainNextNodeData(CaseNextNodeBean resultBean) {
        if (resultBean.isSuccess()) {
            List<CaseNextNodeBean.DataBean> dataBeans = resultBean.getData();
            QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
            sheetBuilder.setTitle("处理结果");
            for (CaseNextNodeBean.DataBean dataBean : dataBeans) {
                sheetBuilder.addItem(dataBean.getNextOperation());
            }
            sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                @Override
                public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                    dialog.dismiss();

                    CaseNextNodeBean.DataBean dataBean = dataBeans.get(position);
                    String nextOperation = dataBean.getNextOperation();
                    viewBinding.caseHandleResultView.setText(nextOperation);
                    if (nextOperation.equals("处理完成")) {
                        viewBinding.line1.setVisibility(View.VISIBLE);
                        viewBinding.line2.setVisibility(View.GONE);
                        viewBinding.imageLayout.setVisibility(View.VISIBLE);
                        viewBinding.reasonLayout.setVisibility(View.GONE);
                        viewBinding.punishLayout.setVisibility(View.VISIBLE);
                    } else {
                        viewBinding.line1.setVisibility(View.GONE);
                        viewBinding.line2.setVisibility(View.VISIBLE);
                        viewBinding.imageLayout.setVisibility(View.GONE);
                        viewBinding.reasonLayout.setVisibility(View.VISIBLE);
                        viewBinding.punishLayout.setVisibility(View.GONE);
                    }
                    changeState = String.valueOf(dataBean.getNextState());
                    approvalResult = dataBean.getApprovalResult();
                }
            }).build().show();
        } else {
            ToastHelper.showToast("该案卷无下级流转节点", ToastHelper.ERROR);
        }
    }

    /**
     * 案卷提交。先提交普通案卷流程，成功后再自动提交三包处罚
     */
    private void submitCase() {
        handleResult = viewBinding.caseHandleResultView.getText().toString();
        if (TextUtils.isEmpty(handleResult)) {
            ToastHelper.showToast("还未选择处理结果", ToastHelper.WARING);
            return;
        }
        if (handleResult.equals("处理完成")) {
            //选择处理完成时，处理图片必传。至少一张，最多两张
            if (handleImageAdapter.getItemCount() != 2) {
                ToastHelper.showToast("当前案卷状态必须上传至少两张图片", ToastHelper.WARING);
                return;
            }
            //只有选择处理完成才需要判断处罚条件
            punishType = viewBinding.punishTypeView.getText().toString();
            if (TextUtils.isEmpty(punishType)) {
                ToastHelper.showToast("处罚类型还未选择", ToastHelper.WARING);
                return;
            }
            punishOpinion = viewBinding.punishOpinionView.getText().toString().trim().replace(" ", "");
            if (TextUtils.isEmpty(punishOpinion)) {
                ToastHelper.showToast("处罚意见还未填写", ToastHelper.WARING);
                return;
            }
        }
        if (handleResult.equals("申请延期") || handleResult.equals("申请调整")) {
            caseReason = viewBinding.caseReasonView.getText().toString();
            if (TextUtils.isEmpty(caseReason)) {
                ToastHelper.showToast("延期/调整的原因必须填写", ToastHelper.WARING);
                return;
            }
        }
        caseHandlePresenter.onReadyRetrofitRequest(data.getProcessId(), id, String.valueOf(data.getCaseState()),
                changeState, caseReason, StringHelper.reformatURL(handleImageList), approvalResult);

        //处理之后才能处罚，所以在处理之后才获取处罚时间
        punishTime = viewBinding.punishDateView.getText().toString();
    }

    @Override
    public void obtainCaseHandleResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            if (handleResult.equals("处理完成")) {
                //只有选择处理完成才需要操作处罚流程
                packageHandlePresenter.onReadyRetrofitRequest(id, StringHelper.StringToType(punishType),
                        punishOpinion, punishTime, StringHelper.reformatURL(punishImageList));
            } else {
                ToastHelper.showToast("案卷处理成功", ToastHelper.SUCCESS);
                PackageTodoFragment.sendEmptyMessage(Constant.PACKAGE_DONE);
                PackageHandledFragment.sendEmptyMessage(Constant.PACKAGE_DONE);
                finish();
            }
        }
    }

    @Override
    public void obtainPackageHandleResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            ToastHelper.showToast("案卷处理成功", ToastHelper.SUCCESS);
            PackageTodoFragment.sendEmptyMessage(Constant.PACKAGE_DONE);
            PackageHandledFragment.sendEmptyMessage(Constant.PACKAGE_DONE);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        if (caseDetailPresenter != null) {
            caseDetailPresenter.disposeRetrofitRequest();
        }
        if (uploadImagePresenter != null) {
            uploadImagePresenter.disposeRetrofitRequest();
        }
        if (caseNextNodePresenter != null) {
            caseNextNodePresenter.disposeRetrofitRequest();
        }
        if (caseHandlePresenter != null) {
            caseHandlePresenter.disposeRetrofitRequest();
        }
        if (packageHandlePresenter != null) {
            packageHandlePresenter.disposeRetrofitRequest();
        }
        super.onDestroy();
    }
}
