package com.casic.dcms.view.department;

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.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityDeptTodoBinding;
import com.casic.dcms.model.CaseDetailBean;
import com.casic.dcms.model.CaseNextNodeBean;
import com.casic.dcms.model.ProcessPersonBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.MapHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.view.BigImageActivity;
import com.casic.dcms.vm.CaseOperateViewModel;
import com.casic.dcms.vm.CaseViewModel;
import com.casic.dcms.vm.NodeViewModel;
import com.gyf.immersionbar.ImmersionBar;
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.StringHub;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.vm.LoadState;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

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

import cn.jzvd.Jzvd;

public class DeptTodoDetailActivity extends AndroidxBaseActivity<ActivityDeptTodoBinding> {

    private final Context context = this;
    private CaseViewModel caseViewModel;
    private NodeViewModel nodeViewModel;
    private CaseOperateViewModel operateViewModel;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();
    private List<ProcessPersonBean.DataBean> personBeans;
    private String id;
    private String changeState;
    private String taskUserId;
    private String operationKey;
    private List<CaseNextNodeBean.DataBean> nodeDataBeans;

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

        String title = getIntent().getStringExtra("title");
        viewBinding.titleBarLayout.titleView.setText(title);
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void observeRequestState() {

    }

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

        nodeViewModel = new ViewModelProvider(this).get(NodeViewModel.class);
        operateViewModel = new ViewModelProvider(this).get(CaseOperateViewModel.class);
    }

    @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.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(StringHub.filterSpaceOrEnter(data.getFieldintro()));
                    viewBinding.caseSituationView.setText(StringHub.filterSpaceOrEnter(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));
                            }
                        }
                        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 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, StringHub.filterSpaceOrEnter(data.getDescription()), Jzvd.SCREEN_NORMAL);
                        //设置第一帧为封面
                        Glide.with(context)
                                .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));
                            }
                        }
                        ReadOnlyImageAdapter imageAdapter = new ReadOnlyImageAdapter(context, urls);
                        viewBinding.handleGridView.setAdapter(imageAdapter);
                        //九宫格点击事件
                        viewBinding.handleGridView.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);
                                }
                            }
                        });
                    }

                    //获取处置类型
                    nodeViewModel.obtainNextNode(String.valueOf(data.getCaseState()));
                }
            }
        });
        caseViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "获取数据中...");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });

        nodeViewModel.nodeModel.observe(this, new Observer<CaseNextNodeBean>() {
            @Override
            public void onChanged(CaseNextNodeBean resultBean) {
                if (resultBean.getCode() == 200) {
                    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());//默认选择第一个
                    }
                } else {
                    StringHub.show(context, "该案卷无下级流转节点");
                }
            }
        });

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

        viewBinding.caseOptTypeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (nodeDataBeans.size() >= 1) {
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                    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);

                            CaseNextNodeBean.DataBean nodeBean = nodeDataBeans.get(position);
                            changeState = String.valueOf(nodeBean.getNextState());
                            operationKey = nodeBean.getOperationKey();
                        }
                    }).build().show();
                }
            }
        });

        viewBinding.commonTipsLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new QMUIBottomSheet.BottomListSheetBuilder(context)
                        .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);
                            }
                        }).build().show();
            }
        });

        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String optType = viewBinding.optTypeView.getText().toString();
                if (optType.equals("")) {
                    StringHub.show(context, "还未选择操作类型");
                    return;
                }
                String optionInput = StringHub.filterSpaceOrEnter(viewBinding.commonTipsView.getText().toString());
                if (TextUtils.isEmpty(optionInput)) {
                    StringHub.show(context, "处理意见必须填写");
                    return;
                }
                operateViewModel.dispatcherHandleCase(data.getProcessId(), id,
                        String.valueOf(data.getCaseState()), changeState, optionInput, operationKey, taskUserId);
            }
        });
        operateViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "案卷处理中，请稍后...");
                } else if (loadState == LoadState.Success) {
                    DialogHelper.dismissLoadingDialog();
                    finish();
                } else {
                    StringHub.show(context, "处理失败，请重试");
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        viewBinding.audioPlayerView.release();
        super.onDestroy();
    }

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

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