package com.casic.dcms.ui;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
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.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.casic.dcms.R;
import com.casic.dcms.adapter.ImageGridViewAdapter;
import com.casic.dcms.adapter.NineGridImageAdapter;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.CaseDetailBean;
import com.casic.dcms.bean.CaseLargeClassBean;
import com.casic.dcms.bean.CaseNextNodeBean;
import com.casic.dcms.bean.CaseSmallClassBean;
import com.casic.dcms.databinding.ActivityCaseVerifyDetailBinding;
import com.casic.dcms.mvp.presenter.impl.CaseDetailPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.CaseHandlePresenterImpl;
import com.casic.dcms.mvp.presenter.impl.CaseLargeClassPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.CaseNextNodePresenterImpl;
import com.casic.dcms.mvp.presenter.impl.CaseSmallClassPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.UploadImagePresenterImpl;
import com.casic.dcms.mvp.view.ICaseDetailHandleView;
import com.casic.dcms.mvp.view.ICaseDetailView;
import com.casic.dcms.mvp.view.ICaseLargeClassView;
import com.casic.dcms.mvp.view.ICaseNextNodeView;
import com.casic.dcms.mvp.view.ICaseSmallClassView;
import com.casic.dcms.mvp.view.IUploadFileView;
import com.casic.dcms.ui.fragment.verify.CaseVerifiedFragment;
import com.casic.dcms.ui.fragment.verify.CaseVerifyFragment;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.JzExoMedia;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ToastHelper;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

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

import cn.jzvd.Jzvd;

public class CaseVerifyDetailActivity extends AndroidxBaseActivity<ActivityCaseVerifyDetailBinding> implements ICaseDetailView, View.OnClickListener,
        ICaseLargeClassView, ICaseSmallClassView, IUploadFileView, ICaseNextNodeView, ICaseDetailHandleView {

    private final Context context = this;
    private final ArrayList<String> realPaths = new ArrayList<>();//真实图片路径
    private final List<String> imageList = new ArrayList<>();//上传到服务器的数据集
    private CaseDetailPresenterImpl caseDetailPresenter;
    private CaseLargeClassPresenterImpl caseLargeClassPresenter;
    private List<CaseLargeClassBean.DataBean> largeClassBeans;
    private CaseSmallClassPresenterImpl caseSmallClassPresenter;
    private List<CaseSmallClassBean.DataBean> smallClassBeans;
    private String id;
    private String eorc;
    private String typeCode;
    private String typeDetailCode;
    private String gridId;//可能来自案卷详情，也可能来自地图选点
    private double longitude, latitude;
    private String changeState;
    private UploadImagePresenterImpl uploadImagePresenter;
    private QMUITipDialog submitDialog;
    private CaseNextNodePresenterImpl caseNextNodePresenter;
    private CaseHandlePresenterImpl caseHandlePresenter;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();
    private NineGridImageAdapter 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() {
        viewBinding.titleBarLayout.titleView.setText("案卷核实");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    public void initData() {
        largeClassBeans = new ArrayList<>();
        smallClassBeans = new ArrayList<>();

        id = getIntent().getStringExtra("id");
        caseDetailPresenter = new CaseDetailPresenterImpl(this);
        caseDetailPresenter.onReadyRetrofitRequest(id);
        caseLargeClassPresenter = new CaseLargeClassPresenterImpl(this);
        caseSmallClassPresenter = new CaseSmallClassPresenterImpl(this);
        uploadImagePresenter = new UploadImagePresenterImpl(this);
        submitDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("处理中，请稍后")
                .create();
        caseNextNodePresenter = new CaseNextNodePresenterImpl(this);
        caseHandlePresenter = new CaseHandlePresenterImpl(this);

        verifyImageAdapter = new NineGridImageAdapter(this);
        viewBinding.verifyGridView.setLayoutManager(new GridLayoutManager(this, 2));
        viewBinding.verifyGridView.setAdapter(verifyImageAdapter);
    }

    @Override
    public void initEvent() {
        viewBinding.caseClassLayout.setOnClickListener(this);
        viewBinding.caseLargeClassLayout.setOnClickListener(this);
        viewBinding.caseSmallClassLayout.setOnClickListener(this);
        viewBinding.locationMapView.setOnClickListener(this);
        viewBinding.caseConditionLayout.setOnClickListener(this);
        viewBinding.submitButton.setOnClickListener(this);
        viewBinding.submitButton.setChangeAlphaWhenPress(true);

        //图片九宫格事件处理
        verifyImageAdapter.setOnItemClickListener(new NineGridImageAdapter.OnItemClickListener() {
            @Override
            public void onAddImageClick() {
                new QMUIDialog.MenuDialogBuilder(context)
                        .addItem("相册中选取", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                OtherUtils.selectPicture(CaseVerifyDetailActivity.this);
                            }
                        })
                        .addItem("相机拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                OtherUtils.takePicture(CaseVerifyDetailActivity.this);
                            }
                        })
                        .create().show();
            }

            @Override
            public void onItemClick(int position) {
                OtherUtils.showBigImage(context, position, realPaths);
            }

            @Override
            public void onItemLongClick(View view, int position) {
                imageList.remove(position);
                verifyImageAdapter.deleteImage(position);
            }
        });
    }

    @Override
    public void obtainCaseDetailData(CaseDetailBean resultBean) {
        if (resultBean.getCode() == 200) {
            data = resultBean.getData().get(0);
            gridId = data.getGridId();
            String lng = data.getLng();
            if (!TextUtils.isEmpty(lng)) {
                this.longitude = Double.parseDouble(lng);
            }
            String lat = data.getLat();
            if (!TextUtils.isEmpty(lat)) {
                this.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(StringHelper.filterString(data.getFieldintro()));
            viewBinding.caseHandleView.setText(data.getCaseStateName().equals("") ? "无处理意见" : data.getCaseStateName());
            viewBinding.caseStartTimeView.setText(data.getCreateTime());
            viewBinding.caseEndTimeView.setText(data.getNodeLimittime());
            viewBinding.caseSituationView.setText(StringHelper.filterString(data.getDescription()));

            //根据source判断是否能够修改案卷类型，11/12是公众号和热线电话，其他类型不可修改
            int source = data.getSource();
            if (source != 11 && source != 12) {
                viewBinding.i.setVisibility(View.GONE);
                viewBinding.ii.setVisibility(View.GONE);
                viewBinding.iii.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));
                    }
                }
                ImageGridViewAdapter imageAdapter = new ImageGridViewAdapter(this);
                imageAdapter.setImageList(urls);
                viewBinding.casePicGridView.setAdapter(imageAdapter);
                //九宫格点击事件
                viewBinding.casePicGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        OtherUtils.showBigImage(context, 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, StringHelper.filterString(data.getDescription()), Jzvd.SCREEN_NORMAL, JzExoMedia.class);
                //设置第一帧为封面
                Glide.with(this)
                        .setDefaultRequestOptions(new RequestOptions().frame(4000000))
                        .load(videoUrl)
                        .into(viewBinding.videoPlayerView.posterImageView);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.caseClassLayout) {
            new QMUIBottomSheet.BottomListSheetBuilder(this)
                    .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);
                            //获取案卷大类
                            caseLargeClassPresenter.onReadyRetrofitRequest(String.valueOf(position + 1));
                        }
                    }).build().show();
        } else if (id == R.id.caseLargeClassLayout) {
            if (largeClassBeans != null) {
                if (largeClassBeans.size() > 1) {
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
                    sheetBuilder.setTitle("案卷大类");
                    for (CaseLargeClassBean.DataBean dataBean : largeClassBeans) {
                        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 = largeClassBeans.get(position).getTypeCode();

                            viewBinding.caseLargeTypeView.setText(tag);

                            //获取案卷小类
                            CaseLargeClassBean.DataBean dataBean = largeClassBeans.get(position);
                            eorc = dataBean.getEorc();
                            String typeId = dataBean.getId();
                            caseSmallClassPresenter.onReadyRetrofitRequest(eorc, typeId);
                        }
                    }).build().show();
                }
            }
        } else if (id == R.id.caseSmallClassLayout) {
            if (smallClassBeans != null) {
                if (smallClassBeans.size() > 1) {
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
                    sheetBuilder.setTitle("案卷小类");
                    for (CaseSmallClassBean.DataBean dataBean : smallClassBeans) {
                        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 = smallClassBeans.get(position).getTypeDetailCode();

                            viewBinding.caseSmallTypeView.setText(tag);
                        }
                    }).build().show();
                }
            }
        } else if (id == R.id.locationMapView) {
            String type = viewBinding.caseTypeView.getText().toString();
            if (type.equals("请选择")) {
                ToastHelper.showToast("请先选择案卷类型", ToastHelper.WARING);
                return;
            }
            int source = data.getSource();
            if (source == 11 || source == 12) {
                Intent intent = new Intent(this, ArcGISMapActivity.class);
                intent.putExtra("type", type);
                verifyCaseLauncher.launch(intent);
            } else {
                OtherUtils.displayOnMap(this, data.getEorcName(), data.getLng(), data.getLat());
            }
        } else if (id == R.id.caseConditionLayout) {
            caseNextNodePresenter.onReadyRetrofitRequest(String.valueOf(data.getCaseState()));
        } else if (id == R.id.submitButton) {
            submitCase();
        }
    }

    private void submitCase() {
        String remarks = viewBinding.caseOpinionView.getText().toString();
        if (TextUtils.isEmpty(remarks)) {
            ToastHelper.showToast("核实意见不能为空", ToastHelper.WARING);
            return;
        }
        if (TextUtils.isEmpty(changeState)) {
            ToastHelper.showToast("核实情况还未选择", ToastHelper.WARING);
            return;
        }
        int source = data.getSource();
        if (source != 11 && source != 12) {
            //修改案卷
            if (verifyImageAdapter.getItemCount() != 2) {
                ToastHelper.showToast("必须选择两张图片", ToastHelper.WARING);
                return;
            }
            caseHandlePresenter.onReadyRetrofitRequest(data.getProcessId(), id, String.valueOf(data.getCaseState()),
                    changeState, remarks, StringHelper.reformatURL(imageList));
        } else {
            //补全案卷
            if (TextUtils.isEmpty(gridId)) {
                ToastHelper.showToast("网格ID异常，请重新选择", ToastHelper.WARING);
                return;
            }
            String fieldIntro = viewBinding.casePlaceView.getText().toString();
            if (TextUtils.isEmpty(fieldIntro)) {
                ToastHelper.showToast("案卷地点还未填写", ToastHelper.WARING);
            }
            if (verifyImageAdapter.getItemCount() != 2) {
                ToastHelper.showToast("必须选择两张图片", ToastHelper.WARING);
                return;
            }
            if (longitude == 0 || latitude == 0) {
                ToastHelper.showToast("经纬度异常，请重新选择位置", ToastHelper.WARING);
                return;
            }
            caseHandlePresenter.onReadyRetrofitRequest(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
    public void obtainCaseHandleResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            ToastHelper.showToast("案卷审核成功", ToastHelper.SUCCESS);
            //案卷办完以后通知待办和已办刷新数据
            CaseVerifyFragment.sendEmptyMessage(Constant.CASE_VERIFY_OK);
            CaseVerifiedFragment.sendEmptyMessage(Constant.CASE_VERIFY_OK);
            finish();
        } else {
            ToastHelper.showToast("案卷审核失败，请重试", ToastHelper.ERROR);
        }
    }

    @Override
    public void obtainDataFail() {
        ToastHelper.showToast("操作失败", ToastHelper.ERROR);
    }

    @Override
    public void obtainLargeClassData(CaseLargeClassBean largeClassBean) {
        if (largeClassBean.isSuccess()) {
            //设置大类数据
            this.largeClassBeans = largeClassBean.getData();
            if (largeClassBeans.size() == 0) {
                viewBinding.caseLargeTypeView.setText("无小类");
            } else {
                viewBinding.caseLargeTypeView.setText(largeClassBeans.get(0).getTypeName());//默认选择第一个
            }
            viewBinding.caseSmallTypeView.setText("请选择");
        }
    }

    @Override
    public void obtainSmallClassData(CaseSmallClassBean smallClassBean) {
        if (smallClassBean.isSuccess()) {
            //设置大类数据
            this.smallClassBeans = smallClassBean.getData();
            if (smallClassBeans.size() == 0) {
                viewBinding.caseSmallTypeView.setText("无小类");
            } else {
                viewBinding.caseSmallTypeView.setText(smallClassBeans.get(0).getTypeDetailName());//默认选择第一个
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : selectList) {
                        File file = new File(media.getCompressPath());
                        if (file.length() <= Constant.IMAGE_MINUS_SIZE) {
                            ToastHelper.showToast("图片尺寸太小，请重新选择", ToastHelper.ERROR);
                            continue;
                        }
                        uploadImagePresenter.onReadyRetrofitRequest(file);
                    }
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    LocalMedia localMedia = PictureSelector.obtainMultipleResult(data).get(0);
                    uploadImagePresenter.onReadyRetrofitRequest(new File(localMedia.getCompressPath()));
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void showProgress() {
        submitDialog.show();
    }

    @Override
    public void hideProgress() {
        submitDialog.dismiss();
    }

    @Override
    public void obtainUploadAudioResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainUploadImageResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            PictureFileUtils.deleteAllCacheDirFile(this);
            /**
             * 系统路径static拼接图片返回路径
             * http://111.198.10.15:11409/static/2021-04/000bcf78345f4c1c86484efa3f9d68a2.jpeg
             */
            //2021-04\\000bcf78345f4c1c86484efa3f9d68a2.jpeg
            if (verifyImageAdapter.getItemCount() <= 2) {
                String url = resultBean.getData();
                imageList.add(url);
                realPaths.add(StringHelper.appendCompleteURL(url));
                verifyImageAdapter.setupImage(realPaths);
            } else {
                ToastHelper.showToast("最多只能上传2张图片", ToastHelper.WARING);
            }
        }
    }

    @Override
    public void obtainUploadVideoResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainNextNodeData(CaseNextNodeBean resultBean) {
        if (resultBean.isSuccess()) {
            List<CaseNextNodeBean.DataBean> dataBeans = resultBean.getData();
            QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
            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.caseOpinionView.setText(dataBean.getNextOperation());
                    viewBinding.caseConditionView.setText(dataBean.getNextOperation());
                    changeState = String.valueOf(dataBean.getNextState());
                }
            }).build().show();
        } else {
            ToastHelper.showToast("该案卷无下级流转节点", ToastHelper.ERROR);
        }
    }

    @Override
    protected void onDestroy() {
        if (caseDetailPresenter != null) {
            caseDetailPresenter.disposeRetrofitRequest();
        }
        if (caseLargeClassPresenter != null) {
            caseLargeClassPresenter.disposeRetrofitRequest();
        }
        if (caseSmallClassPresenter != null) {
            caseSmallClassPresenter.disposeRetrofitRequest();
        }
        if (uploadImagePresenter != null) {
            uploadImagePresenter.disposeRetrofitRequest();
        }
        if (caseNextNodePresenter != null) {
            caseNextNodePresenter.disposeRetrofitRequest();
        }
        if (caseHandlePresenter != null) {
            caseHandlePresenter.disposeRetrofitRequest();
        }
        viewBinding.audioPlayerView.release();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }
}
