package com.casic.dcms.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.casic.dcms.R;
import com.casic.dcms.adapter.ImageRecycleViewAdapter;
import com.casic.dcms.base.BaseCaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.CaseLargeClassBean;
import com.casic.dcms.bean.CaseSmallClassBean;
import com.casic.dcms.mvp.presenter.CaseLargeClassPresenterImpl;
import com.casic.dcms.mvp.presenter.CaseSmallClassPresenterImpl;
import com.casic.dcms.mvp.presenter.CaseSubmitPresenterImpl;
import com.casic.dcms.mvp.presenter.UploadAudioPresenterImpl;
import com.casic.dcms.mvp.presenter.UploadImagePresenterImpl;
import com.casic.dcms.mvp.presenter.UploadVideoPresenterImpl;
import com.casic.dcms.mvp.view.ICaseLargeClassView;
import com.casic.dcms.mvp.view.ICaseSmallClassView;
import com.casic.dcms.mvp.view.ICaseSubmitCaseView;
import com.casic.dcms.mvp.view.IUploadFileView;
import com.casic.dcms.utils.AudioRecodeHelper;
import com.casic.dcms.utils.ColorHelper;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.FileUtils;
import com.casic.dcms.utils.GlideLoadEngine;
import com.casic.dcms.utils.ItemDecorationSpace;
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.VoicePlayView;
import com.iceteck.silicompressorr.SiliCompressor;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
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.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

public class CaseUploadActivity extends BaseCaseActivity implements View.OnClickListener, View.OnTouchListener,
        ICaseLargeClassView, ICaseSmallClassView, ICaseSubmitCaseView, IUploadFileView {

    private Context context = this;
    @BindView(R.id.caseLayout)
    LinearLayout caseLayout;
    @BindView(R.id.caseClassView)
    TextView caseClassView;
    @BindView(R.id.caseLargeClassView)
    TextView caseLargeClassView;
    @BindView(R.id.caseSmallClassView)
    TextView caseSmallClassView;
    @BindView(R.id.longitudeView)
    TextView longitudeView;
    @BindView(R.id.latitudeView)
    TextView latitudeView;
    @BindView(R.id.communityNameView)
    EditText communityNameView;
    @BindView(R.id.caseLocationView)
    EditText caseLocationView;
    @BindView(R.id.caseDetailEditView)
    EditText caseDetailEditView;
    @BindView(R.id.caseAudioButton)
    QMUIRoundButton caseAudioButton;
    @BindView(R.id.voiceView)
    ImageView voiceView;
    @BindView(R.id.addVideoView)
    ImageView addVideoView;
    @BindView(R.id.videoPlayerView)
    JzvdStd videoPlayerView;
    @BindView(R.id.addImageView)
    ImageView addImageView;
    @BindView(R.id.selectedResultView)
    RecyclerView selectedResultView;
    @BindView(R.id.voicePlayView)
    VoicePlayView voicePlayView;
    @BindView(R.id.submitButton)
    QMUIRoundButton submitButton;

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

    @Override
    public int initLayoutView() {
        return R.layout.activity_case_upload;
    }

    @Override
    protected String setTitleName() {
        return "案卷上报";
    }

    @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();
        qmuiTipDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("视频压缩中，请稍后")
                .create();
        weakReferenceHandler = new WeakReferenceHandler(this);
        uploadImagePresenter = new UploadImagePresenterImpl(this);
        uploadAudioPresenter = new UploadAudioPresenterImpl(this);
        uploadVideoPresenter = new UploadVideoPresenterImpl(this);
        imageAdapter = new ImageRecycleViewAdapter(this);
        selectedResultView.setLayoutManager(new GridLayoutManager(this, 2));
        selectedResultView.addItemDecoration(new ItemDecorationSpace());
        selectedResultView.setAdapter(imageAdapter);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initEvent() {
        voiceView.setOnTouchListener(this);
        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));
            }
        });
    }

    @OnClick({R.id.caseClassLayout, R.id.caseLargeClassLayout, R.id.caseSmallClassLayout, R.id.locationMapView, R.id.addVideoView, R.id.deleteView, R.id.addImageView, R.id.submitButton})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case 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();
                                caseClassView.setText(tag);
                                caseClassView.setTextColor(ColorHelper.getResourcesColor(context, R.color.textColor));

                                //获取案卷大类
                                caseLargeClassPresenter.onReadyRetrofitRequest(String.valueOf(position + 1));
                            }
                        }).build().show();
                break;
            case 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();
                                caseLargeClassView.setText(tag);
                                caseLargeClassView.setTextColor(ColorHelper.getResourcesColor(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();
                    }
                }
                break;
            case 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();
                                caseSmallClassView.setText(tag);
                                caseSmallClassView.setTextColor(ColorHelper.getResourcesColor(context, R.color.textColor));

                                typeDetailCode = smallClassBeans.get(position).getTypeDetailCode();
                            }
                        }).build().show();
                    }
                }
                break;
            case R.id.locationMapView:
                String type = caseClassView.getText().toString();
                if (type.equals("请选择")) {
                    ToastHelper.showToast("请先选择案卷类型", ToastHelper.WARING);
                    return;
                }
                Intent intent = new Intent(this, ArcGISMapActivity.class);
                intent.putExtra("type", type);
                startActivityForResult(intent, Constant.REQUEST_MAP_CODE);
                break;
            case R.id.addVideoView:
                PictureSelector.create(this)
                        .openCamera(PictureMimeType.ofVideo())
                        .imageEngine(GlideLoadEngine.createGlideEngine())
                        .maxSelectNum(1)
                        .recordVideoSecond(15)
                        .forResult(PictureConfig.PREVIEW_VIDEO_CODE);
                break;
            case R.id.deleteView:
                if (videoPlayerView.isShown()) {
                    new QMUIDialog.MessageDialogBuilder(this)
                            .setTitle("提示")
                            .setMessage("确定重新拍摄视频材料？")
                            .setCanceledOnTouchOutside(false)
                            .addAction("取消", (dialog, index) -> dialog.dismiss())
                            .addAction("确定", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    dialog.dismiss();
                                    videoPlayerView.setVisibility(View.GONE);
                                    addVideoView.setVisibility(View.VISIBLE);
                                }
                            })
                            .create().show();
                }
                break;
            case R.id.addImageView:
                new QMUIDialog.MenuDialogBuilder(this)
                        .addItem("相册中选取", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //选图
                                selectPicture();
                            }
                        })
                        .addItem("相机拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //拍照
                                takePicture();
                            }
                        })
                        .create().show();
                break;
            case R.id.submitButton:
                submitCase();//案卷提交
                break;
            default:
                break;
        }
    }

    private void selectPicture() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideLoadEngine.createGlideEngine())
                .maxSelectNum(2)
                .isCompress(true)
                .compressQuality(80)
                .compressSavePath(FileUtils.getImageCompressPath())
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void takePicture() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .imageEngine(GlideLoadEngine.createGlideEngine())
                .maxSelectNum(1)
                .isCompress(true)
                .compressQuality(80)
                .compressSavePath(FileUtils.getImageCompressPath())
                .forResult(PictureConfig.REQUEST_CAMERA);
    }

    @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) {
                        String mediaCompressPath = media.getCompressPath();
                        uploadImagePresenter.onReadyRetrofitRequest(new File(mediaCompressPath));
                    }
                    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();

                    qmuiTipDialog.show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                /**
                                 * 视频压缩
                                 * 第一个参数:视频源文件路径
                                 * 第二个参数:压缩后视频保存的路径
                                 */
                                String comPressPath = SiliCompressor.with(context).compressVideo(mediaRealPath, FileUtils.getVideoCompressPath());
                                Message message = weakReferenceHandler.obtainMessage();
                                message.what = 20210427;
                                message.obj = comPressPath;
                                weakReferenceHandler.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;
                case Constant.REQUEST_MAP_CODE:
                    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");

                    longitudeView.setText(String.valueOf(longitude));
                    latitudeView.setText(String.valueOf(latitude));
                    communityNameView.setText(community);
                    break;
                default:
                    break;
            }
        }
    }

    private static class WeakReferenceHandler extends Handler {
        private WeakReference<CaseUploadActivity> reference;

        private WeakReferenceHandler(CaseUploadActivity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            CaseUploadActivity caseUploadActivity = reference.get();
            if (msg.what == 20210427) {
                caseUploadActivity.qmuiTipDialog.dismiss();
                String comPressPath = (String) msg.obj;
                if (!TextUtils.isEmpty(comPressPath)) {
                    caseUploadActivity.uploadVideoPresenter.onReadyRetrofitRequest(new File(comPressPath));
                } else {
                    ToastHelper.showToast("案卷视频上传失败", ToastHelper.ERROR);
                }
            }
        }
    }

    /**
     * 首次进入页面显示引导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(voiceView);
            isFirstEnter = false;
        }
    }

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

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

            caseSmallClassView.setText("请选择");
            caseSmallClassView.setTextColor(ColorHelper.getResourcesColor(this, R.color.darkGray));
        }
    }

    @Override
    public void obtainSmallClassData(CaseSmallClassBean smallClassBean) {
//        Log.d(TAG, "obtainSmallClassData: " + new Gson().toJson(smallClassBean));
        if (smallClassBean.isSuccess()) {
            //设置大类数据
            this.smallClassBeans = smallClassBean.getData();
            if (smallClassBeans.size() == 0) {
                caseSmallClassView.setText("无小类");
            } else {
                caseSmallClassView.setText(smallClassBeans.get(0).getTypeDetailName());//默认选择第一个
            }
            caseSmallClassView.setTextColor(ColorHelper.getResourcesColor(this, R.color.darkGray));
        }
    }

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

    @SuppressLint("SetTextI18n")
    @Override
    public void obtainUploadAudioResult(ActionResultBean resultBean) {
//        Log.d(TAG, "obtainUploadResult: " + gson.toJson(resultBean));
        if (resultBean.isSuccess()) {
            audioUrl = resultBean.getData();
            /**
             * http://111.198.10.15:11409/static/2021-04/8fb86dae39ad4f949e934e25465d7382.m4a
             * */
            caseAudioButton.setVisibility(View.VISIBLE);
            try {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setDataSource(StringHelper.appendCompleteURL(audioUrl));
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }
            caseAudioButton.setChangeAlphaWhenPress(true);
            caseAudioButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!mediaPlayer.isPlaying()) {
                        mediaPlayer.start();
                        voicePlayView.start();
                    }
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    voicePlayView.stop();
                }
            });
        }
    }

    @Override
    public void obtainUploadImageResult(ActionResultBean resultBean) {
//        Log.d(TAG, "obtainUploadResult: " + gson.toJson(resultBean));
        if (resultBean.isSuccess()) {
            /**
             * 系统路径static拼接图片返回路径
             * http://111.198.10.15:11409/static/2021-04/000bcf78345f4c1c86484efa3f9d68a2.jpeg
             */
            //2021-04\\000bcf78345f4c1c86484efa3f9d68a2.jpeg
            int sumItemCount = imageAdapter.getItemCount() + 1;//每上传一张图片，图片总数都是在原有的基础上+1
            if (sumItemCount <= 2) {
                String url = resultBean.getData();
                imageList.add(url);
                realPaths.add(StringHelper.appendCompleteURL(url));
                if (realPaths.size() == 2) {
                    addImageView.setVisibility(View.GONE);
                }
                imageAdapter.setMediaList(realPaths);
                //九宫格点击事件
                imageAdapter.setOnItemClickListener(new ImageRecycleViewAdapter.OnItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        OtherUtils.showBigImage(context, position, realPaths);
                    }
                });
                //删除按钮点击事件
                imageAdapter.setOnDeleteClickListener(new ImageRecycleViewAdapter.OnDeleteItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        realPaths.remove(position);
                        imageAdapter.setMediaList(realPaths);
                        if (realPaths.size() != 2) {
                            addImageView.setVisibility(View.VISIBLE);
                        }
                    }
                });
            } else {
                ToastHelper.showToast("最多只能上传2张图片", ToastHelper.WARING);
            }
        }
    }

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

    /**
     * 案卷提交
     */
    private void submitCase() {
        String longitude = longitudeView.getText().toString();
        String latitude = 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 = caseLocationView.getText().toString().trim().replace(" ", "");
        if (TextUtils.isEmpty(fieldIntro)) {
            ToastHelper.showToast("案卷地点还未填写", ToastHelper.WARING);
            return;
        }
        String description = 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);
    }

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

    @Override
    protected void onDestroy() {
        super.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();
        }
        if (mediaPlayer != null) {
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

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

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