package com.casic.dcms.view.sanbao;

import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivitySanBaoTodoBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.CaseDetailBean;
import com.casic.dcms.model.CaseNextNodeBean;
import com.casic.dcms.utils.MapHelper;
import com.casic.dcms.utils.PictureSelectorHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ViewGroupKit;
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.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.kit.ContextKit;
import com.pengxh.androidx.lite.kit.IntKit;
import com.pengxh.androidx.lite.kit.LongKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.Constant;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

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

public class SanBaoTodoDetailActivity extends AndroidxBaseActivity<ActivitySanBaoTodoBinding> {

    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
    private WeakReferenceHandler weakReferenceHandler;

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);

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

    @Override
    protected void observeRequestState() {
        uploadViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    StringKit.show(SanBaoTodoDetailActivity.this, "上传中，请稍后...");
                }
            }
        });

        caseViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    LoadingDialog.show(SanBaoTodoDetailActivity.this, "获取数据中...");
                } else {
                    LoadingDialog.dismiss();
                }
            }
        });
    }

    @Override
    public void initOnCreate(@Nullable Bundle savedInstanceState) {
        weakReferenceHandler = new WeakReferenceHandler(callback);

        id = getIntent().getStringExtra(Constant.INTENT_PARAM_KEY);
        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);
        caseViewModel.getCaseDetail(this, id);

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

        //案卷处理adapter，默认加载之前的处理图，但是依旧可以处理，然后显示最新的图
        int width = ContextKit.getScreenWidth(this) - IntKit.dp2px(this, 20);
        handleImageAdapter = new EditableImageAdapter(this, handleRealPaths, width, 2, 3);

        //处罚adapter
        punishImageAdapter = new EditableImageAdapter(this, punishRealPaths, width, 2, 3);
        binding.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);
                    binding.caseNumberView.setText(data.getCaseid());
                    binding.caseHandleStatusView.setText(data.getCaseStateName());
                    binding.caseTypeView.setText(data.getEorcName());
                    binding.caseLargeTypeView.setText(data.getCasetypeName());
                    binding.caseSmallTypeView.setText(data.getCasetypeDetailName());
                    binding.caseCommunityView.setText(data.getCommunityName().equals("") ? "社区信息未知" : data.getCommunityName());
                    binding.casePlaceView.setText(data.getFieldintro());
                    binding.caseSituationView.setText(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);
                        binding.imageGridView.setAdapter(imageAdapter);
                        //九宫格点击事件
                        binding.imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (urls.get(position).isEmpty()) {
                                    StringKit.show(context, "图片加载失败，无法查看大图");
                                } else {
                                    ContextKit.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));
                            }
                        }
                        binding.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()) {
                                    StringKit.show(context, "图片加载失败，无法查看大图");
                                } else {
                                    ContextKit.navigatePageTo(context, BigImageActivity.class, position, urls);
                                }
                            }

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

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

        binding.caseHandleResultLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nodeViewModel.getNextNode(context, 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();
                            binding.caseHandleResultView.setText(nextOperation);
                            if (nextOperation.equals("处理完成")) {
                                binding.reasonLayout.setVisibility(View.GONE);
                                binding.punishLayout.setVisibility(View.VISIBLE);
                            } else {
                                binding.reasonLayout.setVisibility(View.VISIBLE);
                                binding.punishLayout.setVisibility(View.GONE);
                            }
                            changeState = String.valueOf(dataBean.getNextState());
                            approvalResult = dataBean.getApprovalResult();
                        }
                    }).build().show();
                } else {
                    StringKit.show(context, "该案卷无下级流转节点");
                }
            }
        });

        binding.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();
                                binding.punishTypeView.setText(tag);
                                binding.punishTypeView.setTextColor(IntKit.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()) {
                    StringKit.show(context, "图片加载失败，无法查看大图");
                } else {
                    ContextKit.navigatePageTo(context, BigImageActivity.class, position, punishRealPaths);
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
                punishImageList.remove(position);
                punishRealPaths.remove(position);
                punishImageAdapter.notifyDataSetChanged();
            }
        });
        uploadViewModel.imageModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    String url = resultBean.getData();
                    if (isAddHandleImage) {
                        //处理图片
                        handleImageList.add(url);
                        handleRealPaths.add(StringHelper.appendCompleteURL(url));
                        handleImageAdapter.notifyDataSetChanged();
                    } else {
                        //处罚图片
                        punishImageList.add(url);
                        punishRealPaths.add(StringHelper.appendCompleteURL(url));
                        punishImageAdapter.notifyDataSetChanged();
                    }
                }
            }
        });

        String systemTime = LongKit.timestampToCompleteDate(System.currentTimeMillis());
        binding.punishDateView.setText(systemTime);

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

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

    private void selectPicture() {
        PictureSelectorHelper.selectPicture(this, 2, new ISelectorListener() {
            @Override
            public void onSuccess(ArrayList<LocalMedia> result) {
                if (result.size() == 1) {
                    handleSelectResult(result.get(0));
                } else {
                    int sum = (result.size() * 1500);
                    new CountDownTimer(sum, 1500) {

                        @Override
                        public void onTick(long millisUntilFinished) {
                            int i = (int) (millisUntilFinished / 1500);
                            Message message = weakReferenceHandler.obtainMessage();
                            message.obj = result.get(i);
                            message.what = 2023060502;
                            weakReferenceHandler.handleMessage(message);
                        }

                        @Override
                        public void onFinish() {

                        }
                    }.start();
                }
            }
        });
    }

    private final Handler.Callback callback = new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 2023060502) {
                handleSelectResult((LocalMedia) msg.obj);
            }
            return true;
        }
    };

    private void handleSelectResult(LocalMedia obj) {
        uploadViewModel.uploadImage(this, new File(obj.getRealPath()));
    }

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

        //TODO 简化处理
        StringKit.show(context, "三包处置完成");
//        caseViewModel.handleOvertimeCase(data.getProcessId(), id, String.valueOf(data.getCaseState()),
//                changeState, caseReason, StringHelper.reformatURL(handleImageList), approvalResult);
    }
}
