package com.casic.dcms.view.upload;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
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.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityCommonCaseBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.CaseLargeTypeBean;
import com.casic.dcms.model.CaseSmallTypeBean;
import com.casic.dcms.utils.AudioPopupWindow;
import com.casic.dcms.utils.FileUtils;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.PictureSelectorHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ViewGroupKit;
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.CaseViewModel;
import com.casic.dcms.vm.CommonDataViewModel;
import com.casic.dcms.vm.UploadViewModel;
import com.luck.picture.lib.entity.LocalMedia;
import com.pengxh.androidx.lite.adapter.EditableImageAdapter;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.kit.ContextKit;
import com.pengxh.androidx.lite.kit.IntKit;
import com.pengxh.androidx.lite.kit.LongKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.widget.audio.AudioRecodeHelper;
import com.pengxh.androidx.lite.widget.dialog.AlertControlDialog;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.zolad.videoslimmer.VideoSlimmer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;


public class CommonCaseActivity extends AndroidxBaseActivity<ActivityCommonCaseBinding> {

    private static final String TAG = "CommonCaseActivity";
    private final Context context = CommonCaseActivity.this;
    private final List<String> imageList = new ArrayList<>();//服务器返回的拍照数据集
    private final ArrayList<String> realPaths = new ArrayList<>();//真实图片路径
    private final Queue<LocalMedia> uploadQueue = new LinkedList<>(); // 用于存储待上传的图片
    private boolean isUploading = false; // 标记是否正在上传图片
    private CaseViewModel caseViewModel;
    private CommonDataViewModel commonDataViewModel;
    private UploadViewModel uploadViewModel;
    private List<CaseLargeTypeBean.DataBean> largeTypeBeans = new ArrayList<>();
    private List<CaseSmallTypeBean.DataBean> smallTypeBeans = new ArrayList<>();
    private ProgressDialog progressDialog;
    private EditableImageAdapter imageAdapter;
    private AudioRecodeHelper audioRecodeHelper;
    private String eorc = "";
    private String typeCode = "";
    private String typeDetailCode = "";//默认值，防止用户不选择直接跳过
    private String gridId;
    private String audioUrl, videoUrl;
    private boolean isFirstEnter = true;
    private OrientationUtils orientationUtils;
    private boolean isPlay;
    private boolean isPause;

    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");

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

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);

        binding.titleBarLayout.titleView.setText("案卷上报");
        binding.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) {
                    LoadingDialog.show(CommonCaseActivity.this, "案卷提交中，请稍后...");
                } else if (loadState == LoadState.Success) {
                    LoadingDialog.dismiss();
                    StringKit.show(context, "案卷提交成功");
                    finish();
                } else {
                    StringKit.show(context, "提交失败，请重试");
                    LoadingDialog.dismiss();
                }
            }
        });

        uploadViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    StringKit.show(CommonCaseActivity.this, "上传中，请稍后...");
                }
            }
        });
    }

    @Override
    public void initOnCreate(@Nullable Bundle savedInstanceState) {
        orientationUtils = new OrientationUtils(this, binding.videoPlayerView);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);

        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);

        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();
                }
            }
        });
        commonDataViewModel.smallTypeModel.observe(this, new Observer<CaseSmallTypeBean>() {
            @Override
            public void onChanged(CaseSmallTypeBean typeBean) {
                if (typeBean.getCode() == 200) {
                    //设置小类数据
                    smallTypeBeans = typeBean.getData();
                }
            }
        });

        uploadViewModel = new ViewModelProvider(this).get(UploadViewModel.class);
        uploadViewModel.imageModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                isUploading = false;
                if (resultBean.getCode() == 200) {
                    String url = resultBean.getData();
                    imageList.add(url);
                    int oldSize = realPaths.size();
                    realPaths.add(StringHelper.appendCompleteURL(url));
                    imageAdapter.notifyItemRangeChanged(oldSize, 1);
                    startUploadNextImage(); // 上传下一张图片
                } else {
                    StringKit.show(context, "图片上传失败，请重试");
                }
            }
        });
        uploadViewModel.audioModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    audioUrl = resultBean.getData();
                    /**
                     * http://111.198.10.15:11409/static/2021-04/8fb86dae39ad4f949e934e25465d7382.m4a
                     * */
                    if (!TextUtils.isEmpty(audioUrl)) {
                        binding.audioPlayerView.setVisibility(View.VISIBLE);
                        String url = StringHelper.appendCompleteURL(audioUrl);
                        try {
                            binding.audioPlayerView.setAudioSource(new File(url));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        uploadViewModel.videoModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    //2021-04\\9d89df21173043cfb4188e68613e3e0e.mp4
                    binding.addVideoView.setVisibility(View.GONE);
                    binding.videoPlayerView.setVisibility(View.VISIBLE);
                    videoUrl = resultBean.getData();
                    String completeURL = StringHelper.appendCompleteURL(videoUrl);
                    GSYVideoOptionBuilder videoOption = new GSYVideoOptionBuilder();
                    videoOption.setIsTouchWiget(true)
                            .setRotateViewAuto(false)
                            .setLockLand(false)
                            .setAutoFullWithSize(true)
                            .setShowFullAnimation(false)
                            .setNeedLockFull(true)
                            .setUrl(videoUrl)
                            .setCacheWithPlay(false)
                            .setVideoAllCallBack(new GSYSampleCallBack() {
                                @Override
                                public void onPrepared(String url, Object... objects) {
                                    super.onPrepared(url, objects);
                                    //开始播放了才能旋转和全屏
                                    orientationUtils.setEnable(true);
                                    isPlay = true;
                                }

                                @Override
                                public void onQuitFullscreen(String url, Object... objects) {
                                    super.onQuitFullscreen(url, objects);
                                    if (orientationUtils != null) {
                                        orientationUtils.backToProtVideo();
                                    }
                                }
                            }).setLockClickListener(new LockClickListener() {
                                @Override
                                public void onClick(View view, boolean lock) {
                                    if (orientationUtils != null) {
                                        //配合下方的onConfigurationChanged
                                        orientationUtils.setEnable(!lock);
                                    }
                                }
                            }).build(binding.videoPlayerView);
                    binding.videoPlayerView.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //直接横屏
                            orientationUtils.resolveByClick();
                            binding.videoPlayerView.startWindowFullscreen(context, true, true);
                        }
                    });
                }
            }
        });

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("视频压缩中...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setProgressDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.bg_progress, null));
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);

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

        //图片九宫格
        int width = ContextKit.getScreenWidth(this) - IntKit.dp2px(this, 20);
        imageAdapter = new EditableImageAdapter(this, realPaths, width, 2, 3);
        binding.addImageRecyclerView.setAdapter(imageAdapter);

        AudioRecodeHelper audioRecorder = new AudioRecodeHelper();
        new AudioPopupWindow.Builder().setContext(this).setOnAudioPopupCallback(new AudioPopupWindow.OnAudioPopupCallback() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public void onViewCreated(PopupWindow window, ImageView imageView, TextView textView) {
                binding.recodeAudioButton.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                                binding.recodeAudioButton.animate().scaleX(0.75f).scaleY(0.75f)
                                        .setDuration(100).start();
                                window.showAtLocation(binding.rootView, Gravity.CENTER, 0, 0);

                                //开始录音
                                audioRecorder.initRecorder(context, ContextKit.createAudioFile(context));
                                audioRecorder.startRecord(new AudioRecodeHelper.OnAudioStateUpdateListener() {
                                    @Override
                                    public void onUpdate(Double db, Long time) {
                                        imageView.getDrawable().setLevel((int) (3000 + 6000 * db / 100));
                                        textView.setText(LongKit.millsToTime(time));
                                    }

                                    @Override
                                    public void onStop(File file) {
                                        try {
                                            binding.audioPlayerView.setAudioSource(file);
                                        } catch (IOException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                });
                                break;

                            case MotionEvent.ACTION_UP:
                                audioRecorder.stopRecord(); //结束录音（保存录音文件）
                                window.dismiss();
                                binding.recodeAudioButton.animate()
                                        .scaleX(1.0f).scaleY(1.0f)
                                        .setDuration(100).start();
                                break;
                        }
                        return true;
                    }
                });
            }
        }).build().create();
    }

    /**
     * 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 = LocaleConstant.DEFAULT_WIDTH / 2;
            height = LocaleConstant.DEFAULT_HEIGHT / 2;
        } else {
            width = LocaleConstant.DEFAULT_HEIGHT / 2;
            height = LocaleConstant.DEFAULT_WIDTH / 2;
        }
        if (TextUtils.isEmpty(defaultBitrate) || defaultBitrate.equals("")) {
            bitrate = LocaleConstant.BITRATE;
        } else {
            bitrate = Integer.parseInt(defaultBitrate) / 2;
        }
        VideoSlimmer.convertVideo(mediaRealPath, outputVideoFile, width, height, LocaleConstant.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) {
                    uploadViewModel.uploadVideo(context, new File(outputVideoFile));
                } else {
                    StringKit.show(CommonCaseActivity.this, "请先选择案卷类型");
                }
                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(binding.recodeAudioButton);
            isFirstEnter = false;
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initEvent() {
        /**
         * 选择案卷类型
         * */
        binding.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();
                                binding.caseClassView.setText(tag);
                                //获取案卷大类
                                commonDataViewModel.getLargeType(context, String.valueOf(position + 1));
                                //清空大小类
                                binding.caseLargeClassView.setText("");
                                binding.caseSmallClassView.setText("");
                            }
                        }).build().show();
            }
        });

        /**
         * 选择案卷大类
         * */
        binding.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();
                            binding.caseLargeClassView.setText(tag);
                            //清空小类
                            binding.caseSmallClassView.setText("");

                            //获取案卷小类
                            CaseLargeTypeBean.DataBean dataBean = largeTypeBeans.get(position);
                            eorc = dataBean.getEorc();
                            typeCode = dataBean.getTypeCode();
                            String typeId = dataBean.getId();

                            commonDataViewModel.getSmallType(context, eorc, typeId);
                        }
                    }).build().show();
                } else {
                    StringKit.show(context, "请先选择案卷类型");
                }
            }
        });

        /**
         * 选择案卷小类
         * */
        binding.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();
                            binding.caseSmallClassView.setText(tag);
                            typeDetailCode = smallTypeBeans.get(position).getTypeDetailCode();
                        }
                    }).build().show();
                } else {
                    StringKit.show(context, "请先选择案卷大类");
                }
            }
        });

        /**
         * 选择经纬度
         * */
        binding.locationMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = binding.caseClassView.getText().toString();
                if (type.equals("")) {
                    StringKit.show(context, "请先选择案卷类型");
                    return;
                }
                Intent intent = new Intent(context, ArcGISMapActivity.class);
                intent.putExtra("type", type);
                uploadCaseLauncher.launch(intent);
            }
        });

        /**
         * 案卷录音
         * */
        //TODO 未完
//        AudioPopupWindow.create(this, new AudioPopupWindow.IWindowListener() {
//            @Override
//            public void onViewCreated(PopupWindow window, ImageView imageView, TextView textView) {
//                binding.recodeAudioButton.setOnTouchListener(new View.OnTouchListener() {
//                    @Override
//                    public boolean onTouch(View v, MotionEvent event) {
//                        switch (event.getAction()) {
//                            case MotionEvent.ACTION_DOWN:
//                                binding.recodeAudioButton.animate().scaleX(0.75f).scaleY(0.75f).setDuration(100).start();
//                                window.showAtLocation(binding.caseLayout, Gravity.CENTER, 0, 0);
//                                audioRecodeHelper.startRecordAudio(ContextKit.createAudioFile(CommonCaseActivity.this).toString());
//                                break;
//                            case MotionEvent.ACTION_UP:
//                                audioRecodeHelper.stopRecordAudio();//结束录音（保存录音文件）
//                                window.dismiss();
//                                binding.recodeAudioButton.animate().scaleX(1.0f).scaleY(1.0f).setDuration(100).start();
//                                break;
//                        }
//                        return true;
//                    }
//                });
//
//                audioRecodeHelper = new AudioRecodeHelper();
//                audioRecodeHelper.setOnAudioStatusUpdateListener(new AudioRecodeHelper.OnAudioStatusUpdateListener() {
//                    @Override
//                    public void onUpdate(double db, long time) {
//                        imageView.getDrawable().setLevel((int) (3000 + 6000 * db / 100));
//                        textView.setText(LongKit.millsToTime(time));
//                    }
//
//                    @Override
//                    public void onStop(String filePath) {
//                        uploadViewModel.uploadAudio(new File(filePath));
//                    }
//                });
//            }
//        });

        /**
         * 案卷视频
         * */
        binding.addVideoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelectorHelper.takeVideo(context, new ISelectorListener() {
                    @Override
                    public void onSuccess(ArrayList<LocalMedia> result) {
                        LocalMedia media = result.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("")) {
                            //如果默认和备用路径还是为空，则不压缩上传
                            StringKit.show(context, "请先选择案卷类型");
                            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);
                    }
                });
            }
        });

        /**
         * 重拍视频
         * */
        binding.deleteView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.videoPlayerView.isShown()) {
                    new AlertControlDialog.Builder()
                            .setContext(context)
                            .setTitle("提示")
                            .setMessage("确定重新拍摄视频材料？")
                            .setNegativeButton("取消")
                            .setPositiveButton("确定")
                            .setOnDialogButtonClickListener(new AlertControlDialog.OnDialogButtonClickListener() {
                                @Override
                                public void onConfirmClick() {
                                    binding.videoPlayerView.setVisibility(View.GONE);
                                    binding.addVideoView.setVisibility(View.VISIBLE);
                                }

                                @Override
                                public void onCancelClick() {

                                }
                            }).build().show();
                }
            }
        });

        /**
         * 图片九宫格事件处理
         * */
        imageAdapter.setOnItemClickListener(new EditableImageAdapter.OnItemClickListener() {
            @Override
            public void onAddImageClick() {
                PictureSelectorHelper.selectPicture(context, 2, new ISelectorListener() {
                    @Override
                    public void onSuccess(ArrayList<LocalMedia> result) {
                        uploadQueue.addAll(result); // 将选中的图片加入队列
                        startUploadNextImage();
                    }
                });
            }

            @Override
            public void onItemClick(int position) {
                if (realPaths.get(position).isEmpty()) {
                    StringKit.show(context, "图片加载失败，无法查看大图");
                } else {
                    ContextKit.navigatePageTo(context, BigImageActivity.class, position, realPaths);
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
                imageList.remove(position);
                realPaths.remove(position);
                imageAdapter.notifyItemRemoved(position);
                imageAdapter.notifyItemRangeChanged(position, realPaths.size() - position);
            }
        });

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

    private void startUploadNextImage() {
        if (isUploading || uploadQueue.isEmpty()) {
            return;
        }

        isUploading = true;
        LocalMedia media = uploadQueue.poll();
        if (media != null) {
            uploadViewModel.uploadImage(this, new File(media.getRealPath()));
        } else {
            isUploading = false;
        }
    }

    /**
     * 案卷提交
     */
    private void submitCase() {
        String longitude = binding.longitudeView.getText().toString();
        String latitude = binding.latitudeView.getText().toString();
        if (longitude.equals("0") || latitude.equals("0") || TextUtils.isEmpty(longitude) || TextUtils.isEmpty(latitude)) {
            StringKit.show(this, "经纬度异常，请重新选择位置");
            return;
        }
        if (eorc.equals("") || typeCode.equals("")) {
            StringKit.show(this, "案卷大类还未选择");
            return;
        }
        if (typeDetailCode.equals("")) {
            StringKit.show(this, "案卷小类还未选择");
            return;
        }
        if (TextUtils.isEmpty(gridId)) {
            StringKit.show(this, "网格ID异常，请重新地图选点");
            return;
        }
        String fieldIntro = binding.caseLocationView.getText().toString().trim().replace(" ", "");
        if (TextUtils.isEmpty(fieldIntro)) {
            StringKit.show(this, "案卷地点还未填写");
            return;
        }
        String description = binding.caseDetailEditView.getText().toString().trim().replace(" ", "");
        if (TextUtils.isEmpty(description)) {
            StringKit.show(this, "案卷情况还未填写");
            return;
        }
        if (imageAdapter.getItemCount() < 1) {
            StringKit.show(this, "至少上传一张图片");
            return;
        }

        caseViewModel.submitCase(this, "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 onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        binding.videoPlayerView.getCurrentPlayer().onVideoPause();
        super.onPause();
        isPause = true;
    }

    @Override
    protected void onResume() {
        binding.videoPlayerView.getCurrentPlayer().onVideoResume(false);
        super.onResume();
        isPause = false;
    }

    @Override
    protected void onDestroy() {
        if (isPlay) {
            binding.videoPlayerView.getCurrentPlayer().release();
        }
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            binding.videoPlayerView.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }
}