package com.casic.dcms.ui;

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

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.CommonSentenceBean;
import com.casic.dcms.mvp.presenter.CaseCommonSentencePresenterImpl;
import com.casic.dcms.mvp.presenter.CaseDetailPresenterImpl;
import com.casic.dcms.mvp.presenter.CaseUpdateSupervisePresenterImpl;
import com.casic.dcms.mvp.view.ICaseCommonSentenceView;
import com.casic.dcms.mvp.view.ICaseDetailView;
import com.casic.dcms.mvp.view.ICaseUpdateSuperviseView;
import com.casic.dcms.ui.fragment.overtime.CaseHandledFragment;
import com.casic.dcms.ui.fragment.overtime.CaseTodoFragment;
import com.casic.dcms.utils.Constant;
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.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

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 CaseTodoDetailActivity extends BaseCaseActivity implements View.OnClickListener,
        ICaseDetailView, ICaseCommonSentenceView, ICaseUpdateSuperviseView {

    private Context context = CaseTodoDetailActivity.this;
    @BindView(R.id.caseNumberView)
    TextView caseNumberView;
    @BindView(R.id.caseOverTimeView)
    TextView caseOverTimeView;
    @BindView(R.id.caseHandleStatusView)
    TextView caseHandleStatusView;
    @BindView(R.id.casePlaceView)
    TextView casePlaceView;
    @BindView(R.id.caseDescriptionView)
    TextView caseDescriptionView;
    @BindView(R.id.casePicRecyclerView)
    RecyclerView casePicRecyclerView;
    @BindView(R.id.voicePlayView)
    VoicePlayView voicePlayView;
    @BindView(R.id.caseAudioButton)
    QMUIRoundButton caseAudioButton;
    @BindView(R.id.videoPlayerView)
    JzvdStd videoPlayerView;
    @BindView(R.id.caseHandleResultView)
    TextView caseHandleResultView;
    @BindView(R.id.caseCommonSentenceView)
    TextView caseCommonSentenceView;
    @BindView(R.id.submitButton)
    QMUIRoundButton submitButton;

    private String title;
    private String id;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();

    private CaseDetailPresenterImpl caseDetailPresenter;
    private CaseCommonSentencePresenterImpl commonSentencePresenter;
    private CaseUpdateSupervisePresenterImpl updateSupervisePresenter;
    private MediaPlayer mediaPlayer;
    private QMUITipDialog submitDialog;

    @Override
    public int initLayoutView() {
        return R.layout.activity_case_todo_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);

        commonSentencePresenter = new CaseCommonSentencePresenterImpl(this);
        updateSupervisePresenter = new CaseUpdateSupervisePresenterImpl(this);

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

    @Override
    public void initEvent() {

    }

    @OnClick({R.id.locationMapView, R.id.caseHandleLayout, R.id.caseCommonSentenceLayout, 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.caseHandleLayout:
                OtherUtils.showCaseProcess(this, data.getProcessId());
                break;
            case R.id.caseCommonSentenceLayout:
                commonSentencePresenter.onReadyRetrofitRequest();
                break;
            case R.id.submitButton:
                submitCase();//案卷提交
                break;
            default:
                break;
        }
    }

    private void submitCase() {
        String remarks = caseHandleResultView.getText().toString();
        if (TextUtils.isEmpty(remarks)) {
            ToastHelper.showToast("督办意见不能为空", ToastHelper.WARING);
            return;
        }
        updateSupervisePresenter.onReadyRetrofitRequest(id, remarks);
    }

    @Override
    public void obtainCaseDetailData(CaseDetailBean resultBean) {
        if (resultBean.isSuccess()) {
            this.data = resultBean.getData().get(0);
            caseNumberView.setText(data.getCaseid());
            caseOverTimeView.setText(data.getNodeLimittime());
            caseHandleStatusView.setText(data.getCaseStateName().equals("") ? "案卷状态未知" : data.getCaseStateName());
            casePlaceView.setText(StringHelper.filterString(data.getFieldintro()));
            caseDescriptionView.setText(StringHelper.filterString(data.getDescription()));

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

    @Override
    public void obtainCommonSentenceData(CommonSentenceBean resultBean) {
        if (resultBean.isSuccess()) {
            List<CommonSentenceBean.DataBean> dataBeans = resultBean.getData();
            QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
            sheetBuilder.setTitle("常用语句");
            for (CommonSentenceBean.DataBean dataBean : dataBeans) {
                sheetBuilder.addItem(dataBean.getName());
            }
            sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                @Override
                public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                    dialog.dismiss();

                    CommonSentenceBean.DataBean dataBean = dataBeans.get(position);
                    caseCommonSentenceView.setText(dataBean.getName());
                    caseHandleResultView.setText(dataBean.getName());
                }
            }).build().show();
        } else {
            ToastHelper.showToast("该案卷无下级流转节点", ToastHelper.ERROR);
        }
    }

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

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

    @Override
    public void obtainUpdateSuperviseData(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            ToastHelper.showToast("案卷督办提交成功", ToastHelper.SUCCESS);
            //案卷办完以后通知待办和已办刷新数据
            if (title.equals("超时督办")) {
                CaseTodoFragment.sendEmptyMessage(Constant.CASE_OVERTIME_OK);
                CaseHandledFragment.sendEmptyMessage(Constant.CASE_OVERTIME_OK);
            } else {
                CaseTodoFragment.sendEmptyMessage(Constant.CASE_URGENT_OK);
                CaseHandledFragment.sendEmptyMessage(Constant.CASE_URGENT_OK);
            }
            finish();
        } else {
            ToastHelper.showToast("案卷督办提交失败，请检查", ToastHelper.ERROR);
        }
    }

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

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