package com.casic.dcms.ui;

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

import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.casic.dcms.R;
import com.casic.dcms.adapter.ImageGridViewAdapter;
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.ActivityDeptAdjustBinding;
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.view.ICaseDetailHandleView;
import com.casic.dcms.mvp.view.ICaseDetailView;
import com.casic.dcms.mvp.view.ICaseNextNodeView;
import com.casic.dcms.ui.fragment.dept.DeptCaseAdjustFragment;
import com.casic.dcms.ui.fragment.dept.DeptCaseHandledFragment;
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.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

import java.util.ArrayList;
import java.util.List;

import cn.jzvd.Jzvd;

public class DeptAdjustDetailActivity extends AndroidxBaseActivity<ActivityDeptAdjustBinding> implements View.OnClickListener,
        ICaseDetailView, ICaseNextNodeView, ICaseDetailHandleView {

    private final Context context = this;
    private CaseDetailPresenterImpl caseDetailPresenter;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();
    private CaseNextNodePresenterImpl nextNodePresenter;
    private List<CaseNextNodeBean.DataBean> nodeDataBeans;
    private CaseHandlePresenterImpl caseHandlePresenter;
    private String id;
    private String changeState;
    private String operationKey;

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText(Constant.DEPT_PAGE_TITLES[3]);
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    public void initData() {
        id = getIntent().getStringExtra("id");
        caseDetailPresenter = new CaseDetailPresenterImpl(this);
        caseDetailPresenter.onReadyRetrofitRequest(id);

        nextNodePresenter = new CaseNextNodePresenterImpl(this);
        caseHandlePresenter = new CaseHandlePresenterImpl(this);
    }

    @Override
    public void initEvent() {
        viewBinding.locationMapView.setOnClickListener(this);
        viewBinding.caseOptTypeLayout.setOnClickListener(this);
        viewBinding.commonTipsLayout.setOnClickListener(this);
        viewBinding.submitButton.setOnClickListener(this);
        viewBinding.submitButton.setChangeAlphaWhenPress(true);
    }

    @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.caseOptTypeLayout) {
            if (nodeDataBeans != null) {
                if (nodeDataBeans.size() >= 1) {
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
                    sheetBuilder.setTitle("操作类型");
                    for (CaseNextNodeBean.DataBean dataBean : nodeDataBeans) {
                        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();
                            viewBinding.optTypeView.setText(tag);
                            viewBinding.optTypeView.setTextColor(ContextCompat.getColor(context, R.color.textColor));

                            CaseNextNodeBean.DataBean nodeBean = nodeDataBeans.get(position);
                            changeState = String.valueOf(nodeBean.getNextState());
                            operationKey = nodeBean.getOperationKey();
                        }
                    }).build().show();
                }
            }
        } else if (id == R.id.commonTipsLayout) {
            new QMUIBottomSheet.BottomListSheetBuilder(this)
                    .setTitle("常见用语")
                    .addItem("请及时处理")
                    .addItem("调查后及时回复")
                    .setGravityCenter(true)
                    .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                        @Override
                        public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                            dialog.dismiss();
                            viewBinding.commonTipsView.setText(tag);
                            viewBinding.commonTipsView.setTextColor(ContextCompat.getColor(context, R.color.textColor));

                            viewBinding.optionEditView.setText(tag);
                            viewBinding.commonTipsView.setTextColor(ContextCompat.getColor(context, R.color.textColor));
                        }
                    }).build().show();
        } else if (id == R.id.submitButton) {
            String optType = viewBinding.optTypeView.getText().toString();
            if (optType.equals("")) {
                ToastHelper.showToast("还未选择操作类型", ToastHelper.WARING);
                return;
            }
            String optionInput = StringHelper.filterString(viewBinding.optionEditView.getText().toString());
            if (TextUtils.isEmpty(optionInput)) {
                ToastHelper.showToast("不同意/同意的意见必须填写", ToastHelper.WARING);
                return;
            }
            caseHandlePresenter.onReadyDispatcherRetrofitRequest(data.getProcessId(), this.id,
                    String.valueOf(data.getCaseState()), changeState, optionInput, operationKey,
                    data.getProcessPersonid());
        }
    }

    @Override
    public void obtainCaseDetailData(CaseDetailBean resultBean) {
        if (resultBean.isSuccess()) {
            this.data = resultBean.getData().get(0);
            viewBinding.caseNumberView.setText(data.getCaseid());
            viewBinding.caseResourceView.setText(data.getSourceName());
            viewBinding.caseCreatorView.setText(data.getCreateUserName());
            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 images = data.getFileIdVerify();
            if (!TextUtils.isEmpty(images)) {
                ArrayList<String> urls = new ArrayList<>();
                String[] split = images.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 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);
            }

            //处理图片
            String handleImages = data.getFileIdProcess();
            if (!TextUtils.isEmpty(handleImages)) {
                ArrayList<String> urls = new ArrayList<>();
                String[] split = handleImages.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.handleGridView.setAdapter(imageAdapter);
                //九宫格点击事件
                viewBinding.handleGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        OtherUtils.showBigImage(context, position, urls);
                    }
                });
            }

            //获取处置类型
            nextNodePresenter.onReadyRetrofitRequest(String.valueOf(data.getCaseState()));
        }
    }

    @Override
    public void obtainNextNodeData(CaseNextNodeBean resultBean) {
        if (resultBean.isSuccess()) {
            this.nodeDataBeans = resultBean.getData();
            if (nodeDataBeans.size() == 0) {
                viewBinding.optTypeView.setText("无下级流转节点");
            } else {
                CaseNextNodeBean.DataBean dataBean = nodeDataBeans.get(0);

                operationKey = dataBean.getOperationKey();
                changeState = String.valueOf(dataBean.getNextState());
                viewBinding.optTypeView.setText(dataBean.getNextOperation());//默认选择第一个
            }
            viewBinding.optTypeView.setTextColor(ContextCompat.getColor(this, R.color.textColor));
        } else {
            ToastHelper.showToast("该案卷无下级流转节点", ToastHelper.ERROR);
        }
    }

    @Override
    public void showProgress() {
        OtherUtils.showLoadingDialog(this, "处理中，请稍后");
    }

    @Override
    public void hideProgress() {
        OtherUtils.dismissLoadingDialog();
    }

    @Override
    public void obtainCaseHandleResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            ToastHelper.showToast("案卷处理成功", ToastHelper.SUCCESS);
            DeptCaseAdjustFragment.sendEmptyMessage(Constant.DEPT_DONE);
            DeptCaseHandledFragment.sendEmptyMessage(Constant.DEPT_DONE);
            finish();
        } else {
            ToastHelper.showToast("案卷处理失败，请检查", ToastHelper.ERROR);
        }
    }

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

    @Override
    protected void onDestroy() {
        if (caseDetailPresenter != null) {
            caseDetailPresenter.disposeRetrofitRequest();
        }
        if (nextNodePresenter != null) {
            nextNodePresenter.disposeRetrofitRequest();
        }
        if (caseHandlePresenter != null) {
            caseHandlePresenter.disposeRetrofitRequest();
        }
        viewBinding.audioPlayerView.release();
        super.onDestroy();
    }

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

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