package com.casic.dcms.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

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.CaseDetailBean;
import com.casic.dcms.bean.CaseNextNodeBean;
import com.casic.dcms.mvp.presenter.CaseDetailPresenterImpl;
import com.casic.dcms.mvp.presenter.CaseHandlePresenterImpl;
import com.casic.dcms.mvp.presenter.CaseNextNodePresenterImpl;
import com.casic.dcms.mvp.presenter.UploadImagePresenterImpl;
import com.casic.dcms.mvp.view.ICaseDetailView;
import com.casic.dcms.mvp.view.ICaseHandleView;
import com.casic.dcms.mvp.view.ICaseNextNodeView;
import com.casic.dcms.mvp.view.IUploadFileView;
import com.casic.dcms.ui.fragment.handle.CaseHandledFragment;
import com.casic.dcms.ui.fragment.handle.CaseTodoFragment;
import com.casic.dcms.ui.fragment.handle.OvertimeCaseFragment;
import com.casic.dcms.ui.fragment.handle.UrgentCaseFragment;
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.ToastHelper;
import com.casic.dcms.widgets.VoicePlayView;
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.luck.picture.lib.tools.PictureFileUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

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

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

public class CaseHandleDetailActivity extends BaseCaseActivity implements View.OnClickListener,
        ICaseDetailView, ICaseNextNodeView, IUploadFileView, ICaseHandleView {

    private Context context = CaseHandleDetailActivity.this;
    @BindView(R.id.caseNumberView)
    TextView caseNumberView;
    @BindView(R.id.caseTypeView)
    TextView caseTypeView;
    @BindView(R.id.caseLargeTypeView)
    TextView caseLargeTypeView;
    @BindView(R.id.caseSmallTypeView)
    TextView caseSmallTypeView;
    @BindView(R.id.caseCommunityView)
    TextView caseCommunityView;
    @BindView(R.id.casePlaceView)
    TextView casePlaceView;
    @BindView(R.id.caseSituationView)
    TextView caseSituationView;
    @BindView(R.id.caseHandleView)
    TextView caseHandleView;
    @BindView(R.id.casePicRecyclerView)
    RecyclerView casePicRecyclerView;
    @BindView(R.id.caseAudioButton)
    QMUIRoundButton caseAudioButton;
    @BindView(R.id.videoPlayerView)
    JzvdStd videoPlayerView;
    @BindView(R.id.caseStartTimeView)
    TextView caseStartTimeView;
    @BindView(R.id.caseEndTimeView)
    TextView caseEndTimeView;
    @BindView(R.id.caseHandleResultView)
    TextView caseHandleResultView;
    @BindView(R.id.imageLayout)
    RelativeLayout imageLayout;
    @BindView(R.id.caseHandleRecyclerView)
    RecyclerView caseHandleRecyclerView;
    @BindView(R.id.voicePlayView)
    VoicePlayView voicePlayView;
    @BindView(R.id.addImageView)
    ImageView addImageView;
    @BindView(R.id.reasonLayout)
    RelativeLayout reasonLayout;
    @BindView(R.id.caseReasonView)
    EditText caseReasonView;
    @BindView(R.id.submitButton)
    QMUIRoundButton submitButton;

    private String title;
    private String id;
    private String changeState;
    private String caseReason;
    private String approvalResult;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();
    private ArrayList<String> realPaths = new ArrayList<>();//真实图片路径
    private List<String> mediaList = new ArrayList<>();//上传到服务器的数据集

    private CaseDetailPresenterImpl caseDetailPresenter;
    private CaseNextNodePresenterImpl caseNextNodePresenter;
    private UploadImagePresenterImpl uploadImagePresenter;
    private CaseHandlePresenterImpl caseHandlePresenter;
    private MediaPlayer mediaPlayer;
    private QMUITipDialog submitDialog;
    private ImageRecycleViewAdapter handleImageAdapter;//处理图片的adapter

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

    @Override
    protected String setTitleName() {
        return title;
    }

    @Override
    public void initData() {
        mediaPlayer = new MediaPlayer();

        title = getIntent().getStringExtra("title");
        id = getIntent().getStringExtra("id");
        caseDetailPresenter = new CaseDetailPresenterImpl(this);
        caseDetailPresenter.onReadyRetrofitRequest(id);

        caseNextNodePresenter = new CaseNextNodePresenterImpl(this);
        uploadImagePresenter = new UploadImagePresenterImpl(this);
        caseHandlePresenter = new CaseHandlePresenterImpl(this);

        submitDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("提交中，请稍后")
                .create();

        handleImageAdapter = new ImageRecycleViewAdapter(this);
        caseHandleRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        caseHandleRecyclerView.addItemDecoration(new ItemDecorationSpace());
        caseHandleRecyclerView.setAdapter(handleImageAdapter);
    }

    @Override
    public void initEvent() {
        submitButton.setChangeAlphaWhenPress(true);
    }

    @Override
    public void obtainCaseDetailData(CaseDetailBean resultBean) {
        if (resultBean.isSuccess()) {
            this.data = resultBean.getData().get(0);
            caseNumberView.setText(data.getCaseid());
            caseTypeView.setText(data.getEorcName());
            caseLargeTypeView.setText(data.getCasetypeName());
            caseSmallTypeView.setText(data.getCasetypeDetailName());
            caseCommunityView.setText(data.getCommunityName().equals("") ? "无更详细社区信息" : data.getCommunityName());
            casePlaceView.setText(StringHelper.filterString(data.getFieldintro()));
            caseSituationView.setText(StringHelper.filterString(data.getDescription()));
            caseHandleView.setText(data.getCaseStateName().equals("") ? "无处理意见" : data.getCaseStateName());

            String verifyImages = data.getFileIdVerify();
            if (!TextUtils.isEmpty(verifyImages)) {
                ArrayList<String> urls = new ArrayList<>();
                String[] split = verifyImages.split(",");
                for (String s : split) {
                    if (s.endsWith(".jpg") || s.contains(".jpeg") || s.contains(".png")) {
                        urls.add(StringHelper.appendCompleteURL(s));
                    }
                }
                ImageRecycleViewAdapter imageAdapter = new ImageRecycleViewAdapter(this);
                imageAdapter.setMediaList(urls);
                casePicRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
                casePicRecyclerView.addItemDecoration(new ItemDecorationSpace());
                casePicRecyclerView.setAdapter(imageAdapter);
                //九宫格点击事件
                imageAdapter.setOnItemClickListener(new ImageRecycleViewAdapter.OnItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        OtherUtils.showBigImage(context, position, urls);
                    }
                });
                imageAdapter.setDeleteView(false);
            }

            //音频
            String audioFile = data.getAudioIdVerify();
            if (!TextUtils.isEmpty(audioFile)) {
                caseAudioButton.setVisibility(View.VISIBLE);
                try {
                    mediaPlayer.setDataSource(StringHelper.appendCompleteURL(audioFile));
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mediaPlayer.prepare();
                } 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();
                    }
                });
            }

            //视频
            String videoFile = data.getVideoIdVerify();
            if (!TextUtils.isEmpty(videoFile)) {
                videoPlayerView.setVisibility(View.VISIBLE);
                String videoUrl = StringHelper.appendCompleteURL(videoFile);
                videoPlayerView.setUp(videoUrl, StringHelper.filterString(data.getDescription()));
                //设置第一帧为封面
                Glide.with(this)
                        .setDefaultRequestOptions(new RequestOptions().frame(4000000))
                        .load(videoUrl)
                        .into(videoPlayerView.posterImageView);
            }

            caseStartTimeView.setText(data.getCreateTime());
            caseEndTimeView.setText(data.getNodeLimittime());
        }
    }

    @Override
    public void obtainNextNodeData(CaseNextNodeBean resultBean) {
        if (resultBean.isSuccess()) {
            List<CaseNextNodeBean.DataBean> dataBeans = resultBean.getData();
            QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
            sheetBuilder.setTitle("处理结果");
            for (CaseNextNodeBean.DataBean dataBean : dataBeans) {
                sheetBuilder.addItem(dataBean.getNextOperation());
            }
            sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                @Override
                public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                    dialog.dismiss();

                    CaseNextNodeBean.DataBean dataBean = dataBeans.get(position);
                    String nextOperation = dataBean.getNextOperation();
                    caseHandleResultView.setText(nextOperation);
                    if (nextOperation.equals("处理完成")) {
                        imageLayout.setVisibility(View.VISIBLE);
                        reasonLayout.setVisibility(View.GONE);
                    } else {
                        imageLayout.setVisibility(View.GONE);
                        reasonLayout.setVisibility(View.VISIBLE);
                    }
                    changeState = String.valueOf(dataBean.getNextState());
                    approvalResult = dataBean.getApprovalResult();
                }
            }).build().show();
        } else {
            ToastHelper.showToast("该案卷无下级流转节点", ToastHelper.ERROR);
        }
    }

    @OnClick({R.id.locationMapView, R.id.caseHandleResultLayout, R.id.addImageView, R.id.submitButton})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.locationMapView:
                Intent intent = new Intent(this, DisplayMapActivity.class);
                intent.putExtra("caseType", data.getEorcName());
                String dataLng = data.getLng();
                if (TextUtils.isEmpty(dataLng)) {
                    ToastHelper.showToast("案卷经度异常", ToastHelper.ERROR);
                    return;
                }
                intent.putExtra("lng", Double.parseDouble(dataLng));
                String dataLat = data.getLat();
                if (TextUtils.isEmpty(dataLat)) {
                    ToastHelper.showToast("案卷纬度异常", ToastHelper.ERROR);
                    return;
                }
                intent.putExtra("lat", Double.parseDouble(dataLat));
                startActivity(intent);
                break;
            case R.id.caseHandleResultLayout:
                caseNextNodePresenter.onReadyRetrofitRequest(String.valueOf(data.getCaseState()));
                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 submitCase() {
        String handleResult = caseHandleResultView.getText().toString();
        if (handleResult.equals("请选择")) {
            ToastHelper.showToast("还未选择处理结果", ToastHelper.WARING);
            return;
        }
        if (handleResult.equals("处理完成")) {
            //选择处理完成时，处理图片必传。至少一张，最多两张
            if (handleImageAdapter.getItemCount() < 1 || handleImageAdapter.getItemCount() > 2) {
                ToastHelper.showToast("当前案卷状态必须上传至少一张图片", ToastHelper.WARING);
                return;
            }
        }
        if (handleResult.equals("申请延期") || handleResult.equals("申请调整")) {
            caseReason = caseReasonView.getText().toString();
            if (TextUtils.isEmpty(caseReason)) {
                ToastHelper.showToast("延期/调整的原因必须填写", ToastHelper.WARING);
                return;
            }
        }
        caseHandlePresenter.onReadyRetrofitRequest(data.getProcessId(), id, String.valueOf(data.getCaseState()),
                changeState, caseReason, StringHelper.reformatURL(mediaList), approvalResult);
    }

    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;
                default:
                    break;
            }
        }
    }

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

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

    @Override
    public void obtainUploadAudioResult(ActionResultBean resultBean) {

    }

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

    @Override
    public void obtainUploadVideoResult(ActionResultBean resultBean) {

    }

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

    @Override
    public void obtainCaseHandleResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            ToastHelper.showToast("案卷处理成功", ToastHelper.SUCCESS);
            switch (title) {
                case "超时案卷":
                    OvertimeCaseFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    CaseHandledFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    break;
                case "紧急案卷":
                    UrgentCaseFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    CaseHandledFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    break;
                case "待办案卷":
                    CaseTodoFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    CaseHandledFragment.sendEmptyMessage(Constant.CASE_HANDLE_OK);
                    break;
            }
            finish();
        } else {
            ToastHelper.showToast("案卷处理失败，请检查", ToastHelper.ERROR);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (caseDetailPresenter != null) {
            caseDetailPresenter.disposeRetrofitRequest();
        }
        if (caseNextNodePresenter != null) {
            caseNextNodePresenter.disposeRetrofitRequest();
        }
        if (uploadImagePresenter != null) {
            uploadImagePresenter.disposeRetrofitRequest();
        }
        if (caseHandlePresenter != null) {
            caseHandlePresenter.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();
    }
}
