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

import android.annotation.SuppressLint;
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.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.MediaManager;
import com.lcp.arecyclerview.widget.ARecycleView;
import com.lcp.arecyclerview.widget.ARecyclerBaseAdapter;
import com.mgq.base.utils.progressdialog.ProgressManager;
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.common.ui.adapter.PlanTroubleRecordAdapter;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.controller.TroubleCallBack;
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.trouble.ui.UiTroubleRecordDetail;
import com.tofly.ghrq_route.module.uploadFile.GetUploadFileCallback;
import com.tofly.ghrq_route.module.uploadFile.domain.UploadFileBean;
import com.tofly.ghrq_route.common.util.EventBusUtil;
import com.tofly.ghrq_route.common.util.image.ImageUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.tofly.ghrq_route.module.trouble.domain.TroubleBean.NOT_TROUBLE_STATE;
import static com.tofly.ghrq_route.module.trouble.domain.TroubleBean.SAVED_NO_COMMIT_STATE;
import static com.tofly.ghrq_route.module.trouble.domain.TroubleBean.SAVE_UPLOADING_STATE;
import static com.tofly.ghrq_route.module.trouble.domain.TroubleBean.TROUBLE_STATE;

/**
 * Created by zombiexq on 2016/6/28.
 */
public class UiReportedDetail extends BaseUi {
    @BindView(R.id.reporteddetail_user)
    TextView reporteddetailUser;
    @BindView(R.id.reporteddetail_time)
    TextView reporteddetailTime;
    @BindView(R.id.reporteddetail_handle_state)
    TextView reporteddetailHandleState;
    @BindView(R.id.reporteddetail_trouble_name)
    TextView reporteddetailTroubleName;
    @BindView(R.id.layout_device_type)
    LinearLayout layoutReportedDeviceType;
    @BindView(R.id.reporteddetail_devtype)
    TextView reporteddetailDevtype;
    @BindView(R.id.reporteddetail_troubletype)
    TextView reporteddetailTroubletype;
    @BindView(R.id.reporteddetail_trouble_addr)
    TextView reporteddetailTroubleAddr;
    @BindView(R.id.reporteddetail_detail)
    TextView reporteddetailDetail;
    @BindView(R.id.reporteddetail_trouble_kind)
    TextView reporteddetailTroubleKind;
    @BindView(R.id.layout_trouble_level)
    LinearLayout layoutTroubleLevel;
    @BindView(R.id.reporteddetail_trouble_level)
    TextView reporteddetailTroubleLevel;
    @BindView(R.id.layout_trouble_levelcheck)
    LinearLayout layoutTroubleLevelCheck;
    @BindView(R.id.reporteddetail_trouble_levelcheck)
    TextView reporteddetailTroubleLevelCheck;
    @BindView(R.id.gallery)
    LinearLayout layoutGallery;
/*    @BindView(R.id.layout_picture_clear)
    LinearLayout layoutClearArea;
    @BindView(R.id.clear_gallery)
    LinearLayout layoutClearGallery;*/
    @BindView(R.id.layout_trouble_after)
    LinearLayout layoutAfterArea;
    @BindView(R.id.layout_trouble_after_result)
    LinearLayout layoutAfterResult;
    @BindView(R.id.recycler_trouble_after)
    ARecycleView recycleTroubleClear;
    @BindView(R.id.layout_unclear)
    LinearLayout layoutUnclear;
    @BindView(R.id.layout_confirm_clear)
    LinearLayout layoutConfirmClear;
    @BindView(R.id.layout_audio_record)
    LinearLayout layoutAudioRecord;
    @BindView(R.id.audio_record_gallery)
    LinearLayout layoutAudioGallery;
    @BindView(R.id.layout_trouble_middle)
    LinearLayout layoutRouteModule;

    private MenuItem menuCommit;
    private TroubleTool troubleTool;
    private TroubleBean mTroubleUpload;
    private PlanTroubleRecordAdapter troubleClearRecordAdpter;
    private List<TroublePictureBean> mTroublePicturesUpload = new ArrayList<>();
    private List<TroubleAudioBean> mTroubleAudiosUpload;
    private List<Record> mAudioRecords;
    private List<AnimationDrawable> mAnimationDrawables = new ArrayList<>();
    private int selectedPosition = -1;
    private boolean isLocal = false;
    private ImageUtil imageUtil;

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

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

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

        EventBusUtil.register(this);
    }

    @Subscribe
    public void onMessageEvent(UiReportedClear.ReportClearMessageEvent messageEvent){
        if (messageEvent.message.equals(UiReportedClear.REPORT_CLEAR_UPLOADED)){
            finish();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_reported_detail, menu);
        menuCommit = menu.findItem(R.id.action_commit);
        menuCommit.setVisible(isLocal);
        MenuItem menuClear = menu.findItem(R.id.action_clear);
        menuClear.setVisible(false);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_commit:
                commitTrouble();
                break;
            /*case R.id.action_clear:
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("trouble_id", mTroubleUpload.getId());
                intent.setClass(this, UiReportedClear.class);
                intent.putExtras(bundle);
                startActivity(intent);*/
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        layoutRouteModule.setVisibility(View.GONE);

        List<TroublePlanRecordBean> list = new ArrayList<>();
        LinearLayoutManager linearLayoutManagerClear = new LinearLayoutManager(this);
        recycleTroubleClear.setLayoutManager(linearLayoutManagerClear);
        recycleTroubleClear.setItemAnimator(new DefaultItemAnimator());
        troubleClearRecordAdpter = new PlanTroubleRecordAdapter(this, list, true);
        recycleTroubleClear.setAdapter(troubleClearRecordAdpter);
        recycleTroubleClear.setEnabled(false);
    }

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

        String s_user, s_troubleName, s_deviceTypeId, s_deviceTypeName, s_troubleTypeName, strAddress,
                s_detail, s_uptime, s_troubleid, s_levelname, s_leveltime, s_levelchecktime, s_processName;
        int level_state, level_check_state;

        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle == null)
            return;

        selectedPosition = bundle.getInt("position", -1);
        TroubleBean trouble = (TroubleBean) bundle.getSerializable("trouble");
        mTroubleUpload = trouble;

        if (trouble == null)
            return;

        s_troubleid = trouble.getId();
        s_user = trouble.getUserid();
        s_troubleName = trouble.getTroubleName();
        s_detail = trouble.getNotes();
        strAddress = trouble.getAddress();

        if (s_detail == null || s_detail.isEmpty()) {
            s_detail = getString(R.string.reported_detail_no_content);
        }

        if (s_troubleName != null){
            reporteddetailTroubleName.setText(s_troubleName);
        }

        layoutReportedDeviceType.setVisibility(View.GONE);

        int status = trouble.getSave_state();
        if (SAVED_NO_COMMIT_STATE == status) {
            isLocal = true;
            loadSavedTroublePictures(s_troubleid);
            loadSavedTroubleAudios(s_troubleid);
        } else {
            isLocal = false;
            if (status == SAVE_UPLOADING_STATE) {
                if (menuCommit != null)
                    menuCommit.setTitle(getResources().getString(R.string.uploading));
            }
            loadUploadedTroubleFiles(s_troubleid);
        }
        s_uptime = trouble.getFindTime();

        if (status == TROUBLE_STATE){
            reporteddetailTroubleKind.setText("是");
            reporteddetailTroubleKind.setTextColor(getResources().getColor(R.color.colorPrimary));
        }else if (status == NOT_TROUBLE_STATE){
            reporteddetailTroubleKind.setText("否");
            layoutTroubleLevel.setVisibility(View.GONE);
            layoutTroubleLevelCheck.setVisibility(View.GONE);
        }else {
            reporteddetailTroubleKind.setText("未确定");
        }

        reporteddetailTroubleLevel.setText("未定级");
        reporteddetailTroubleLevelCheck.setText("未审核");

        layoutConfirmClear.setVisibility(View.GONE);
        layoutAfterArea.setVisibility(View.GONE);

        String username = trouble.getUserid();
        if (username == null || username.isEmpty())
            reporteddetailUser.setText(s_user);
        else
            reporteddetailUser.setText(username);
        reporteddetailTroubleAddr.setText(strAddress);
        reporteddetailDetail.setText(s_detail);
        reporteddetailTime.setText(s_uptime);
    }

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

    private void loadSavedTroubleAudios(String troubleId){
        List<TroubleAudioBean> audios = troubleTool.getSavedTroubleAudios(troubleId);
        mTroubleAudiosUpload = audios;
        if (audios.size() > 0){
            mAudioRecords = new ArrayList<>();
            layoutAudioRecord.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)
                        layoutAudioGallery.addView(view);
                }
            }
        }else {
            layoutAudioRecord.setVisibility(View.GONE);
        }
    }

    private void resetData() {
        if (mAudioRecords != null){
            for (Record record : mAudioRecords) {
                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);
            mAudioRecords.add(record);
            rootView.setTag(record);
            progressBar.setVisibility(View.GONE);
            layoutAudio.setVisibility(View.VISIBLE);
        }else {
            troubleTool.getTroubleAudioFromServer(this, mTroubleUpload.getId(), url, audioLength, fileNote, new TroubleTool.GetAudioCallback() {
                @Override
                public void onGetAudioRecord(boolean isSuccess, Record record) {
                    progressBar.setVisibility(View.GONE);
                    if (isSuccess){
                        mAudioRecords.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 loadUploadedTroubleFiles(String troubleId){
        String strUploading = "正在加载图片...";
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        troubleTool.getUploadedTroubleFiles(this, troubleId, new GetUploadFileCallback() {
            @Override
            public void onGetPhotoAudio(boolean isSuccess, List<UploadFileBean> photos, List<UploadFileBean> audios) {
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess){
                    getFilesFromServer(photos, audios);
                }
            }
        });
    }

    private void getFilesFromServer(List<UploadFileBean> photos, List<UploadFileBean> audios){
        if (photos != null && photos.size() > 0){
            View view = null;
            for (UploadFileBean photo : photos){
                String file_name = photo.getFilename();
                String file_path = photo.getFilepath();
                if (file_name == null || file_name.isEmpty()){
                    if (file_path != null && !file_path.isEmpty()){
                        view = imageUtil.getViewFromPath(file_path);
                    }
                }else {
                    String url = NetRequestURL.getHttpHead() + photo.getFilename();
                    view = imageUtil.getViewFromUrl(url);
                }
                if (view != null)
                    layoutGallery.addView(view);
            }
        }

        if (audios != null && audios.size() > 0){
            mAudioRecords = new ArrayList<>();
            layoutAudioRecord.setVisibility(View.VISIBLE);
            for (UploadFileBean fileBean : audios) {
                final String url = fileBean.getFilename();
                String fileNote = fileBean.getFilenote();
                final int audioLength;
                if (fileBean.getAudiolength() != null){
                    audioLength = Integer.parseInt(fileBean.getAudiolength());
                }else {
                    audioLength = 1;
                }
                View view = getRecordViewFromAudio(url, audioLength, fileNote,false);
                if (view != null)
                    layoutAudioGallery.addView(view);
            }
        }
    }

    private void initListener() {
        troubleClearRecordAdpter.setOnItemClickListener(new ARecyclerBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                TroublePlanRecordBean recordBean = troubleClearRecordAdpter.getItem(position);
                gotoUiRecordDetail(recordBean);
            }
        });
    }

    private void gotoUiRecordDetail(TroublePlanRecordBean recordBean) {
        if (mTroubleUpload != null && recordBean != null){
            Bundle bundle = new Bundle();
            bundle.putSerializable("trouble", mTroubleUpload);
            bundle.putSerializable("trouble_record", recordBean);
            bundle.putBoolean("is_clear", true);
            Intent intent = new Intent();
            intent.setClass(this, UiTroubleRecordDetail.class);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    private void commitTrouble() {
        /*if (isLocal){
            if (troubleTool.isUploadingTroubleInfo(mTroubleUpload.getId())){
                toast("后台数据正在上传中，不可重复提交！");
                return;
            }
        }*/
        uploadDanger();
    }

    private void uploadDanger() {
        String title = "上传隐患";
        String content = "是否上传隐患?";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> uploadTrouble());
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void uploadTrouble() {
        if (mTroubleUpload != null) {
            String strUploading = getString(R.string.dangerreport_next_uploading_info);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            troubleTool.uploadNewTroubleNoSave(this, mTroubleUpload,
                    mTroublePicturesUpload, mTroubleAudiosUpload, null, new TroubleCallBack() {
                        @Override
                        public void onAddTrouble(boolean isSuccess, int errorCode, String errMsg, String troubleId) {
                            super.onAddTrouble(isSuccess, errorCode, errMsg, troubleId);
                            ProgressManager.getInstance().cancelProgress();
                            if (isSuccess && troubleId != null){
                                onUploadFinished();
                            }
                        }
                    }
            );
        }
    }


    private void onUploadFinished(){
        menuCommit.setEnabled(false);
        EventBus.getDefault().post(new ReportDetailMessageEvent(REPORT_DETAIL_UPLOADED, selectedPosition));
        showUploadFinishedDialog();
    }

    private void showUploadFinishedDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.dangerreport_next_upload_ok);
        builder.setCancelable(false);
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> forward(UiReported.class));
        builder.show();
    }

    public final static String REPORT_DETAIL_UPLOADED = "dangerReportDetailUploaded";
    public static class ReportDetailMessageEvent {
        public String message;
        Object arg;
        ReportDetailMessageEvent(String message, Object obj) {
            this.message = message;
            this.arg = obj;
        }
    }

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

    @Override
    protected void onDestroy() {
        //重置数据状态
        resetData();
        MediaManager.release();//重置

        EventBusUtil.unregister(this);
        super.onDestroy();
    }
}
