package com.casic.dcms.view;

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.ActivityCaseTodoDetailBinding;
import com.casic.dcms.model.CaseDetailBean;
import com.casic.dcms.model.ComSentenceBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.MapHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.vm.CaseOperateViewModel;
import com.casic.dcms.vm.CaseViewModel;
import com.casic.dcms.vm.CommonDataViewModel;
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 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;

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

        commonViewModel = new ViewModelProvider(this).get(CommonDataViewModel.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.caseOverTimeView.setText(data.getNodeLimittime());
                    viewBinding.caseHandleStatusView.setText(data.getCaseStateName().equals("") ? "案卷状态未知" : data.getCaseStateName());
                    viewBinding.casePlaceView.setText(StringHub.filterSpaceOrEnter(data.getFieldintro()));
                    viewBinding.caseDescriptionView.setText(StringHub.filterSpaceOrEnter(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);
                        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);
                    }
                }
            }
        });
        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.caseHandleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContextHub.navigatePageTo(context, CaseProcessActivity.class, data.getProcessId());
            }
        });
        viewBinding.caseCommonSentenceLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commonViewModel.obtainCommonSentence();
            }
        });
        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);
                            viewBinding.caseHandleResultView.setText(dataBean.getName());
                        }
                    }).build().show();
                }
            }
        });

        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String remarks = viewBinding.caseHandleResultView.getText().toString();
                if (TextUtils.isEmpty(remarks)) {
                    StringHub.show(context, "督办意见不能为空");
                    return;
                }
                operateViewModel.updateCaseSupervise(id, remarks);
            }
        });
        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();
    }
}
