package com.casic.dcms.view.verify;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
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.ActivityVerifyDetailBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.CaseDetailBean;
import com.casic.dcms.model.CaseLargeTypeBean;
import com.casic.dcms.model.CaseNextNodeBean;
import com.casic.dcms.model.CaseSmallTypeBean;
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.view.map.ArcGISMapActivity;
import com.casic.dcms.vm.CaseOperateViewModel;
import com.casic.dcms.vm.CaseViewModel;
import com.casic.dcms.vm.CommonDataViewModel;
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 VerifyDetailActivity extends AndroidxBaseActivity<ActivityVerifyDetailBinding> {

    private final Context context = VerifyDetailActivity.this;
    private final ArrayList<String> realPaths = new ArrayList<>();//真实图片路径
    private final List<String> imageList = new ArrayList<>();//上传到服务器的数据集
    private CaseViewModel caseViewModel;
    private CommonDataViewModel commonDataViewModel;
    private UploadViewModel uploadViewModel;
    private NodeViewModel nodeViewModel;
    private CaseOperateViewModel operateViewModel;
    private List<CaseLargeTypeBean.DataBean> largeTypeBeans;
    private List<CaseSmallTypeBean.DataBean> smallTypeBeans;
    private String id;
    private String eorc;
    private String typeCode;
    private String typeDetailCode;
    private String gridId;//可能来自案卷详情，也可能来自地图选点
    private double longitude, latitude;
    private String changeState;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();
    private EditableImageAdapter verifyImageAdapter;

    private final ActivityResultLauncher<Intent> verifyCaseLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == Activity.RESULT_OK) {
                Intent data = result.getData();
                if (data == null) {
                    return;
                }
                longitude = data.getDoubleExtra("longitude", 0);
                latitude = data.getDoubleExtra("latitude", 0);
                gridId = data.getStringExtra("gridId");
                String community = data.getStringExtra("community");
                String casePlace = data.getStringExtra("pos");
                viewBinding.caseCommunityView.setText(community);
                if (TextUtils.isEmpty(casePlace)) {
                    viewBinding.casePlaceView.setText(community);
                } else {
                    viewBinding.casePlaceView.setText(casePlace);
                }
            }
        }
    });

    @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
    public void initData() {
        id = getIntent().getStringExtra(Constant.INTENT_PARAM);

        largeTypeBeans = new ArrayList<>();
        smallTypeBeans = new ArrayList<>();

        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);
                    gridId = data.getGridId();
                    String lng = data.getLng();
                    if (!TextUtils.isEmpty(lng)) {
                        longitude = Double.parseDouble(lng);
                    }
                    String lat = data.getLat();
                    if (!TextUtils.isEmpty(lat)) {
                        latitude = Double.parseDouble(lat);
                    }
                    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.caseHandleView.setText(data.getCaseStateName().equals("") ? "无处理意见" : data.getCaseStateName());
                    viewBinding.caseStartTimeView.setText(data.getCreateTime());
                    viewBinding.caseEndTimeView.setText(data.getNodeLimittime());
                    viewBinding.caseSituationView.setText(StringHub.filterSpaceOrEnter(data.getDescription()));

                    //根据source判断是否能够修改案卷类型，11/12是公众号和热线电话，案卷类型可修改；否则不可修改
                    int source = data.getSource();
                    if (source != 11 && source != 12) {
                        viewBinding.caseTypeRightImage.setVisibility(View.GONE);
                        viewBinding.largeTypeRightImage.setVisibility(View.GONE);
                        viewBinding.smallTypeRightImage.setVisibility(View.GONE);

                        viewBinding.caseClassLayout.setClickable(false);
                        viewBinding.caseLargeClassLayout.setClickable(false);
                        viewBinding.caseSmallClassLayout.setClickable(false);
                    }

                    //图片
                    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);
                        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);
                    }
                }
            }
        });

        commonDataViewModel = new ViewModelProvider(this).get(CommonDataViewModel.class);
        commonDataViewModel.largeTypeModel.observe(this, new Observer<CaseLargeTypeBean>() {
            @Override
            public void onChanged(CaseLargeTypeBean typeBean) {
                if (typeBean.getCode() == 200) {
                    //设置大类数据
                    largeTypeBeans = typeBean.getData();
                    if (largeTypeBeans.size() == 0) {
                        viewBinding.caseLargeTypeView.setText("无小类");
                    } else {
                        viewBinding.caseLargeTypeView.setText(largeTypeBeans.get(0).getTypeName());//默认选择第一个
                    }
                    viewBinding.caseSmallTypeView.setText("请选择");
                }
            }
        });
        commonDataViewModel.smallTypeModel.observe(this, new Observer<CaseSmallTypeBean>() {
            @Override
            public void onChanged(CaseSmallTypeBean typeBean) {
                if (typeBean.getCode() == 200) {
                    smallTypeBeans = typeBean.getData();
                    if (smallTypeBeans.size() == 0) {
                        viewBinding.caseSmallTypeView.setText("无小类");
                    } else {
                        viewBinding.caseSmallTypeView.setText(smallTypeBeans.get(0).getTypeDetailName());//默认选择第一个
                    }
                }
            }
        });

        uploadViewModel = new ViewModelProvider(this).get(UploadViewModel.class);
        uploadViewModel.imageModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.isSuccess()) {
                    if (verifyImageAdapter.getItemCount() <= 3) {
                        String url = resultBean.getData();
                        imageList.add(url);
                        realPaths.add(StringHelper.appendCompleteURL(url));
                        verifyImageAdapter.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.isSuccess()) {
                    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.caseConditionView.setText(dataBean.getNextOperation());
                            changeState = String.valueOf(dataBean.getNextState());
                        }
                    }).build().show();
                } else {
                    StringHub.show(context, "该案卷无下级流转节点");
                }
            }
        });

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

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

    @Override
    public void initEvent() {
        viewBinding.caseClassLayout.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();
                                viewBinding.caseTypeView.setText(tag);
                                //获取案卷大类
                                commonDataViewModel.obtainLargeType(String.valueOf(position + 1));
                            }
                        }).build().show();
            }
        });

        viewBinding.caseLargeClassLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (largeTypeBeans.size() > 1) {
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                    sheetBuilder.setTitle("案卷大类");
                    for (CaseLargeTypeBean.DataBean dataBean : largeTypeBeans) {
                        sheetBuilder.addItem(dataBean.getTypeName());
                    }
                    sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                        @Override
                        public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                            dialog.dismiss();
                            typeCode = largeTypeBeans.get(position).getTypeCode();

                            viewBinding.caseLargeTypeView.setText(tag);

                            //获取案卷小类
                            CaseLargeTypeBean.DataBean dataBean = largeTypeBeans.get(position);
                            eorc = dataBean.getEorc();
                            String typeId = dataBean.getId();
                            commonDataViewModel.obtainSmallType(eorc, typeId);
                        }
                    }).build().show();
                }
            }
        });

        viewBinding.caseSmallClassLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (smallTypeBeans.size() > 1) {
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                    sheetBuilder.setTitle("案卷小类");
                    for (CaseSmallTypeBean.DataBean dataBean : smallTypeBeans) {
                        sheetBuilder.addItem(dataBean.getTypeDetailName());
                    }
                    sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                        @Override
                        public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                            dialog.dismiss();
                            typeDetailCode = smallTypeBeans.get(position).getTypeDetailCode();

                            viewBinding.caseSmallTypeView.setText(tag);
                        }
                    }).build().show();
                }
            }
        });

        viewBinding.locationMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = viewBinding.caseTypeView.getText().toString();
                if (type.equals("请选择")) {
                    StringHub.show(context, "请先选择案卷类型");
                    return;
                }
                int source = data.getSource();
                if (source == 11 || source == 12) {
                    Intent intent = new Intent(context, ArcGISMapActivity.class);
                    intent.putExtra("type", type);
                    verifyCaseLauncher.launch(intent);
                } else {
                    MapHelper.displayOnMap(context, data.getEorcName(), data.getLng(), data.getLat());
                }
            }
        });

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

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

        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitCase();
            }
        });
    }

    private void submitCase() {
        String remarks = viewBinding.caseConditionView.getText().toString();
        if (TextUtils.isEmpty(remarks)) {
            StringHub.show(this, "核实意见不能为空");
            return;
        }
        if (TextUtils.isEmpty(changeState)) {
            StringHub.show(this, "核实情况还未选择");
            return;
        }
        int source = data.getSource();
        if (source != 11 && source != 12) {
            //修改案卷
            operateViewModel.checkCase(data.getProcessId(), id, String.valueOf(data.getCaseState()),
                    changeState, remarks, StringHelper.reformatURL(imageList));
        } else {
            //补全案卷
            if (TextUtils.isEmpty(gridId)) {
                StringHub.show(this, "网格ID异常，请重新选择");
                return;
            }
            String fieldIntro = viewBinding.casePlaceView.getText().toString();
            if (TextUtils.isEmpty(fieldIntro)) {
                StringHub.show(this, "案卷地点还未填写");
            }
            if (longitude == 0 || latitude == 0) {
                StringHub.show(this, "经纬度异常，请重新选择位置");
                return;
            }
            operateViewModel.verifyCase(data.getProcessId(), id, String.valueOf(data.getCaseState()),
                    changeState, remarks, StringHelper.reformatURL(imageList),
                    eorc == null ? data.getEorc() : eorc,
                    typeCode == null ? data.getCasetypeCode() : typeCode,
                    typeDetailCode == null ? data.getCasetypeDetailCode() : typeDetailCode,
                    String.valueOf(longitude), String.valueOf(latitude),
                    "1", gridId.substring(0, 6),
                    gridId.substring(0, 9), data.getCommunityCode(), gridId, fieldIntro);
        }
    }

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