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.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
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.ActivityCaseHandleDetailBinding;
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.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.IUploadFileView;
import com.casic.dcms.ui.fragment.handle.CaseHandledFragment;
import com.casic.dcms.ui.fragment.handle.CaseTodoFragment;
import com.casic.dcms.ui.fragment.handle.OvertimeCaseFragment;
import com.casic.dcms.ui.fragment.handle.UrgentCaseFragment;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.JzExoMedia;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.StringHelper;
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.QMUIBottomSheet.BottomListSheetBuilder;
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 cn.jzvd.Jzvd;

public class CaseHandleDetailActivity extends AndroidxBaseActivity<ActivityCaseHandleDetailBinding> implements ICaseDetailView, ICaseNextNodeView,
        IUploadFileView, ICaseDetailHandleView {

    private final Context context = CaseHandleDetailActivity.this;
    private final ArrayList<String> realPaths = new ArrayList<>(); //真实图片路径
    private final List<String> imageList = new ArrayList<>(); //上传到服务器的数据集
    private CaseDetailPresenterImpl caseDetailPresenter;
    private CaseNextNodePresenterImpl caseNextNodePresenter;
    private UploadImagePresenterImpl uploadImagePresenter;
    private CaseHandlePresenterImpl caseHandlePresenter;
    private String title;
    private String id;
    private String changeState;
    private String caseReason;
    private String approvalResult;
    private QMUITipDialog submitDialog;
    private NineGridImageAdapter handleImageAdapter;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();

    @Override
    protected void setupTopBarLayout() {
        title = getIntent().getStringExtra("title");
        viewBinding.titleBarLayout.titleView.setText(title);
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

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

        handleImageAdapter = new NineGridImageAdapter(this);
        viewBinding.handleGridView.setLayoutManager(new GridLayoutManager(this, 2));
        viewBinding.handleGridView.setAdapter(handleImageAdapter);
    }

    @Override
    protected void initEvent() {
        viewBinding.locationMapView.setOnClickListener(v -> OtherUtils.displayOnMap(context, data.getEorcName(), data.getLng(), data.getLat()));
        viewBinding.caseHandleResultLayout.setOnClickListener(v -> caseNextNodePresenter.onReadyRetrofitRequest(String.valueOf(data.getCaseState())));

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

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

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

        viewBinding.submitButton.setChangeAlphaWhenPress(true);
        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String handleResult = viewBinding.caseHandleResultView.getText().toString();
                if (handleResult.equals("")) {
                    ToastHelper.showToast("还未选择处理结果", ToastHelper.WARING);
                    return;
                }
                if (handleResult.equals("处理完成")) {
                    //选择处理完成时，处理图片必传。至少一张，最多两张
                    if (handleImageAdapter.getItemCount() != 2) {
                        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(imageList), approvalResult
                );
            }
        });
    }

    @Override
    public void obtainCaseDetailData(CaseDetailBean resultBean) {
        if (resultBean.getCode() == 200) {
            data = resultBean.getData().get(0);
            viewBinding.caseNumberView.setText(data.getCaseid());
            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()));
            viewBinding.caseHandleView.setText(data.getCaseStateName().equals("") ? "无处理意见" : data.getCaseStateName());

            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<?> adapterView, View view, int position, long l) {
                        OtherUtils.showBigImage(context, position, urls);
                    }
                });
            }

            //音频
            String audioFile = data.getAudioIdVerify();
            if (!TextUtils.isEmpty(audioFile)) {
                viewBinding.audioPlayerView.setVisibility(View.VISIBLE);
                viewBinding.audioPlayerView.setAudioUrl(StringHelper.appendCompleteURL(audioFile));
            }

            //视频
            String videoFile = data.getVideoIdVerify();
            if (!TextUtils.isEmpty(videoFile)) {
                viewBinding.videoPlayerView.setVisibility(View.VISIBLE);
                String videoUrl = StringHelper.appendCompleteURL(videoFile);
                viewBinding.videoPlayerView.setUp(
                        videoUrl,
                        StringHelper.filterString(data.getDescription()),
                        Jzvd.SCREEN_NORMAL,
                        JzExoMedia.class
                );
                //设置第一帧为封面
                Glide.with(this)
                        .setDefaultRequestOptions(new RequestOptions().frame(4000000))
                        .load(videoUrl)
                        .into(viewBinding.videoPlayerView.posterImageView);
            }
            viewBinding.caseStartTimeView.setText(data.getCreateTime());
            viewBinding.caseEndTimeView.setText(data.getNodeLimittime());
        }
    }

    @Override
    public void obtainNextNodeData(CaseNextNodeBean resultBean) {
        if (resultBean.getCode() == 200) {
            List<CaseNextNodeBean.DataBean> dataBeans = resultBean.getData();
            BottomListSheetBuilder sheetBuilder = new BottomListSheetBuilder(this);
            sheetBuilder.setTitle("处理结果");
            for (CaseNextNodeBean.DataBean dataBean : dataBeans) {
                sheetBuilder.addItem(dataBean.getNextOperation());
            }
            sheetBuilder.setGravityCenter(true)
                    .setOnSheetItemClickListener(new 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.imageLayout.setVisibility(View.VISIBLE);
                                viewBinding.reasonLayout.setVisibility(View.GONE);
                            } else {
                                viewBinding.imageLayout.setVisibility(View.GONE);
                                viewBinding.reasonLayout.setVisibility(View.VISIBLE);
                            }
                            changeState = String.valueOf(dataBean.getNextState());
                            approvalResult = dataBean.getApprovalResult();
                        }
                    }).build().show();
        } else {
            ToastHelper.showToast("该案卷无下级流转节点", ToastHelper.ERROR);
        }
    }

    @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;
            }
        }
    }

    @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.getCode() == 200) {
            PictureFileUtils.deleteAllCacheDirFile(this);
            /**
             * 系统路径static拼接图片返回路径
             * http://111.198.10.15:11409/static/2021-04/000bcf78345f4c1c86484efa3f9d68a2.jpeg
             */
            //2021-04\\000bcf78345f4c1c86484efa3f9d68a2.jpeg
            if (handleImageAdapter.getItemCount() <= 2) {
                String url = resultBean.getData();
                imageList.add(url);
                realPaths.add(StringHelper.appendCompleteURL(url));
                handleImageAdapter.setupImage(realPaths);
            } else {
                ToastHelper.showToast("最多只能上传2张图片", ToastHelper.WARING);
            }
        }
    }

    @Override
    public void obtainUploadVideoResult(ActionResultBean resultBean) {
    }

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

    @Override
    public void obtainCaseHandleResult(ActionResultBean resultBean) {
        if (resultBean.getCode() == 200) {
            ToastHelper.showToast("案卷处理成功", ToastHelper.SUCCESS);
            switch (title) {
                case "超时案卷":
                    OvertimeCaseFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    CaseHandledFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    break;
                case "紧急案卷":
                    UrgentCaseFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    CaseHandledFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    break;
                case "待办案卷":
                    CaseTodoFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    CaseHandledFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    break;
            }
            finish();
        } else {
            ToastHelper.showToast("案卷处理失败，请检查", ToastHelper.ERROR);
        }
    }

    @Override
    protected void onDestroy() {
        caseDetailPresenter.disposeRetrofitRequest();
        caseNextNodePresenter.disposeRetrofitRequest();
        uploadImagePresenter.disposeRetrofitRequest();
        caseHandlePresenter.disposeRetrofitRequest();
        viewBinding.audioPlayerView.release();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }
}