package com.casic.dcms.ui;

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

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.ComSentenceBean;
import com.casic.dcms.databinding.ActivityCaseTodoDetailBinding;
import com.casic.dcms.mvp.presenter.impl.CaseDetailPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.ComSentencePresenterImpl;
import com.casic.dcms.mvp.presenter.impl.UpdateSupervisePresenterImpl;
import com.casic.dcms.mvp.view.ICaseDetailView;
import com.casic.dcms.mvp.view.ICommonSentenceView;
import com.casic.dcms.mvp.view.IUpdateSuperviseView;
import com.casic.dcms.ui.fragment.overtime.CaseHandledFragment;
import com.casic.dcms.ui.fragment.overtime.CaseTodoFragment;
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 CaseTodoDetailActivity extends AndroidxBaseActivity<ActivityCaseTodoDetailBinding> implements View.OnClickListener,
        ICaseDetailView, ICommonSentenceView, IUpdateSuperviseView {

    private final Context context = this;
    private String title;
    private String id;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();

    private CaseDetailPresenterImpl caseDetailPresenter;
    private ComSentencePresenterImpl sentencePresenter;
    private UpdateSupervisePresenterImpl updateSupervisePresenter;

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

    @Override
    public void initData() {
        id = getIntent().getStringExtra("id");

        caseDetailPresenter = new CaseDetailPresenterImpl(this);
        caseDetailPresenter.onReadyRetrofitRequest(id);

        sentencePresenter = new ComSentencePresenterImpl(this);
        updateSupervisePresenter = new UpdateSupervisePresenterImpl(this);
    }

    @Override
    public void initEvent() {
        viewBinding.locationMapView.setOnClickListener(this);
        viewBinding.caseHandleLayout.setOnClickListener(this);
        viewBinding.caseCommonSentenceLayout.setOnClickListener(this);
        viewBinding.submitButton.setOnClickListener(this);
    }

    @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.caseHandleLayout) {
            OtherUtils.showCaseProcess(this, data.getProcessId());
        } else if (id == R.id.caseCommonSentenceLayout) {
            sentencePresenter.onReadyRetrofitRequest();
        } else if (id == R.id.submitButton) {
            submitCase();
        }
    }

    private void submitCase() {
        String remarks = viewBinding.caseHandleResultView.getText().toString();
        if (TextUtils.isEmpty(remarks)) {
            ToastHelper.showToast("督办意见不能为空", ToastHelper.WARING);
            return;
        }
        updateSupervisePresenter.onReadyRetrofitRequest(id, remarks);
    }

    @Override
    public void obtainCaseDetailData(CaseDetailBean resultBean) {
        if (resultBean.isSuccess()) {
            this.data = resultBean.getData().get(0);
            viewBinding.caseNumberView.setText(data.getCaseid());
            viewBinding.caseOverTimeView.setText(data.getNodeLimittime());
            viewBinding.caseHandleStatusView.setText(data.getCaseStateName().equals("") ? "案卷状态未知" : data.getCaseStateName());
            viewBinding.casePlaceView.setText(StringHelper.filterString(data.getFieldintro()));
            viewBinding.caseDescriptionView.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 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);
            }
        }
    }

    @Override
    public void obtainCommonSentenceData(ComSentenceBean resultBean) {
        if (resultBean.isSuccess()) {
            List<ComSentenceBean.DataBean> dataBeans = resultBean.getData();
            QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
            sheetBuilder.setTitle("常用语句");
            for (ComSentenceBean.DataBean dataBean : dataBeans) {
                sheetBuilder.addItem(dataBean.getName());
            }
            sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                @Override
                public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                    dialog.dismiss();

                    ComSentenceBean.DataBean dataBean = dataBeans.get(position);
                    viewBinding.caseCommonSentenceView.setText(dataBean.getName());
                    viewBinding.caseHandleResultView.setText(dataBean.getName());
                }
            }).build().show();
        } else {
            ToastHelper.showToast("该案卷无下级流转节点", ToastHelper.ERROR);
        }
    }

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

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

    @Override
    public void obtainUpdateData(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            ToastHelper.showToast("案卷督办提交成功", ToastHelper.SUCCESS);
            //案卷办完以后通知待办和已办刷新数据
            if (title.equals("超时督办")) {
                CaseTodoFragment.sendEmptyMessage(Constant.CASE_OVERTIME_OK);
                CaseHandledFragment.sendEmptyMessage(Constant.CASE_OVERTIME_OK);
            } else {
                CaseTodoFragment.sendEmptyMessage(Constant.CASE_URGENT_OK);
                CaseHandledFragment.sendEmptyMessage(Constant.CASE_URGENT_OK);
            }
            finish();
        } else {
            ToastHelper.showToast("案卷督办提交失败，请检查", ToastHelper.ERROR);
        }
    }

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

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

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

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