package com.casic.dcms.view.dept;

import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityDeptAuthorizeBinding;
import com.casic.dcms.model.CaseDetailBean;
import com.casic.dcms.model.CaseNextNodeBean;
import com.casic.dcms.model.ProcessPersonBean;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.MapHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ViewGroupKit;
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.WorkerViewModel;
import com.pengxh.androidx.lite.adapter.ReadOnlyImageAdapter;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.kit.ContextKit;
import com.pengxh.androidx.lite.kit.IntKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.Constant;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;

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


public class DeptAuthorizeDetailActivity extends AndroidxBaseActivity<ActivityDeptAuthorizeBinding> {

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

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);

        binding.titleBarLayout.titleView.setText(LocaleConstant.DEPT_PAGE_TITLES[4]);
        binding.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) {
                    LoadingDialog.show(DeptAuthorizeDetailActivity.this, "获取数据中...");
                } else {
                    LoadingDialog.dismiss();
                }
            }
        });

        operateViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    LoadingDialog.show(DeptAuthorizeDetailActivity.this, "案卷处理中，请稍后...");
                } else if (loadState == LoadState.Success) {
                    LoadingDialog.dismiss();
                    finish();
                } else {
                    StringKit.show(context, "处理失败，请重试");
                    LoadingDialog.dismiss();
                }
            }
        });
    }

    @Override
    public void initOnCreate(@Nullable Bundle savedInstanceState) {
        orientationUtils = new OrientationUtils(this, binding.videoPlayerView);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);

        id = getIntent().getStringExtra(Constant.INTENT_PARAM_KEY);
        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);
        caseViewModel.getCaseDetail(this, id);
        caseViewModel.caseDetailModel.observe(this, new Observer<CaseDetailBean>() {
            @Override
            public void onChanged(CaseDetailBean resultBean) {
                if (resultBean.isSuccess()) {
                    data = resultBean.getData().get(0);
                    binding.caseNumberView.setText(data.getCaseid());
                    binding.caseResourceView.setText(data.getSourceName());
                    binding.caseCreatorView.setText(data.getCreateUserName());
                    binding.caseTypeView.setText(data.getEorcName());
                    binding.caseLargeTypeView.setText(data.getCasetypeName());
                    binding.caseSmallTypeView.setText(data.getCasetypeDetailName());
                    binding.caseCommunityView.setText(data.getCommunityName().equals("") ? "无更详细社区信息" : data.getCommunityName());
                    binding.casePlaceView.setText(data.getFieldintro());
                    binding.caseSituationView.setText(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);
                        binding.imageGridView.setAdapter(imageAdapter);
                        //九宫格点击事件
                        binding.imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (urls.get(position).isEmpty()) {
                                    StringKit.show(context, "图片加载失败，无法查看大图");
                                } else {
                                    ContextKit.navigatePageTo(context, BigImageActivity.class, position, urls);
                                }
                            }
                        });
                    }

                    String audioFile = data.getAudioIdVerify();
                    if (!TextUtils.isEmpty(audioFile)) {
                        binding.audioPlayerView.setVisibility(View.VISIBLE);
                        String url = StringHelper.appendCompleteURL(audioFile);
                        try {
                            binding.audioPlayerView.setAudioSource(new File(url));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    String videoFile = data.getVideoIdVerify();
                    if (!TextUtils.isEmpty(videoFile)) {
                        binding.videoPlayerView.setVisibility(View.VISIBLE);
                        String videoUrl = StringHelper.appendCompleteURL(videoFile);
                        GSYVideoOptionBuilder videoOption = new GSYVideoOptionBuilder();
                        videoOption.setIsTouchWiget(true)
                                .setRotateViewAuto(false)
                                .setLockLand(false)
                                .setAutoFullWithSize(true)
                                .setShowFullAnimation(false)
                                .setNeedLockFull(true)
                                .setUrl(videoUrl)
                                .setCacheWithPlay(false)
                                .setVideoTitle(data.getDescription())
                                .setVideoAllCallBack(new GSYSampleCallBack() {
                                    @Override
                                    public void onPrepared(String url, Object... objects) {
                                        super.onPrepared(url, objects);
                                        //开始播放了才能旋转和全屏
                                        orientationUtils.setEnable(true);
                                        isPlay = true;
                                    }

                                    @Override
                                    public void onQuitFullscreen(String url, Object... objects) {
                                        super.onQuitFullscreen(url, objects);
                                        if (orientationUtils != null) {
                                            orientationUtils.backToProtVideo();
                                        }
                                    }
                                }).setLockClickListener(new LockClickListener() {
                                    @Override
                                    public void onClick(View view, boolean lock) {
                                        if (orientationUtils != null) {
                                            //配合下方的onConfigurationChanged
                                            orientationUtils.setEnable(!lock);
                                        }
                                    }
                                }).build(binding.videoPlayerView);
                        binding.videoPlayerView.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //直接横屏
                                orientationUtils.resolveByClick();
                                binding.videoPlayerView.startWindowFullscreen(context, true, true);
                            }
                        });
                    }

                    //处理图片
                    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);
                        binding.handleGridView.setAdapter(imageAdapter);
                        //九宫格点击事件
                        binding.handleGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (urls.get(position).isEmpty()) {
                                    StringKit.show(context, "图片加载失败，无法查看大图");
                                } else {
                                    ContextKit.navigatePageTo(context, BigImageActivity.class, position, urls);
                                }
                            }
                        });
                    }

                    //获取处置类型
                    nodeViewModel.getNextNode(context, String.valueOf(data.getCaseState()));
                    //获取下级处置人员
                    workerViewModel.getSubordinateWorker(context);
                }
            }
        });

        nodeViewModel = new ViewModelProvider(this).get(NodeViewModel.class);
        nodeViewModel.nodeModel.observe(this, new Observer<CaseNextNodeBean>() {
            @Override
            public void onChanged(CaseNextNodeBean resultBean) {
                if (resultBean.getCode() == 200) {
                    nodeDataBeans = resultBean.getData();
                    if (nodeDataBeans.size() == 0) {
                        binding.optTypeView.setText("无下级流转节点");
                    } else {
                        CaseNextNodeBean.DataBean dataBean = nodeDataBeans.get(0);

                        operationKey = dataBean.getOperationKey();
                        changeState = String.valueOf(dataBean.getNextState());
                        binding.optTypeView.setText(dataBean.getNextOperation());//默认选择第一个
                    }
                    binding.optTypeView.setTextColor(IntKit.convertColor(context, R.color.mainTextColor));
                } else {
                    StringKit.show(context, "该案卷无下级流转节点");
                }
            }
        });

        workerViewModel = new ViewModelProvider(this).get(WorkerViewModel.class);
        workerViewModel.processPersonModel.observe(this, new Observer<ProcessPersonBean>() {
            @Override
            public void onChanged(ProcessPersonBean resultBean) {
                if (resultBean.getCode() == 200) {
                    personBeans = resultBean.getData();
                }
            }
        });

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

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

        binding.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();
                            binding.optTypeView.setText(tag);
                            binding.optTypeView.setTextColor(IntKit.convertColor(context, R.color.mainTextColor));

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

                            if (binding.optTypeView.getText().toString().equals("处置人员") || binding.optTypeView.getText().toString().equals("返回处理")) {
                                binding.handlePersonLayout.setVisibility(View.VISIBLE);

                                //处置人员列表
                                binding.handlePersonLayout.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                                        sheetBuilder.setTitle("处置人员");
                                        for (ProcessPersonBean.DataBean dataBean : personBeans) {
                                            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();

                                                binding.handlePersonView.setText(tag);
                                                taskUserId = personBeans.get(position).getId();
                                            }
                                        }).build().show();
                                    }
                                });
                            } else {
                                binding.handlePersonLayout.setVisibility(View.GONE);
                            }
                        }
                    }).build().show();
                }
            }
        });

        binding.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();
                                binding.commonTipsView.setText(tag);
                                binding.commonTipsView.setTextColor(IntKit.convertColor(context, R.color.mainTextColor));
                            }
                        }).build().show();
            }
        });

        binding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String optType = binding.optTypeView.getText().toString();
                if (optType.equals("")) {
                    StringKit.show(context, "还未选择操作类型");
                    return;
                }
                if (optType.equals("返回处理")) {
                    //选择处理人员时，必选一个处置人员
                    String handlePerson = binding.handlePersonView.getText().toString();
                    if (handlePerson.equals("")) {
                        StringKit.show(context, "当前状态必须指定处置员");
                        return;
                    }
                }
                String optionInput = binding.commonTipsView.getText().toString();
                if (TextUtils.isEmpty(optionInput)) {
                    StringKit.show(context, "处理意见必须填写");
                    return;
                }
                operateViewModel.dispatcherHandleCase(context, data.getProcessId(), id,
                        String.valueOf(data.getCaseState()), changeState, optionInput, "", operationKey, taskUserId);
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        binding.videoPlayerView.getCurrentPlayer().onVideoPause();
        super.onPause();
        isPause = true;
    }

    @Override
    protected void onResume() {
        binding.videoPlayerView.getCurrentPlayer().onVideoResume(false);
        super.onResume();
        isPause = false;
    }

    @Override
    protected void onDestroy() {
        if (isPlay) {
            binding.videoPlayerView.getCurrentPlayer().release();
        }
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            binding.videoPlayerView.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }
}
