package com.tofly.ghrq_route.common.ui.activity;

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 androidx.appcompat.widget.Toolbar;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.MediaManager;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.module.buildManage.BuildTool;
import com.tofly.ghrq_route.module.buildManage.controller.BuildManageCallback;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildReportBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildReportEvent;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.uploadFile.GetUploadFileCallback;
import com.tofly.ghrq_route.module.uploadFile.domain.UploadFileBean;
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.module.buildManage.domain.BuildReportEvent.BUILD_REPORT_REMOVED;

/**
 * Created by Amu on 2017/5/26.
 */

public class UiBuildReportDetail extends BaseUi {
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.report_build_name)
    TextView reportBuildName;
    @BindView(R.id.build_build_state)
    TextView reportBuildState;
    @BindView(R.id.report_build_addr)
    TextView reportBuildAddr;
    @BindView(R.id.report_build_company)
    TextView reportBuildCompany;
    @BindView(R.id.build_safe_sign)
    TextView buildSafeSign;
    @BindView(R.id.build_gas_leak)
    TextView buildGasLeak;
    @BindView(R.id.build_distance_confirm)
    TextView buildDistanceConfirm;
    @BindView(R.id.build_send_warrant)
    TextView buildSendWarrant;
    @BindView(R.id.build_occupy_pipe)
    TextView buildOccupyPipe;
    @BindView(R.id.build_report_state)
    TextView buildReportState;
    @BindView(R.id.build_report_situation)
    TextView buildReportSituation;
    @BindView(R.id.build_report_time)
    TextView buildReportTime;
    @BindView(R.id.report_addr)
    TextView reportAddr;
    @BindView(R.id.build_report_notes)
    TextView buildReportNotes;
    @BindView(R.id.build_photo_area)
    LinearLayout layoutPhotoArea;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindView(R.id.audio_record_gallery)
    LinearLayout audioRecordGallery;
    @BindView(R.id.layout_audio_record)
    LinearLayout layoutAudioRecord;
    @BindArray(R.array.build_report_yes_no)
    String[] reportMarks;
    @BindArray(R.array.build_report_state)
    String[] reportStates;
    @BindArray(R.array.build_state)
    String[] buildStates;

    private BuildTool buildTool;

    private BuildReportBean mReportBean = null;

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

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

    private ImageUtil imageUtil;

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

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

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

    private void initView() {

    }

    private void initData() {
        buildTool = BuildTool.getInstance();
        imageUtil = new ImageUtil(this);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            BuildManageBean buildManageBean = (BuildManageBean) bundle.getSerializable("build_manage");
            BuildReportBean reportBean = (BuildReportBean) bundle.getSerializable("build_report");
            if (reportBean != null && buildManageBean != null) {
                mReportBean = reportBean;

                String buildname = buildManageBean.getSiteName();
                reportBuildName.setText(buildname);
                int state = reportBean.getBuild_state();
                if (state > 0 && state + 1 < buildStates.length) {
                    reportBuildState.setText(buildStates[state + 1]);
                }
                String buildaddr = buildManageBean.getConstructionAddress();
                reportBuildAddr.setText(buildaddr);
                String buildCompany = buildManageBean.getConstructionUnit();
                reportBuildCompany.setText(buildCompany);

                int safemark = reportBean.getIs_safemark();
                buildSafeSign.setText(reportMarks[safemark]);
                int leak = reportBean.getIs_leak();
                buildGasLeak.setText(reportMarks[leak]);
                int distance = reportBean.getIs_safedistance();
                buildDistanceConfirm.setText(reportMarks[distance]);
                int warrant = reportBean.getIs_notification();
                buildSendWarrant.setText(reportMarks[warrant]);
                int pipeoccupy = reportBean.getIs_pipeline();
                buildOccupyPipe.setText(reportMarks[pipeoccupy]);
                /*int state = reportBean.getReport_state();
                buildReportState.setText(reportStates[state]);*/

                String situation = reportBean.getReport_situation();
                buildReportSituation.setText(situation);

                String reporttime = reportBean.getReport_time();
                buildReportTime.setText(reporttime);

                String addr = reportBean.getAddress();
                reportAddr.setText(addr);

                String reportNotes = reportBean.getNotes();
                if (reportNotes == null || reportNotes.isEmpty()) {
                    reportNotes = getString(R.string.reported_detail_no_content);
                }
                buildReportNotes.setText(reportNotes);

                loadBuildReportPhoto();
            }
        }
    }

    private void initListener() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_message_remove, menu);
        menu.findItem(R.id.action_remove).setVisible(false);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_remove: {
                showRemoveAlert();
            }
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void loadBuildReportPhoto(){
        layoutPhotoArea.setVisibility(View.GONE);
        layoutAudioRecord.setVisibility(View.GONE);
        if (mReportBean != null){
            String strUploading = "正在加载图片...";
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            String reportId = mReportBean.getId();
            buildTool.getUploadedBuildReportFiles(this, reportId, new GetUploadFileCallback() {
                @Override
                public void onGetPhotoAudio(boolean isSuccess, List<UploadFileBean> photos, List<UploadFileBean> audios) {
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess){
                        if (photos != null && photos.size() > 0){
                            layoutPhotoArea.setVisibility(View.VISIBLE);
                            for (UploadFileBean photo : photos){
                                String path = NetRequestURL.getHttpHead() + photo.getFilename();
                                View view = imageUtil.getViewFromUrl(path);
                                photoGallery.addView(view);
                            }
                        }
                        if (audios != null && audios.size() > 0){
                            layoutAudioRecord.setVisibility(View.VISIBLE);
                            getAudiosFromServer(audios);
                        }
                    }
                }
            });
        }
    }

    private void getAudiosFromServer(List<UploadFileBean> audios){
        if (audios != null && audios.size() > 0){
            mAudiosUpload = new ArrayList<>();
            layoutAudioRecord.setVisibility(View.VISIBLE);
            audioRecordGallery.removeAllViews();
            for (UploadFileBean fileBean: audios) {
                final String url = fileBean.getFilename();
                int audioLength;
                if (fileBean.getAudiolength() != null){
                    try{
                        audioLength = Integer.parseInt(fileBean.getAudiolength());
                    }catch (NumberFormatException e){
                        audioLength = 1;
                    }
                }else {
                    audioLength = 1;
                }
                String fileNote = fileBean.getFilenote();
                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 {
            buildTool.getUploadAudioFromServer(this, mReportBean.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 void showRemoveAlert() {
        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) {
                removeBuildReport();
            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void removeBuildReport() {
        if (mReportBean != null) {
            String strUploading = getString(R.string.report_remove_deleting);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            buildTool.deleteBuildReport(this, mReportBean, new BuildManageCallback(){
                @Override
                public void onRemoveBuildReport(boolean isSuccess, int errorCode, String errMsg) {
                    super.onRemoveBuildReport(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        EventBus.getDefault().post(new BuildReportEvent(BUILD_REPORT_REMOVED, mReportBean));
                        showRemoveFinishedDialog();
                    }
                }
            });
        }
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
