package com.casic.dcms.view.check;

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.ActivityCheckDetailBinding;
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.Constant;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.vm.LoadState;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

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

import cn.jzvd.Jzvd;

public class CheckDetailActivity extends AndroidxBaseActivity<ActivityCheckDetailBinding> {

    private final Context context = CheckDetailActivity.this;
    private final ArrayList<String> realPaths = new ArrayList<>(); //真实图片路径
    private final ArrayList<String> imageList = new ArrayList<>(); //上传到服务器的数据集
    private CaseViewModel caseViewModel;
    private UploadViewModel uploadViewModel;
    private NodeViewModel nodeViewModel;
    private CaseOperateViewModel operateViewModel;
    private String id;
    private String changeState;
    private EditableImageAdapter checkImageAdapter;
    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();

        viewBinding.titleBarLayout.titleView.setText("案卷核查详情");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void observeRequestState() {
        caseViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "获取数据中...");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });

        uploadViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "上传中，请稍后...");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });

        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 initData() {
        id = getIntent().getStringExtra(Constant.INTENT_PARAM);
        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);
        caseViewModel.obtainCaseDetail(id);
        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.getProcessRemarks().equals("") ? "无" : data.getProcessRemarks());
                    viewBinding.caseStartTimeView.setText(data.getCreateTime());
                    viewBinding.caseEndTimeView.setText(data.getNodeLimittime());
                    /**
                     * 图片
                     */
                    //核实照片
                    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);
                    }

                    //处理照片
                    String processImages = data.getFileIdProcess();
                    if (!TextUtils.isEmpty(processImages)) {
                        ArrayList<String> urls = new ArrayList<>();
                        String[] split = processImages.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<?> adapterView, View view, int position, long l) {
                                if (urls.get(position).isEmpty()) {
                                    StringHub.show(context, "图片加载失败，无法查看大图");
                                } else {
                                    ContextHub.navigatePageTo(context, BigImageActivity.class, position, urls);
                                }
                            }
                        });
                    }
                    viewBinding.caseHandleResultView.setText(data.getProcessRemarks().equals("") ? "无处理意见" : data.getProcessRemarks());
                    //TODO 服务器返回数据缺少此字段，暂时注掉
//                    viewBinding.caseHandleTimeView.setText();
                }
            }
        });

        uploadViewModel = new ViewModelProvider(this).get(UploadViewModel.class);
        uploadViewModel.imageModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    if (checkImageAdapter.getItemCount() <= 3) {
                        String url = resultBean.getData();
                        imageList.add(url);
                        realPaths.add(StringHelper.appendCompleteURL(url));
                        checkImageAdapter.setupImage(realPaths);
                    } else {
                        StringHub.show(context, "最多只能上传3张图片");
                    }
                }
            }
        });

        nodeViewModel = new ViewModelProvider(this).get(NodeViewModel.class);
        nodeViewModel.nodeModel.observe(this, new Observer<CaseNextNodeBean>() {
            @Override
            public void onChanged(CaseNextNodeBean resultBean) {
                if (resultBean.getCode() == 200) {
                    List<CaseNextNodeBean.DataBean> dataBeans = resultBean.getData();
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                    sheetBuilder.setTitle("核实情况");
                    for (CaseNextNodeBean.DataBean dataBean : dataBeans) {
                        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();
                                    CaseNextNodeBean.DataBean dataBean = dataBeans.get(position);
                                    viewBinding.caseCheckOptView.setText(dataBean.getNextOperation());
                                    changeState = String.valueOf(dataBean.getNextState());
                                }
                            }).build().show();
                } else {
                    StringHub.show(context, "该案卷无下级流转节点");
                }
            }
        });

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

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

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

        //图片九宫格事件处理
        checkImageAdapter.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);
                checkImageAdapter.deleteImage(position);
            }
        });


        viewBinding.caseCheckLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nodeViewModel.obtainNextNode(String.valueOf(data.getCaseState()));
            }
        });

        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //案卷提交
                String remarks = viewBinding.caseCheckOptView.getText().toString();
                if (TextUtils.isEmpty(remarks)) {
                    StringHub.show(context, "核查意见不能为空");
                    return;
                }
                if (TextUtils.isEmpty(changeState)) {
                    StringHub.show(context, "核查情况还未选择");
                    return;
                }
                operateViewModel.checkCase(data.getProcessId(), id,
                        String.valueOf(data.getCaseState()), changeState, remarks,
                        StringHelper.reformatURL(imageList)
                );
            }
        });
    }

    @Override
    public 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();
    }
}