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.ActivityCaseDetailBinding;
import com.casic.dcms.model.CaseDetailBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.MapHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.vm.CaseViewModel;
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.Constant;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.vm.LoadState;

import java.util.ArrayList;

import cn.jzvd.Jzvd;

public class CaseDetailActivity extends AndroidxBaseActivity<ActivityCaseDetailBinding> {

    private final Context context = CaseDetailActivity.this;
    private CaseViewModel caseViewModel;
    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() {

    }

    @Override
    protected void initData() {
        String id = getIntent().getStringExtra(Constant.INTENT_PARAM);
        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);
        caseViewModel.obtainCaseDetail(id);
    }

    @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.caseStatusView.setText(data.getCaseStateName());
                    viewBinding.caseTypeView.setText(data.getEorcName());
                    viewBinding.caseLargeTypeView.setText(data.getCasetypeName());
                    viewBinding.caseSmallTypeView.setText(data.getCasetypeDetailName());
                    viewBinding.caseCommunityView.setText(data.getCommunityName());
                    viewBinding.casePlaceView.setText(StringHub.filterSpaceOrEnter(data.getFieldintro()));
                    viewBinding.caseSituationView.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.casePicGridView.setAdapter(imageAdapter);
                        //九宫格点击事件
                        viewBinding.casePicGridView.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 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);
                        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);
                                }
                            }
                        });
                    }

                    //核查图片
                    String checkImages = data.getFileIdCheck();
                    if (!TextUtils.isEmpty(checkImages)) {
                        ArrayList<String> urls = new ArrayList<>();
                        String[] split = checkImages.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.checkGridView.setAdapter(imageAdapter);
                        //九宫格点击事件
                        viewBinding.checkGridView.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);
                    }
                }
            }
        });
        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(v -> MapHelper.displayOnMap(this, data.getEorcName(), data.getLng(), data.getLat()));
        viewBinding.handleRecordLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContextHub.navigatePageTo(context, CaseProcessActivity.class, data.getProcessId());
            }
        });
    }

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