package com.casic.dcms.view;

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.ActivityCaseTodoDetailBinding;
import com.casic.dcms.model.CaseDetailBean;
import com.casic.dcms.model.ComSentenceBean;
import com.casic.dcms.utils.MapHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.vm.CaseOperateViewModel;
import com.casic.dcms.vm.CaseViewModel;
import com.casic.dcms.vm.CommonDataViewModel;
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.StringKit;
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.util.ArrayList;
import java.util.List;

public class CaseTodoDetailActivity extends AndroidxBaseActivity<ActivityCaseTodoDetailBinding> {

    private final Context context = this;
    private String id;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();
    private CaseViewModel caseViewModel;
    private CommonDataViewModel commonViewModel;
    private CaseOperateViewModel operateViewModel;
    private OrientationUtils orientationUtils;
    private boolean isPlay;
    private boolean isPause;

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

        String title = getIntent().getStringExtra("title");
        binding.titleBarLayout.titleView.setText(title);
        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(CaseTodoDetailActivity.this, "获取数据中...");
                } else {
                    LoadingDialog.dismiss();
                }
            }
        });

        operateViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    LoadingDialog.show(CaseTodoDetailActivity.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("id");
        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.caseOverTimeView.setText(data.getNodeLimittime());
                    binding.caseHandleStatusView.setText(data.getCaseStateName().equals("") ? "案卷状态未知" : data.getCaseStateName());
                    binding.casePlaceView.setText(data.getFieldintro());
                    binding.caseDescriptionView.setText(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));
                            }
                        }
                        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);
                        //TODO
//                        binding.audioPlayerView.setAudioUrl(StringHelper.appendCompleteURL(audioFile));
                    }

                    //视频
                    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);
                            }
                        });
                    }
                }
            }
        });

        commonViewModel = new ViewModelProvider(this).get(CommonDataViewModel.class);
        commonViewModel.sentenceModel.observe(this, new Observer<ComSentenceBean>() {
            @Override
            public void onChanged(ComSentenceBean resultBean) {
                if (resultBean.getCode() == 200) {
                    List<ComSentenceBean.DataBean> dataBeans = resultBean.getData();
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                    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);
                            binding.caseHandleResultView.setText(dataBean.getName());
                        }
                    }).build().show();
                }
            }
        });

        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.caseHandleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContextKit.navigatePageTo(context, CaseProcessActivity.class, data.getProcessId());
            }
        });

        binding.caseCommonSentenceLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commonViewModel.getCommonSentence(context);
            }
        });

        binding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String remarks = binding.caseHandleResultView.getText().toString();
                if (TextUtils.isEmpty(remarks)) {
                    StringKit.show(context, "督办意见不能为空");
                    return;
                }
                operateViewModel.updateCaseSupervise(context, id, remarks);
            }
        });
    }

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