package com.casic.dcms.view.handle;

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.ActivityCaseHandleDetailBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.CaseDetailBean;
import com.casic.dcms.model.CaseNextNodeBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.MapHelper;
import com.casic.dcms.utils.PictureSelectorHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.callback.ISelectorListener;
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.casic.dcms.vm.UploadViewModel;
import com.gyf.immersionbar.ImmersionBar;
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.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 com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet.BottomListSheetBuilder;

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

import cn.jzvd.Jzvd;

public class CaseHandleDetailActivity extends AndroidxBaseActivity<ActivityCaseHandleDetailBinding> {

    private final Context context = CaseHandleDetailActivity.this;
    private final ArrayList<String> realPaths = new ArrayList<>(); //真实图片路径
    private final List<String> imageList = new ArrayList<>(); //上传到服务器的数据集
    private CaseViewModel caseViewModel;
    private UploadViewModel uploadViewModel;
    private NodeViewModel nodeViewModel;
    private CaseOperateViewModel operateViewModel;
    private String id;
    private String changeState;
    private String caseReason;
    private String approvalResult;
    private EditableImageAdapter handleImageAdapter;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();

    @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
    protected void initData() {
        id = getIntent().getStringExtra("id");
        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);
        caseViewModel.obtainCaseDetail(id);

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

        handleImageAdapter = new EditableImageAdapter(this, 3, 13);
        viewBinding.addImageRecyclerView.setAdapter(handleImageAdapter);
    }

    @Override
    protected void initEvent() {
        caseViewModel.caseDetailModel.observe(this, new Observer<CaseDetailBean>() {
            @Override
            public void onChanged(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(StringHub.filterSpaceOrEnter(data.getFieldintro()));
                    viewBinding.caseSituationView.setText(StringHub.filterSpaceOrEnter(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));
                            }
                        }
                        ReadOnlyImageAdapter imageAdapter = new ReadOnlyImageAdapter(context, urls);
                        viewBinding.imageGridView.setAdapter(imageAdapter);
                        //九宫格点击事件
                        viewBinding.imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                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);
                    }
                    viewBinding.caseStartTimeView.setText(data.getCreateTime());
                    viewBinding.caseEndTimeView.setText(data.getNodeLimittime());
                }
            }
        });
        caseViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "获取数据中...");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });

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

        viewBinding.caseHandleResultLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nodeViewModel.obtainNextNode(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();
                    BottomListSheetBuilder sheetBuilder = new BottomListSheetBuilder(context);
                    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.reasonLayout.setVisibility(View.GONE);
                                    } else {
                                        viewBinding.reasonLayout.setVisibility(View.VISIBLE);
                                    }
                                    changeState = String.valueOf(dataBean.getNextState());
                                    approvalResult = dataBean.getApprovalResult();
                                }
                            }).build().show();
                } else {
                    StringHub.show(context, "该案卷无下级流转节点");
                }
            }
        });

        //图片九宫格事件处理
        handleImageAdapter.setOnItemClickListener(new EditableImageAdapter.OnItemClickListener() {
            @Override
            public void onAddImageClick() {
                PictureSelectorHelper.selectPicture(context, new ISelectorListener() {
                    @Override
                    public void onSuccess(ArrayList<LocalMedia> result) {
                        if (result.size() == 1) {
                            uploadViewModel.uploadImage(new File(result.get(0).getRealPath()));
                        } else {
                            for (LocalMedia localMedia : result) {
                                uploadViewModel.uploadImage(new File(localMedia.getRealPath()));
                            }
                        }
                    }
                });
            }

            @Override
            public void onItemClick(int position) {
                if (realPaths.get(position).isEmpty()) {
                    StringHub.show(context, "图片加载失败，无法查看大图");
                } else {
                    ContextHub.navigatePageTo(context, BigImageActivity.class, position, realPaths);
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
                imageList.remove(position);
                handleImageAdapter.deleteImage(position);
            }
        });
        uploadViewModel.imageModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    if (handleImageAdapter.getItemCount() <= 3) {
                        String url = resultBean.getData();
                        imageList.add(url);
                        realPaths.add(StringHelper.appendCompleteURL(url));
                        handleImageAdapter.setupImage(realPaths);
                    } else {
                        StringHub.show(context, "最多只能上传3张图片");
                    }
                }
            }
        });
        uploadViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "上传中，请稍后...");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });

        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String handleResult = viewBinding.caseHandleResultView.getText().toString();
                if (handleResult.equals("")) {
                    StringHub.show(context, "还未选择处理结果");
                    return;
                }
                if (handleResult.equals("处理完成")) {
                    //选择处理完成时，处理图片必传。至少一张，最多两张
                    if (handleImageAdapter.getItemCount() < 1) {
                        StringHub.show(context, "当前案卷状态必须上传至少一张图片");
                        return;
                    }
                }
                if (handleResult.equals("申请延期") || handleResult.equals("申请调整")) {
                    caseReason = viewBinding.caseReasonView.getText().toString();
                    if (TextUtils.isEmpty(caseReason)) {
                        StringHub.show(context, "延期/调整的原因必须填写");
                        return;
                    }
                }
                operateViewModel.handleOvertimeCase(
                        data.getProcessId(), id, String.valueOf(data.getCaseState()),
                        changeState, caseReason, StringHelper.reformatURL(imageList), approvalResult
                );
            }
        });
        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
    public void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }
}