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.core.content.ContextCompat;
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.BaseActivity;
import com.casic.dcms.bean.CaseDetailBean;
import com.casic.dcms.mvp.presenter.CaseDetailPresenterImpl;
import com.casic.dcms.mvp.view.ICaseDetailView;
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.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

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

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

public class CaseHandledDetailActivity extends BaseActivity implements View.OnClickListener, ICaseDetailView {

    private Context context = CaseHandledDetailActivity.this;
    @BindView(R.id.detailTopLayout)
    QMUITopBarLayout detailTopLayout;
    @BindView(R.id.caseNumberView)
    TextView caseNumberView;
    @BindView(R.id.caseHandleStatusView)
    TextView caseHandleStatusView;
    @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.casePicRecyclerView)
    RecyclerView casePicRecyclerView;
    @BindView(R.id.caseHandleImageView)
    RecyclerView caseHandleImageView;
    @BindView(R.id.voicePlayView)
    VoicePlayView voicePlayView;
    @BindView(R.id.caseAudioButton)
    QMUIRoundButton caseAudioButton;
    @BindView(R.id.videoPlayerView)
    JzvdStd videoPlayerView;

    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();
    private CaseDetailPresenterImpl caseDetailPresenter;
    private MediaPlayer mediaPlayer;

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

    @Override
    protected void setupTopBarLayout() {
        detailTopLayout.setTitle("已办案卷").setTextColor(ContextCompat.getColor(this, R.color.white));
        detailTopLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.mainThemeColor));
        detailTopLayout.addLeftImageButton(R.drawable.ic_left_white, 1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

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

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

    @Override
    public void initEvent() {

    }

    @Override
    public void obtainCaseDetailData(CaseDetailBean resultBean) {
        if (resultBean.isSuccess()) {
            this.data = resultBean.getData().get(0);
            caseNumberView.setText(data.getCaseid());
            caseHandleStatusView.setText(data.getCaseStateName());
            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()));

            //最初始的案卷图片
            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 handleImages = data.getFileIdProcess();
            if (!TextUtils.isEmpty(handleImages)) {
                ArrayList<String> urls = new ArrayList<>();
                String[] split = handleImages.split(",");
                for (String s : split) {
                    if (s.contains("jpg") || s.contains("jpeg") || s.contains("png")) {
                        urls.add(StringHelper.appendCompleteURL(s));
                    }
                }
                ImageRecycleViewAdapter imageAdapter = new ImageRecycleViewAdapter(this);
                imageAdapter.setMediaList(urls);
                caseHandleImageView.setLayoutManager(new GridLayoutManager(this, 2));
                caseHandleImageView.addItemDecoration(new ItemDecorationSpace());
                caseHandleImageView.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 obtainDataFail() {
        ToastHelper.showToast("获取案卷详情失败", ToastHelper.ERROR);
    }

    @OnClick({R.id.locationMapView, R.id.handleLayout})
    @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.handleLayout:
                OtherUtils.showCaseProcess(this, data.getProcessId());
                break;
            default:
                break;
        }
    }

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