package com.casic.dcms.view.business;

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

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityPackageTodoBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.CaseDetailBean;
import com.casic.dcms.model.CaseNextNodeBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.MapHelper;
import com.casic.dcms.utils.PictureSelectorHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.callback.ISelectorListener;
import com.casic.dcms.view.BigImageActivity;
import com.casic.dcms.view.CaseProcessActivity;
import com.casic.dcms.vm.CaseViewModel;
import com.casic.dcms.vm.NodeViewModel;
import com.casic.dcms.vm.UploadViewModel;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.entity.LocalMedia;
import com.pengxh.androidx.lite.adapter.EditableImageAdapter;
import com.pengxh.androidx.lite.adapter.ReadOnlyImageAdapter;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.hub.ContextHub;
import com.pengxh.androidx.lite.hub.IntHub;
import com.pengxh.androidx.lite.hub.LongHub;
import com.pengxh.androidx.lite.hub.StringHub;
import com.pengxh.androidx.lite.utils.Constant;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.vm.LoadState;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

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

public class PackageTodoDetailActivity extends AndroidxBaseActivity<ActivityPackageTodoBinding> {

    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 CaseViewModel caseViewModel;
    private UploadViewModel uploadViewModel;
    private NodeViewModel nodeViewModel;
    private EditableImageAdapter handleImageAdapter;
    private EditableImageAdapter punishImageAdapter;
    private String changeState;
    private String approvalResult;
    private String caseReason;
    private boolean isAddHandleImage = false;//区分是添加处理图片还是添加处罚图片
    private String id;//案卷id

    @Override
    protected void setupTopBarLayout() {
        ImmerseStatusBarManager.setColor(this, IntHub.convertColor(this, R.color.white));
        ImmersionBar.with(this).statusBarDarkFont(true).init();

        viewBinding.titleBarLayout.titleView.setText("待办案卷");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void observeRequestState() {

    }

    @Override
    public void initData() {
        id = getIntent().getStringExtra(Constant.INTENT_PARAM);
        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);
        caseViewModel.obtainCaseDetail(id);

        uploadViewModel = new ViewModelProvider(this).get(UploadViewModel.class);
        //下级结点
        nodeViewModel = new ViewModelProvider(this).get(NodeViewModel.class);

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

        //处罚adapter
        punishImageAdapter = new EditableImageAdapter(this, 3, 13);
        viewBinding.addPunishImageRecyclerView.setAdapter(punishImageAdapter);
    }

    @Override
    public void initEvent() {
        caseViewModel.caseDetailModel.observe(this, new Observer<CaseDetailBean>() {
            @Override
            public void onChanged(CaseDetailBean resultBean) {
                if (resultBean.isSuccess()) {
                    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(StringHub.filterSpaceOrEnter(data.getFieldintro()));
                    viewBinding.caseSituationView.setText(StringHub.filterSpaceOrEnter(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));
                            }
                        }
                        ReadOnlyImageAdapter imageAdapter = new ReadOnlyImageAdapter(context, urls);
                        viewBinding.imageGridView.setAdapter(imageAdapter);
                        //九宫格点击事件
                        viewBinding.imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (urls.get(position).isEmpty()) {
                                    StringHub.show(context, "图片加载失败，无法查看大图");
                                } else {
                                    ContextHub.navigatePageTo(context, BigImageActivity.class, 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));
                            }
                        }
                        handleImageAdapter.setupImage(urls);
                        viewBinding.handleImageRecyclerView.setAdapter(handleImageAdapter);
                        //九宫格点击事件
                        handleImageAdapter.setOnItemClickListener(new EditableImageAdapter.OnItemClickListener() {
                            @Override
                            public void onAddImageClick() {
                                isAddHandleImage = true;
                                selectPicture();
                            }

                            @Override
                            public void onItemClick(int position) {
                                if (urls.get(position).isEmpty()) {
                                    StringHub.show(context, "图片加载失败，无法查看大图");
                                } else {
                                    ContextHub.navigatePageTo(context, BigImageActivity.class, position, urls);
                                }
                            }

                            @Override
                            public void onItemLongClick(View view, int position) {
                                handleImageList.remove(position);
                                handleImageAdapter.deleteImage(position);
                            }
                        });
                    }
                }
            }
        });
        caseViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "获取数据中...");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });

        viewBinding.locationMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MapHelper.displayOnMap(context, data.getEorcName(), data.getLng(), data.getLat());
            }
        });

        viewBinding.caseHandleResultLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nodeViewModel.obtainNextNode(String.valueOf(data.getCaseState()));
            }
        });
        nodeViewModel.nodeModel.observe(this, new Observer<CaseNextNodeBean>() {
            @Override
            public void onChanged(CaseNextNodeBean resultBean) {
                if (resultBean.getCode() == 200) {
                    List<CaseNextNodeBean.DataBean> dataBeans = resultBean.getData();
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                    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.reasonLayout.setVisibility(View.GONE);
                                viewBinding.punishLayout.setVisibility(View.VISIBLE);
                            } else {
                                viewBinding.reasonLayout.setVisibility(View.VISIBLE);
                                viewBinding.punishLayout.setVisibility(View.GONE);
                            }
                            changeState = String.valueOf(dataBean.getNextState());
                            approvalResult = dataBean.getApprovalResult();
                        }
                    }).build().show();
                } else {
                    StringHub.show(context, "该案卷无下级流转节点");
                }
            }
        });

        viewBinding.punishHandleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new QMUIBottomSheet.BottomListSheetBuilder(context)
                        .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(IntHub.convertColor(context, R.color.mainTextColor));
                            }
                        }).build().show();
            }
        });

        punishImageAdapter.setOnItemClickListener(new EditableImageAdapter.OnItemClickListener() {
            @Override
            public void onAddImageClick() {
                isAddHandleImage = false;
                selectPicture();
            }

            @Override
            public void onItemClick(int position) {
                if (punishRealPaths.get(position).isEmpty()) {
                    StringHub.show(context, "图片加载失败，无法查看大图");
                } else {
                    ContextHub.navigatePageTo(context, BigImageActivity.class, position, punishRealPaths);
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
                punishImageList.remove(position);
                punishImageAdapter.deleteImage(position);
            }
        });
        uploadViewModel.imageModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    if (isAddHandleImage) {
                        //处理图片
                        if (handleImageAdapter.getItemCount() <= 2) {
                            String url = resultBean.getData();
                            handleImageList.add(url);
                            handleRealPaths.add(StringHelper.appendCompleteURL(url));
                            handleImageAdapter.setupImage(handleRealPaths);
                        } else {
                            StringHub.show(context, "最多只能上传3张图片");
                        }
                    } else {
                        //处罚图片
                        if (punishImageAdapter.getItemCount() <= 2) {
                            String url = resultBean.getData();
                            punishImageList.add(url);
                            punishRealPaths.add(StringHelper.appendCompleteURL(url));
                            punishImageAdapter.setupImage(punishRealPaths);
                        } else {
                            StringHub.show(context, "最多只能上传3张图片");
                        }
                    }
                }
            }
        });

        String systemTime = LongHub.timestampToCompleteDate(System.currentTimeMillis());
        viewBinding.punishDateView.setText(systemTime);

        viewBinding.handleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContextHub.navigatePageTo(context, CaseProcessActivity.class, data.getProcessId());
            }
        });

        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitCase();
            }
        });
    }

    private void selectPicture() {
        PictureSelectorHelper.selectPicture(this, new ISelectorListener() {
            @Override
            public void onSuccess(ArrayList<LocalMedia> result) {
                if (result.size() == 1) {
                    uploadViewModel.uploadImage(new File(result.get(0).getRealPath()));
                } else {
                    for (LocalMedia localMedia : result) {
                        uploadViewModel.uploadImage(new File(localMedia.getRealPath()));
                    }
                }
            }
        });
    }

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