package com.tofly.ghrq_route.module.trouble.ui;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.MediaManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.module.plan.domain.OfflinePathBean;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePlanRecordBean;
import com.tofly.ghrq_route.module.uploadFile.domain.UploadFileBean;
import com.tofly.ghrq_route.common.ui.activity.UiReportedClear;
import com.tofly.ghrq_route.common.util.EventBusUtil;
import com.tofly.ghrq_route.common.util.image.ImageUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;

import static com.tofly.ghrq_route.common.ui.activity.UiReportedClear.REPORT_CLEAR_UPLOADED;
import static com.tofly.ghrq_route.common.ui.activity.UiReportedClear.REPORT_ROUTE_UPLOADED;

/**
 * Created by Amu on 2017/3/23.
 */

public class UiTroubleRecordDetail extends BaseUi {
    @BindView(R.id.text_report_user)
    TextView textReportUser;
    @BindView(R.id.text_report_time)
    TextView textReportTime;
    @BindView(R.id.layout_check_area)
    LinearLayout layoutCheckArea;
    @BindView(R.id.text_check_state)
    TextView textCheckState;
    @BindView(R.id.layout_audio_area)
    LinearLayout layoutAudioArea;
    @BindView(R.id.audio_record_gallery)
    LinearLayout audioRecordGallery;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindView(R.id.text_report_notes)
    TextView textReportNotes;
    @BindArray(R.array.trouble_clear_check_state)
    String[] clearCheckStates;

    private List<Record> mAudiosUpload = new ArrayList<>();

    private List<TroublePictureBean> mTroublePictures;

    private List<TroubleAudioBean> mTroubleAudios;

    private List<AnimationDrawable> mAnimationDrawables = new ArrayList<>();

    private TroubleBean mTrouble;

    private OfflinePathBean mPlanPoint;

    private TroublePlanRecordBean mTroubleRecord;

    private TroubleTool troubleTool;

    private boolean mbIsLocal = false;

    private boolean mbIsClear = false;

    private boolean mbIsEditable = false;

    private MenuItem menuUpload;

    private MenuItem menuRemove;

    private ImageUtil imageUtil;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_trouble_record_detaill);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_remove_upload, menu);
        menuUpload = menu.findItem(R.id.action_commit);
        menuRemove = menu.findItem(R.id.action_remove);
        if (!mbIsLocal){
            menuRemove.setVisible(false);
        }else {
            menuRemove.setVisible(true);
        }
        menuUpload.setVisible(mbIsEditable && mbIsLocal);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_commit:{
                if (mbIsLocal){
                    if (isValid()){
                        showUploadAlertDialog();
                    }
                }
            }
            break;
            case R.id.action_remove:{
                showRemoveAlertDialog();
            }
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {

    }

    private void initData() {
        troubleTool = TroubleTool.getInstance();
        imageUtil = new ImageUtil(this);

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mTrouble = (TroubleBean) bundle.getSerializable(TroubleBean.TROUBLE_BEAN_KEY);
            mPlanPoint = (OfflinePathBean) bundle.getSerializable(OfflinePathBean.PLAN_POINT_BEAN_KEY);
            mTroubleRecord = (TroublePlanRecordBean) bundle.getSerializable(TroublePlanRecordBean.TROUBLE_RECORD_BEAN_KEY);
            mbIsClear = bundle.getBoolean(TroublePlanRecordBean.TROUBLE_RECORD_CLOSE_KEY, false);
            mbIsEditable = bundle.getBoolean(TroublePlanRecordBean.TROUBLE_RECORD_EDITABLE_KEY, false);
            mbIsLocal = (mTroubleRecord.getStatus() == TroubleBean.SAVED_STATE ||
                    mTroubleRecord.getStatus() == TroubleBean.CLEAR_SAVED_STATE);
        }

        if (mTroubleRecord != null){
            String reporter = mTroubleRecord.getCreate_username();
            textReportUser.setText(reporter);
            String reportTime = mTroubleRecord.getCreate_time();
            textReportTime.setText(reportTime);
            String reportNotes = mTroubleRecord.getNotes();
            textReportNotes.setText(reportNotes);

            if (mbIsLocal){
                layoutCheckArea.setVisibility(View.GONE);
                String localId = mTroubleRecord.getId();
                loadSavedTroublePictures(localId);
                loadSavedTroubleAudios(localId);
            }else {
                /*if (mbIsClear){
                    int check_state = mTroubleRecord.getCheck_state();
                    if (check_state >= 0 && check_state < clearCheckStates.length){
                        layoutCheckArea.setVisibility(View.VISIBLE);
                        textCheckStatetextCheckState.setText(clearCheckStates[check_state]);
                    }
                }else {
                    layoutCheckArea.setVisibility(View.GONE);
                }*/
                loadUploadPhoto();
                getAudiosFromServer();
            }
        }
    }

    private void initListener() {
        setOnNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void loadSavedTroublePictures(String troubleId){
        List<TroublePictureBean> pictures = troubleTool.getSavedTroublePictures(troubleId);
        mTroublePictures = new ArrayList<>();
        for (TroublePictureBean picture : pictures){
            if (picture != null){
                mTroublePictures.add(picture);
                String path = picture.getFilepath();
                View view = imageUtil.getViewFromPath(path);
                if (view != null){
                    photoGallery.addView(view);
                }
            }
        }
    }

    private void loadSavedTroubleAudios(String troubleId){
        List<TroubleAudioBean> audios = troubleTool.getSavedTroubleAudios(troubleId);
        if (audios.size() > 0){
            mTroubleAudios = audios;
            mAudiosUpload = new ArrayList<>();
            layoutAudioArea.setVisibility(View.VISIBLE);
            for (TroubleAudioBean audio : audios){
                if (audio != null){
                    String path = audio.getPath();
                    int second = audio.getSecond() <= 0 ? 1 :  audio.getSecond();
                    String fileNote = audio.getFilenote();
                    View view = getRecordViewFromAudio(path, second, fileNote, true);
                    if (view != null)
                        audioRecordGallery.addView(view);
                }
            }
        }else {
            layoutAudioArea.setVisibility(View.GONE);
        }
    }

    private void loadUploadPhoto() {
        if (mTroubleRecord != null) {
            List<UploadFileBean> photos = mTroubleRecord.getPic();
            if (photos != null && photos.size() > 0) {
                photoGallery.removeAllViews();
                for (UploadFileBean fileBean : photos) {
                    String filePath = fileBean.getFilename();
                    String path = NetRequestURL.getHttpHead() + filePath;
                    View view = imageUtil.getViewFromUrl(path);
                    photoGallery.addView(view);
                }
            }
        }
    }

    private void getAudiosFromServer(){
        List<UploadFileBean> audios = mTroubleRecord.getAudio();
        if (audios != null && audios.size() > 0){
            mAudiosUpload = new ArrayList<>();
            layoutAudioArea.setVisibility(View.VISIBLE);
            for (UploadFileBean fileBean: audios) {
                String url = fileBean.getFilename();
                String fileNote = fileBean.getFilenote();
                int audioLength;
                if (fileBean.getAudiolength() != null){
                    try{
                        audioLength = Integer.parseInt(fileBean.getAudiolength());
                    }catch (NumberFormatException e){
                        audioLength = 1;
                    }
                }else {
                    audioLength = 1;
                }
                View view = getRecordViewFromAudio(url, audioLength, fileNote, false);
                if (view != null)
                    audioRecordGallery.addView(view);
            }
        }
    }

    private void resetData() {
        if (mAudiosUpload != null){
            for (Record record : mAudiosUpload) {
                record.setPlaying(false);//保证在第二次点击该语音栏时当作没有“不是在播放状态”。
            }
        }
    }

    private void resetAnim(AnimationDrawable animationDrawable) {
        if (!mAnimationDrawables.contains(animationDrawable)) {
            mAnimationDrawables.add(animationDrawable);
        }
        for (AnimationDrawable ad : mAnimationDrawables) {
            ad.selectDrawable(0);
            ad.stop();
        }
    }

    @SuppressLint("InflateParams")
    private View getRecordViewFromAudio(final String url, int audioLength, final String fileNote, boolean isLocal){
        LayoutInflater inflater = LayoutInflater.from(this);
        final View rootView = inflater.inflate(R.layout.item_audio_record, null);

        final LinearLayout layoutAudio = rootView.findViewById(R.id.layout_audio_area);
        TextView textTime = rootView.findViewById(R.id.textview_audio_time);
        ImageView imageRead = rootView.findViewById(R.id.image_audio_read);
        final ProgressBar progressBar = rootView.findViewById(R.id.progress_loading);
        final ImageView imageFailed = rootView.findViewById(R.id.image_failed);

        progressBar.setVisibility(View.VISIBLE);
        layoutAudio.setVisibility(View.GONE);
        imageFailed.setVisibility(View.GONE);

        if (isLocal){
            Record record = new Record(url, audioLength);
            mAudiosUpload.add(record);
            rootView.setTag(record);
            progressBar.setVisibility(View.GONE);
            layoutAudio.setVisibility(View.VISIBLE);
        }else {
            troubleTool.getTroubleAudioFromServer(this, mTrouble.getId(), url, audioLength, fileNote, new TroubleTool.GetAudioCallback() {
                @Override
                public void onGetAudioRecord(boolean isSuccess, Record record) {
                    progressBar.setVisibility(View.GONE);
                    if (isSuccess){
                        mAudiosUpload.add(record);
                        rootView.setTag(record);
                        layoutAudio.setVisibility(View.VISIBLE);
                    }else {
                        imageFailed.setVisibility(View.VISIBLE);
                    }
                }
            });
        }

        //设置显示时长
        textTime.setText(audioLength <= 0 ? 1 + "''" : audioLength + "''");
        imageRead.setVisibility(View.VISIBLE);
        rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Record record1 = (Record) view.getTag();
                if (record1 != null){
                    record1.setPlayed(true);
                    ImageView imageRead1 = view.findViewById(R.id.image_audio_read);
                    imageRead1.setVisibility(View.GONE);
                    LinearLayout layoutSignal = view.findViewById(R.id.layout_audio_signal);
                    final AnimationDrawable animationDrawable = (AnimationDrawable) layoutSignal.getBackground();
                    //重置动画
                    resetAnim(animationDrawable);
                    //重置数据状态
                    resetData();

                    //处理点击正在播放的语音时，可以停止；再次点击时重新播放。
                    if (record1.isPlaying()) {
                        record1.setPlaying(false);
                        MediaManager.release();//重置
                    } else {
                        record1.setPlaying(true);
                        //获取语音信号栏，开始播放动画
                        animationDrawable.start();
                        //播放前重置。
                        MediaManager.release();
                        //开始实质播放
                        MediaManager.playSound(record1.getPath(),
                                new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        animationDrawable.selectDrawable(0);//显示动画第一帧
                                        animationDrawable.stop();
                                    }
                                });
                    }
                }
            }
        });

        return rootView;
    }

    private boolean isValid() {
        boolean isPictureValid = false;
        boolean isEditValid = false;

        String notes = textReportNotes.getText().toString();
        if (!notes.isEmpty()){
            isEditValid = true;
        }

        if (mTroublePictures != null && mTroublePictures.size() > 0) {
            isPictureValid = true;
        }

        if (!isEditValid){
            toast("备注为空");
            return false;
        }

        if (!isPictureValid) {
            toast("图片不能为空");
            return false;
        }

        return true;
    }

    private void showRemoveAlertDialog() {
        String title = "删除数据";
        String content = "是否删除数据?";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mbIsLocal){
                    removeLocalRouteRecord();
                    onRemoveFinished();
                }else {
                    removeUploadRouteRecord();
                }
            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void removeLocalRouteRecord(){

    }

    private void onRemoveFinished(){
        menuUpload.setEnabled(false);
        menuRemove.setEnabled(false);
        String msg = mbIsClear ? REPORT_CLEAR_UPLOADED : REPORT_ROUTE_UPLOADED;
        EventBusUtil.postEvent(new UiReportedClear.ReportClearMessageEvent(msg));
        showRemoveFinishedDialog();
    }

    private void showRemoveFinishedDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.repair_update_delete_data_ok);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UiTroubleRecordDetail.this.finish();
            }
        });
        builder.show();
    }

    private void removeUploadRouteRecord(){

    }

    private void showUploadAlertDialog() {
        String title = "上传数据";
        String content = "是否上传数据?";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mbIsClear)
                    uploadClearRecord();
                else {
                    uploadRouteRecord();
                }
            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void uploadRouteRecord(){

    }

    private void uploadClearRecord(){

    }

    private void onUploadFinished(){
        menuUpload.setEnabled(false);
        menuRemove.setEnabled(false);
        String msg = mbIsClear ? REPORT_CLEAR_UPLOADED : REPORT_ROUTE_UPLOADED;
        EventBus.getDefault().post(new UiReportedClear.ReportClearMessageEvent(msg));
        showUploadFinishedDialog();
    }

    private void showUploadFinishedDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.reported_clear_upload_ok);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UiTroubleRecordDetail.this.finish();
            }
        });
        builder.show();
    }

    public static class ReportClearMessageEvent {
        public String message;
        public ReportClearMessageEvent(String message) {
            this.message = message;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    protected void onStop() {
        BaseApp.cancelMultiRequest(getClass().getName());
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApp.cancelAllRequest(getClass().getName());
        //重置数据状态
        if (mAudiosUpload != null) {
            for (Record record : mAudiosUpload) {
                record.setPlaying(false);
            }
        }
        MediaManager.release();//重置
    }
}
