package com.casic.dcms.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

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.core.content.ContextCompat;
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.NineGridImageAdapter;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.CaseLargeClassBean;
import com.casic.dcms.bean.CaseSmallClassBean;
import com.casic.dcms.databinding.ActivityUploadCaseBinding;
import com.casic.dcms.mvp.presenter.impl.CaseLargeClassPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.CaseSmallClassPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.CaseSubmitPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.UploadAudioPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.UploadImagePresenterImpl;
import com.casic.dcms.mvp.presenter.impl.UploadVideoPresenterImpl;
import com.casic.dcms.mvp.view.ICaseLargeClassView;
import com.casic.dcms.mvp.view.ICaseSmallClassView;
import com.casic.dcms.mvp.view.ICaseSubmitView;
import com.casic.dcms.mvp.view.IUploadFileView;
import com.casic.dcms.utils.AudioRecodeHelper;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.FileUtils;
import com.casic.dcms.utils.JzExoMedia;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.TimeOrDateUtil;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.widgets.AlertControlDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.zolad.videoslimmer.VideoSlimmer;

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

import cn.jzvd.Jzvd;

public class CaseUploadActivity extends AndroidxBaseActivity<ActivityUploadCaseBinding> implements View.OnClickListener, View.OnTouchListener,
        ICaseLargeClassView, ICaseSmallClassView, ICaseSubmitView, IUploadFileView {

    private static final String TAG = "CaseUploadActivity";
    private final Context context = this;
    private CaseLargeClassPresenterImpl caseLargeClassPresenter;
    private CaseSmallClassPresenterImpl caseSmallClassPresenter;
    private CaseSubmitPresenterImpl caseSubmitPresenter;
    private List<CaseLargeClassBean.DataBean> largeClassBeans;
    private List<CaseSmallClassBean.DataBean> smallClassBeans;
    private QMUITipDialog submitDialog;
    private ProgressDialog progressDialog;
    private UploadImagePresenterImpl uploadImagePresenter;
    private final List<String> imageList = new ArrayList<>();//服务器返回的拍照数据集
    private final ArrayList<String> realPaths = new ArrayList<>();//真实图片路径
    private String eorc = "";
    private String typeCode = "";
    private String typeDetailCode = "";//默认值，防止用户不选择直接跳过
    private UploadAudioPresenterImpl uploadAudioPresenter;
    private NineGridImageAdapter imageAdapter;
    private String gridId;
    private UploadVideoPresenterImpl uploadVideoPresenter;
    private String audioUrl, videoUrl;
    private AudioRecodeHelper audioRecodeHelper;
    private PopupWindow popWindow;
    private boolean isFirstEnter = true;

    private final ActivityResultLauncher<Intent> uploadCaseLauncher = 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;
                }
                double longitude = data.getDoubleExtra("longitude", 0);
                double latitude = data.getDoubleExtra("latitude", 0);
                gridId = data.getStringExtra("gridId");
                String community = data.getStringExtra("community");

                viewBinding.longitudeView.setText(String.valueOf(longitude));
                viewBinding.latitudeView.setText(String.valueOf(latitude));
                viewBinding.communityNameView.setText(community);
            }
        }
    });

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText("案卷上报");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    public void initData() {
        largeClassBeans = new ArrayList<>();
        smallClassBeans = new ArrayList<>();
        caseLargeClassPresenter = new CaseLargeClassPresenterImpl(this);
        caseSmallClassPresenter = new CaseSmallClassPresenterImpl(this);
        caseSubmitPresenter = new CaseSubmitPresenterImpl(this);
        submitDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("处理中，请稍后")
                .create();
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("视频压缩中...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setProgressDrawable(getResources().getDrawable(R.drawable.bg_progress));
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);

        uploadImagePresenter = new UploadImagePresenterImpl(this);
        uploadAudioPresenter = new UploadAudioPresenterImpl(this);
        uploadVideoPresenter = new UploadVideoPresenterImpl(this);

        /**
         * 计算+图标大小
         *
         * CarrView水平外边距5dp
         * RelativeLayout水平内边距10dp
         * RecyclerView左边距100dp
         * */
        int realWidth = QMUIDisplayHelper.getScreenWidth(this) - QMUIDisplayHelper.dp2px(this, 130);
        int margins = QMUIDisplayHelper.dp2px(this, 3);
        int itemSize = (realWidth - 4 * margins) / 2;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(itemSize, itemSize);
        params.setMargins(margins, margins, margins, margins);
        params.gravity = Gravity.LEFT;
        viewBinding.addVideoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        viewBinding.addVideoView.setLayoutParams(params);

        //图片九宫格
        imageAdapter = new NineGridImageAdapter(this);
        viewBinding.selectedGridViewView.setLayoutManager(new GridLayoutManager(this, 2));
        viewBinding.selectedGridViewView.setAdapter(imageAdapter);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initEvent() {
        viewBinding.caseClassLayout.setOnClickListener(this);
        viewBinding.caseLargeClassLayout.setOnClickListener(this);
        viewBinding.caseSmallClassLayout.setOnClickListener(this);
        viewBinding.locationMapView.setOnClickListener(this);
        viewBinding.addVideoView.setOnClickListener(this);
        viewBinding.deleteView.setOnClickListener(this);
        viewBinding.submitButton.setOnClickListener(this);

        viewBinding.recodeAudioButton.setOnTouchListener(this);
        viewBinding.submitButton.setChangeAlphaWhenPress(true);
        //录音相关
        View view = View.inflate(this, R.layout.popu_microphone, null);
        int popWidth = (int) (QMUIDisplayHelper.getScreenWidth(this) * 0.35);
        int popHeight = (int) (QMUIDisplayHelper.getScreenWidth(this) * 0.30);
        popWindow = new PopupWindow(view, popWidth, popHeight, true);
        popWindow.setAnimationStyle(R.style.PopupAnimation);
        ImageView recodeImageView = view.findViewById(R.id.recodeImageView);
        TextView recodeTextView = view.findViewById(R.id.recodeTextView);
        audioRecodeHelper = new AudioRecodeHelper();
        audioRecodeHelper.setOnAudioStatusUpdateListener(new AudioRecodeHelper.OnAudioStatusUpdateListener() {
            @Override
            public void onUpdate(double db, long time) {
                recodeImageView.getDrawable().setLevel((int) (3000 + 6000 * db / 100));
                recodeTextView.setText(TimeOrDateUtil.millsToTime(time));
            }

            @Override
            public void onStop(String filePath) {
                uploadAudioPresenter.onReadyRetrofitRequest(new File(filePath));
            }
        });

        //图片九宫格事件处理
        imageAdapter.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(CaseUploadActivity.this);
                            }
                        })
                        .addItem("相机拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                OtherUtils.takePicture(CaseUploadActivity.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);
                imageAdapter.deleteImage(position);
            }
        });
    }

    @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.caseClassView.setText(tag);
                            viewBinding.caseClassView.setTextColor(ContextCompat.getColor(context, R.color.textColor));

                            //获取案卷大类
                            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();
                            viewBinding.caseLargeClassView.setText(tag);
                            viewBinding.caseLargeClassView.setTextColor(ContextCompat.getColor(context, R.color.textColor));

                            //获取案卷小类
                            CaseLargeClassBean.DataBean dataBean = largeClassBeans.get(position);
                            eorc = dataBean.getEorc();
                            typeCode = dataBean.getTypeCode();
                            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();
                            viewBinding.caseSmallClassView.setText(tag);
                            viewBinding.caseSmallClassView.setTextColor(ContextCompat.getColor(context, R.color.textColor));

                            typeDetailCode = smallClassBeans.get(position).getTypeDetailCode();
                        }
                    }).build().show();
                }
            }
        } else if (id == R.id.locationMapView) {
            String type = viewBinding.caseClassView.getText().toString();
            if (type.equals("")) {
                ToastHelper.showToast("请先选择案卷类型", ToastHelper.WARING);
                return;
            }
            Intent intent = new Intent(this, ArcGISMapActivity.class);
            intent.putExtra("type", type);
            uploadCaseLauncher.launch(intent);
        } else if (id == R.id.addVideoView) {
            OtherUtils.takeVideo(this);
        } else if (id == R.id.deleteView) {
            if (viewBinding.videoPlayerView.isShown()) {
                new AlertControlDialog.Builder()
                        .setContext(this)
                        .setTitle("提示")
                        .setMessage("确定重新拍摄视频材料？")
                        .setNegativeButton("取消")
                        .setPositiveButton("确定")
                        .setOnDialogButtonClickListener(new AlertControlDialog.OnDialogButtonClickListener() {
                            @Override
                            public void onConfirmClick() {
                                viewBinding.videoPlayerView.setVisibility(View.GONE);
                                viewBinding.addVideoView.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onCancelClick() {

                            }
                        }).build().show();
            }
        } else if (id == R.id.submitButton) {
            submitCase();
        }
    }

    @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;
                case PictureConfig.PREVIEW_VIDEO_CODE:
                    LocalMedia media = PictureSelector.obtainMultipleResult(data).get(0);
                    //"realPath":"/storage/emulated/0/Movies/VID_20210426_17552226.mp4"
                    //需要手动压缩视频
                    String mediaRealPath = media.getRealPath();
                    if (TextUtils.isEmpty(mediaRealPath)) {
                        //部分手机getRealPath可能为空，需要备用路径
                        mediaRealPath = media.getPath();
                    }
                    if (TextUtils.isEmpty(mediaRealPath) || mediaRealPath.equals("")) {
                        //如果默认和备用路径还是为空，则不压缩上传
                        ToastHelper.showToast("操作失败，无法获取有效的视频文件", ToastHelper.ERROR);
                        return;
                    }
                    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                    retriever.setDataSource(mediaRealPath);
                    String defaultRotation = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
                    String defaultBitrate = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE);

                    assert defaultRotation != null;
                    compressVideo(mediaRealPath, defaultRotation, defaultBitrate);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 6.0以上视频压缩
     */
    private void compressVideo(String mediaRealPath, String defaultRotation, String defaultBitrate) {
        Log.d(TAG, "defaultRotation: " + defaultRotation + ", defaultBitrate: " + defaultBitrate);
        String outputVideoFile = FileUtils.getOutputVideoFile();
        int width, height, bitrate;
        if (defaultRotation.equals("90")) {//视频为竖屏，0为横屏
            width = Constant.DEFAULT_WIDTH / 2;
            height = Constant.DEFAULT_HEIGHT / 2;
        } else {
            width = Constant.DEFAULT_HEIGHT / 2;
            height = Constant.DEFAULT_WIDTH / 2;
        }
        if (TextUtils.isEmpty(defaultBitrate) || defaultBitrate.equals("")) {
            bitrate = Constant.BITRATE;
        } else {
            bitrate = Integer.parseInt(defaultBitrate) / 2;
        }
        VideoSlimmer.convertVideo(mediaRealPath, outputVideoFile, width, height, Constant.BITRATE, new VideoSlimmer.ProgressListener() {
            @Override
            public void onStart() {
                progressDialog.show();
            }

            @Override
            public void onProgress(float percent) {
                progressDialog.setProgress((int) percent);
            }

            @Override
            public void onFinish(boolean result) {
                if (result) {
                    uploadVideoPresenter.onReadyRetrofitRequest(new File(outputVideoFile));
                } else {
                    ToastHelper.showToast("压缩失败", ToastHelper.ERROR);
                }
                progressDialog.dismiss();
            }
        });
    }

    /**
     * 首次进入页面显示引导Popup
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (isFirstEnter) {
            TextView textView = new TextView(this);
            int padding = QMUIDisplayHelper.dp2px(this, 10);
            textView.setPadding(padding, padding, padding, padding);
            textView.setGravity(Gravity.CENTER);
            textView.setText("按住即可开始录音");
            QMUIPopups.popup(this, QMUIDisplayHelper.dp2px(this, 150))
                    .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                    .view(textView)
                    .shadow(true)
                    .arrow(true)
                    .animStyle(QMUIPopup.ANIM_AUTO)
                    .dimAmount(0.6f)//60%透明度
                    .onDismiss(null)
                    .show(viewBinding.recodeAudioButton);
            isFirstEnter = false;
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                viewBinding.recodeAudioButton.animate().scaleX(0.75f).scaleY(0.75f).setDuration(100).start();
                popWindow.showAtLocation(viewBinding.caseLayout, Gravity.CENTER, 0, 0);
                audioRecodeHelper.startRecordAudio();
                break;
            case MotionEvent.ACTION_UP:
                audioRecodeHelper.stopRecordAudio();//结束录音（保存录音文件）
                popWindow.dismiss();
                viewBinding.recodeAudioButton.animate().scaleX(1.0f).scaleY(1.0f).setDuration(100).start();
                break;
        }
        return true;
    }

    @Override
    public void obtainLargeClassData(CaseLargeClassBean largeClassBean) {
        if (largeClassBean.isSuccess()) {
            //设置大类数据
            this.largeClassBeans = largeClassBean.getData();
            if (largeClassBeans.size() == 0) {
                viewBinding.caseLargeClassView.setText("无小类");
            } else {
                viewBinding.caseLargeClassView.setText(largeClassBeans.get(0).getTypeName());//默认选择第一个
            }
            viewBinding.caseLargeClassView.setTextColor(ContextCompat.getColor(this, R.color.darkGray));

            viewBinding.caseSmallClassView.setText("请选择");
            viewBinding.caseSmallClassView.setTextColor(ContextCompat.getColor(this, R.color.darkGray));
        }
    }

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

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

    @SuppressLint("SetTextI18n")
    @Override
    public void obtainUploadAudioResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            audioUrl = resultBean.getData();
            /**
             * http://111.198.10.15:11409/static/2021-04/8fb86dae39ad4f949e934e25465d7382.m4a
             * */
            if (!TextUtils.isEmpty(audioUrl)) {
                viewBinding.audioPlayerView.setVisibility(View.VISIBLE);
                viewBinding.audioPlayerView.setAudioUrl(StringHelper.appendCompleteURL(audioUrl));
            }
        }
    }

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

    @Override
    public void obtainUploadVideoResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            //2021-04\\9d89df21173043cfb4188e68613e3e0e.mp4
            viewBinding.addVideoView.setVisibility(View.GONE);
            viewBinding.videoPlayerView.setVisibility(View.VISIBLE);
            videoUrl = resultBean.getData();
            String completeURL = StringHelper.appendCompleteURL(videoUrl);
            viewBinding.videoPlayerView.setUp(completeURL, "", Jzvd.SCREEN_NORMAL, JzExoMedia.class);
            //设置第一帧为封面
            Glide.with(context)
                    .setDefaultRequestOptions(new RequestOptions().frame(4000000))
                    .load(completeURL)
                    .into(viewBinding.videoPlayerView.posterImageView);
        }
    }

    /**
     * 案卷提交
     */
    private void submitCase() {
        String longitude = viewBinding.longitudeView.getText().toString();
        String latitude = viewBinding.latitudeView.getText().toString();
        if (longitude.equals("0") || latitude.equals("0") || TextUtils.isEmpty(longitude) || TextUtils.isEmpty(latitude)) {
            ToastHelper.showToast("经纬度异常，请重新选择位置", ToastHelper.WARING);
            return;
        }
        if (eorc.equals("") || typeCode.equals("")) {
            ToastHelper.showToast("案卷大类还未选择", ToastHelper.WARING);
            return;
        }
        if (typeDetailCode.equals("")) {
            ToastHelper.showToast("案卷小类还未选择", ToastHelper.WARING);
            return;
        }
        if (TextUtils.isEmpty(gridId)) {
            ToastHelper.showToast("网格ID异常，请重新地图选点", ToastHelper.WARING);
            return;
        }
        String fieldIntro = viewBinding.caseLocationView.getText().toString().trim().replace(" ", "");
        if (TextUtils.isEmpty(fieldIntro)) {
            ToastHelper.showToast("案卷地点还未填写", ToastHelper.WARING);
            return;
        }
        String description = viewBinding.caseDetailEditView.getText().toString().trim().replace(" ", "");
        if (TextUtils.isEmpty(description)) {
            ToastHelper.showToast("案卷情况还未填写", ToastHelper.WARING);
            return;
        }
        if (imageAdapter.getItemCount() != 2) {
            ToastHelper.showToast("必须选择两张图片", ToastHelper.WARING);
            return;
        }
        caseSubmitPresenter.onReadyRetrofitRequest("0", "0", longitude, latitude,
                "2", "1", eorc, typeCode, typeDetailCode,
                gridId.substring(0, 6),
                gridId.substring(0, 9),
                gridId.substring(0, 12),
                gridId, description, fieldIntro,
                StringHelper.reformatURL(imageList), audioUrl, videoUrl, 0, 0);
    }

    @Override
    public void obtainSubmitResult(ActionResultBean resultBean) {
//        Log.d(TAG, "obtainSubmitResult: " + gson.toJson(resultBean));
        if (resultBean.isSuccess()) {
            ToastHelper.showToast("案卷提交成功", ToastHelper.SUCCESS);
            finish();
        } else {
            ToastHelper.showToast("案卷提交失败，请重试", ToastHelper.ERROR);
        }
    }

    @Override
    public void obtainDataFail() {
        ToastHelper.showToast("操作失败", ToastHelper.ERROR);
        //TODO 案卷如果在网络极差的情况下，提交超时导致失败了，需要保存到本地吗？等下次打开的是时候提醒用户补提交之前没提交成功的案卷？
    }

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

    @Override
    protected void onDestroy() {
        if (caseLargeClassPresenter != null) {
            caseLargeClassPresenter.disposeRetrofitRequest();
        }
        if (caseSmallClassPresenter != null) {
            caseSmallClassPresenter.disposeRetrofitRequest();
        }
        if (caseSubmitPresenter != null) {
            caseSubmitPresenter.disposeRetrofitRequest();
        }
        if (uploadImagePresenter != null) {
            uploadImagePresenter.disposeRetrofitRequest();
        }
        if (uploadAudioPresenter != null) {
            uploadAudioPresenter.disposeRetrofitRequest();
        }
        if (uploadVideoPresenter != null) {
            uploadVideoPresenter.disposeRetrofitRequest();
        }
        viewBinding.audioPlayerView.release();
        super.onDestroy();
    }

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

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