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

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.esri.arcgisruntime.geometry.Point;
import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.MediaManager;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.lcp.arecyclerview.widget.ARecycleView;
import com.lcp.arecyclerview.widget.ARecyclerBaseAdapter;
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.plan.domain.PlanBean;
import com.tofly.ghrq_route.module.plan.domain.PlanBean.PlanDeviceType;
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.GetUploadFileCallback;
import com.tofly.ghrq_route.module.uploadFile.domain.UploadFileBean;
import com.tofly.ghrq_route.common.ui.activity.UiReportedClear;
import com.tofly.ghrq_route.module.trouble.ui.UiTroubleRecordDetail;
import com.tofly.ghrq_route.module.trouble.ui.UiTroubleRecordHistory;
import com.tofly.ghrq_route.common.ui.adapter.PlanTroubleRecordAdapter;
import com.tofly.ghrq_route.common.util.Location.LocationUtil;
import com.tofly.ghrq_route.common.util.Location.LocationUtil_xu;
import com.tofly.ghrq_route.common.util.image.ImageUtil;

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_STATE;
import static com.tofly.ghrq_route.module.trouble.domain.TroubleBean.TROUBLE_STATE;

/**
 * Created by Amu on 2017/2/21.
 */

public class BottomSheetDangerDetail extends LinearLayout{
    @BindView(R.id.detail_cardview)
    CardView cardViewBottomDetail;
    @BindView(R.id.bottom_sheet_detail_header)
    RelativeLayout textBottomSheetDetailHeader;
    @BindView(R.id.bottom_sheet_detail_header_close)
    ImageView imageViewBottomDetailClose;
    @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.reporteddetail_trouble_level)
    TextView reporteddetailTroubleLevel;
    @BindView(R.id.reporteddetail_trouble_levelcheck)
    TextView reporteddetailTroubleLevelCheck;
    @BindView(R.id.gallery)
    LinearLayout imageGallery;
/*    @BindView(R.id.layout_picture_clear)
    LinearLayout layoutClearArea;
    @BindView(R.id.layout_btn_add)
    LinearLayout layoutBtnAdd;
    @BindView(R.id.btn_add_photo)
    Button btnAddClearPhoto;*/
    @BindView(R.id.layout_audio_record)
    LinearLayout layoutAudioRecord;
    @BindView(R.id.audio_record_gallery)
    LinearLayout layoutAudioGallery;
    @BindView(R.id.layout_trouble_middle)
    LinearLayout layoutRouteModule;
    @BindView(R.id.recycler_trouble_middle)
    ARecycleView recycleTroubleRecord;
    @BindView(R.id.layout_trouble_middle_function)
    LinearLayout layoutRecordFunc;
    @BindView(R.id.btn_trouble_route_add)
    Button btnRouteAdd;
    @BindView(R.id.btn_trouble_route_more)
    Button btnRouteMore;
    @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 layoutClearFunc;
    @BindView(R.id.btn_confirm_clear)
    Button btnConfirmClear;
    @BindView(R.id.btn_trouble_clear_more)
    Button btnClearMore;

    private Context mContext;
    private TroubleTool troubleTool;
    private TroubleBean mTroubleUpload;
    private OfflinePathBean mPlanPoint;
    private Point mLocation;
    private List<Record> mAudioRecords;
    private List<AnimationDrawable> mAnimationDrawables = new ArrayList<>();
    private BottomSheetBehavior bottomSheetBehavior = null;
    private boolean isBottomSheetDetailShow = false;
    private boolean isDialogMode = false;
    private boolean isClearEnabled = false;
/*    private PhotoHelper photoHelper;
    private PermissionHelper permissionHelper;*/

    private PlanTroubleRecordAdapter troubleRecordAdapter;

    private PlanTroubleRecordAdapter troubleClearRecordAdapter;

    private ImageUtil imageUtil;

    private onDetailButtonCloseClicked mOnDetailButtonCloseClicked;

    final int BOTTOM_SHEET_BOTTOM = BaseApp.dip2px(56);
    final int BOTTOM_SHEET_MIDDLE = BaseApp.dip2px(350);
    final int BOTTOM_SHEET_TOP = ViewGroup.LayoutParams.MATCH_PARENT;

    public BottomSheetDangerDetail(Context context) {
        this(context, null);
    }

    public BottomSheetDangerDetail(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomSheetDangerDetail(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;
        imageUtil = new ImageUtil(context);
        troubleTool = TroubleTool.getInstance();

        initAttrs(attrs);
        initView();
        initListener();
    }

    public boolean isBottomSheetDetailShowing(){ return isBottomSheetDetailShow; }

    public interface onDetailButtonCloseClicked{
        void onClicked();
    }

    public void setOnDetailButtonCloseClicked(onDetailButtonCloseClicked closeClicked){
        mOnDetailButtonCloseClicked = closeClicked;
    }

    public void setClearEnable(boolean enable){
        isClearEnabled = enable;
        btnRouteAdd.setEnabled(enable);
        btnConfirmClear.setEnabled(enable);
    }

    private void initAttrs(AttributeSet attrs){
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BottomSheetDangerDetail);
        try {
            isDialogMode = typedArray.getBoolean(R.styleable.BottomSheetDangerDetail_DialogMode, false);
        }finally {
            typedArray.recycle();
        }
    }

    private void initView(){
        inflate(mContext, R.layout.layout_bottom_sheet_detail, this);
        ButterKnife.bind(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recycleTroubleRecord.setLayoutManager(linearLayoutManager);
        recycleTroubleRecord.setItemAnimator(new DefaultItemAnimator());
        List<TroublePlanRecordBean> list = new ArrayList<>();
        troubleRecordAdapter = new PlanTroubleRecordAdapter(mContext, list, false);
        recycleTroubleRecord.setAdapter(troubleRecordAdapter);
        recycleTroubleRecord.setEnabled(false);

        LinearLayoutManager linearLayoutManagerClear = new LinearLayoutManager(mContext);
        recycleTroubleClear.setLayoutManager(linearLayoutManagerClear);
        recycleTroubleClear.setItemAnimator(new DefaultItemAnimator());
        troubleClearRecordAdapter = new PlanTroubleRecordAdapter(mContext, list, true);
        recycleTroubleClear.setAdapter(troubleClearRecordAdapter);
        recycleTroubleClear.setEnabled(false);
    }

    private void initListener(){
        if (!isDialogMode){
            imageViewBottomDetailClose.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    hideSelf();
                }
            });

            textBottomSheetDetailHeader.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                    } else if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
                        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                    }
                }
            });
        }
        btnRouteAdd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUiClear(false);
            }
        });
        btnConfirmClear.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUiClear(true);
            }
        });
        btnRouteMore.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUiRecordMore(false);
            }
        });

        btnClearMore.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                gotoUiRecordMore(true);
            }
        });

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

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

    private void gotoUiRecordDetail(TroublePlanRecordBean recordBean, boolean isClear) {
        if (mTroubleUpload != null && recordBean != null){
            Bundle bundle = new Bundle();
            bundle.putSerializable(TroubleBean.TROUBLE_BEAN_KEY, mTroubleUpload);
            bundle.putSerializable(OfflinePathBean.PLAN_POINT_BEAN_KEY, mPlanPoint);
            bundle.putSerializable(TroublePlanRecordBean.TROUBLE_RECORD_BEAN_KEY, recordBean);
            bundle.putBoolean(TroublePlanRecordBean.TROUBLE_RECORD_CLOSE_KEY, isClear);
            bundle.putBoolean(TroublePlanRecordBean.TROUBLE_RECORD_EDITABLE_KEY, isClearEnabled);
            Intent intent = new Intent();
            intent.setClass(mContext, UiTroubleRecordDetail.class);
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        }
    }

    private void gotoUiRecordMore(boolean isClear){
        if (mTroubleUpload != null){
            Bundle bundle = new Bundle();
            bundle.putSerializable(TroubleBean.TROUBLE_BEAN_KEY, mTroubleUpload);
            bundle.putSerializable(OfflinePathBean.PLAN_POINT_BEAN_KEY, mPlanPoint);
            bundle.putSerializable(TroublePlanRecordBean.TROUBLE_RECORD_CLOSE_KEY, isClear);
            bundle.putBoolean(TroublePlanRecordBean.TROUBLE_RECORD_EDITABLE_KEY, isClearEnabled);
            if (isClear)
                bundle.putString(BaseUi.MAIN_TITLE_KEY, mContext.getResources().getString(R.string.trouble_clear_record_history_title));
            Intent intent = new Intent();
            intent.setClass(mContext, UiTroubleRecordHistory.class);
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        }
    }

    private void gotoUiClear(boolean isClear) {
        if (mTroubleUpload != null && mPlanPoint != null){
            Bundle bundle = new Bundle();
            bundle.putBoolean(TroublePlanRecordBean.TROUBLE_RECORD_CLOSE_KEY, isClear);
            bundle.putSerializable(TroubleBean.TROUBLE_BEAN_KEY, mTroubleUpload);
            bundle.putSerializable(OfflinePathBean.PLAN_POINT_BEAN_KEY, mPlanPoint);
            if (mLocation != null) {
                LocationUtil_xu.CoordinateClass coordinate =
                        new LocationUtil_xu.CoordinateClass(mLocation.getX(), mLocation.getY());
                bundle.putSerializable(LocationUtil.CURRENT_LOCATION_KEY, coordinate);
            }
            if (!isClear)
                bundle.putString(BaseUi.MAIN_TITLE_KEY, mContext.getResources().getString(R.string.plan_route));
            Intent intent = new Intent();
            intent.setClass(mContext, UiReportedClear.class);
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        }
    }

    public void hideSelf(){
        isBottomSheetDetailShow = false;
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams)this.getLayoutParams();
        if (layoutParams.height == BOTTOM_SHEET_TOP){
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            this.postDelayed(new Runnable() {
                @Override
                public void run() {
                    BottomSheetDangerDetail.this.setVisibility(View.INVISIBLE);
                    if (mOnDetailButtonCloseClicked != null){
                        mOnDetailButtonCloseClicked.onClicked();
                    }
                }
            }, 50);
        }else {
            this.setVisibility(View.INVISIBLE);
            if (mOnDetailButtonCloseClicked != null){
                mOnDetailButtonCloseClicked.onClicked();
            }
        }
        layoutAudioRecord.setVisibility(View.GONE);
        //重置数据状态
        resetData();
        MediaManager.release();//重置
    }

    public void setBottomDetailState(@BottomSheetBehavior.State int state){
        if (bottomSheetBehavior != null){
            if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED
                    && state == BottomSheetBehavior.STATE_COLLAPSED) {
                bottomSheetBehavior.setState(state);
            } else if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED
                    && state == BottomSheetBehavior.STATE_EXPANDED) {
                bottomSheetBehavior.setState(state);
            }
        }
    }

    public void initBottomSheetDetail(TroubleBean trouble){
        initBottomSheetDetail(trouble, null, null, null);
    }

    public void initBottomSheetDetail(TroubleBean trouble, OfflinePathBean pointBean, PlanBean planBean, Point location) {
        isBottomSheetDetailShow = true;
        imageGallery.removeAllViews();
        layoutAudioGallery.removeAllViews();
        mTroubleUpload = trouble;
        mPlanPoint = pointBean;
        mLocation = location;
/*        this.permissionHelper = permissionHelper;
        this.photoHelper = photoHelper;*/

        if (isDialogMode){
            textBottomSheetDetailHeader.setOnClickListener(null);
            layoutRouteModule.setVisibility(VISIBLE);
            btnConfirmClear.setVisibility(VISIBLE);
            btnRouteAdd.setVisibility(VISIBLE);
        }else {
            btnConfirmClear.setVisibility(GONE);
            btnRouteAdd.setVisibility(GONE);
        }

        if (trouble != null){
            String strTroubleId = trouble.getId();
            String strRemark = trouble.getNotes();
            String strSubtime = trouble.getFindTime();
            String strAddress = trouble.getAddress();
            String strTroubleName = trouble.getTroubleName();
            int device_type_id = -1;
            if (planBean != null){
                device_type_id = planBean.getDevice_type_id();
            }

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

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

            layoutReportedDeviceType.setVisibility(View.GONE);

            int status = trouble.getSave_state();
            if (SAVED_STATE == status) {
                strSubtime = trouble.getFindTime();
                loadSavedTroublePictures(strTroubleId);
                loadSavedTroubleAudios(strTroubleId);
            } else {
                if (strSubtime == null || strSubtime.isEmpty()) {
                    strSubtime = trouble.getFindTime();
                }
                loadUploadedTroubleFiles(strTroubleId);
            }

            boolean isTrouble = false;
            if (status == TROUBLE_STATE){
                isTrouble = true;
                reporteddetailTroubleKind.setText("是");
                reporteddetailTroubleKind.setTextColor(getResources().getColor(R.color.colorPrimary));
            }else if (status == NOT_TROUBLE_STATE){
                reporteddetailTroubleKind.setText("否");
            }else {
                reporteddetailTroubleKind.setText("未确定");
            }
                        reporteddetailTroubleLevel.setText("未定级");
            reporteddetailTroubleLevelCheck.setText("未审核");

            reporteddetailTroubleAddr.setText(strAddress);
            reporteddetailDetail.setText(strRemark);
            reporteddetailTime.setText(strSubtime);

            if (isTrouble && isDialogMode){
                loadPlanTroubleRecord();

                if (false){
                    layoutUnclear.setVisibility(GONE);
                    btnRouteAdd.setVisibility(GONE);
                    btnConfirmClear.setVisibility(GONE);
                    loadPlanTroubleClearRecord();
                }else {
                    btnRouteAdd.setEnabled(isClearEnabled);
                     /*第三方未处理结束 (不再需要)*/
                    btnConfirmClear.setEnabled(isClearEnabled/* && handle_third_state == 2*/);
                    if (device_type_id == PlanDeviceType.PLAN_DEVICE_TYPE_YHXJ){
                        layoutRouteModule.setVisibility(VISIBLE);
                        layoutAfterArea.setVisibility(GONE);
                        btnConfirmClear.setVisibility(GONE);
                        btnRouteAdd.setVisibility(VISIBLE);
                    }else if (device_type_id == PlanDeviceType.PLAN_DEVICE_TYPE_YHZG){
                        layoutRouteModule.setVisibility(GONE);
                        layoutAfterArea.setVisibility(VISIBLE);
                        btnRouteAdd.setVisibility(GONE);
                        btnConfirmClear.setVisibility(VISIBLE);
                    }
                    layoutUnclear.setVisibility(VISIBLE);
                    if (isDialogMode){
                        /*if (handle_trouble_clear == TROUBLE_CLEAR_STATE){
                            loadPlanTroubleClearRecord();
                        }else {
                            loadSavedTroubleClearRecord();
                        }*/
                        loadPlanTroubleClearRecord();
                    }
                    else
                        layoutAfterResult.setVisibility(GONE);
                }
            }else {
                layoutAfterArea.setVisibility(GONE);
            }

        }

        if (!isDialogMode){
            CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams)this.getLayoutParams();
            layoutParams.height = BOTTOM_SHEET_MIDDLE;
            setLayoutParams(layoutParams);
            bottomSheetBehavior = BottomSheetBehavior.from(this);

            bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_BOTTOM);
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);

            final float[] offset = {0};
            bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                @Override
                public void onStateChanged(@NonNull View bottomSheet, int newState) {
                    CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams)bottomSheet.getLayoutParams();
                    switch (newState){
                        case BottomSheetBehavior.STATE_DRAGGING:
                            layoutParams.height = BOTTOM_SHEET_TOP;
                            bottomSheet.setLayoutParams(layoutParams);
                            break;
                        case BottomSheetBehavior.STATE_COLLAPSED:
                            break;
                        case BottomSheetBehavior.STATE_SETTLING:
                            if (offset[0] >=0 && offset[0]  <=1){
                                if (offset[0]  > 0.7 && offset[0] < 1){
                                    bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_MIDDLE);
                                    layoutParams.height = BOTTOM_SHEET_TOP;
                                    bottomSheet.setLayoutParams(layoutParams);
                                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                                }else if (offset[0] > 0.35 && offset[0] < 0.7){
                                    bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_BOTTOM);
                                    layoutParams.height = BOTTOM_SHEET_MIDDLE;
                                    bottomSheet.setLayoutParams(layoutParams);
                                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                                }else if (offset[0] != 0){
                                    bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_BOTTOM);
                                    layoutParams.height = BOTTOM_SHEET_MIDDLE;
                                    bottomSheet.setLayoutParams(layoutParams);
                                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                                }
                            }
                            break;
                        case BottomSheetBehavior.STATE_EXPANDED:
                            break;
                    }
                }

                @Override
                public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                    offset[0] = slideOffset;
                }
            });
        }
    }

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

    private void loadSavedTroubleAudios(String troubleId){
        List<TroubleAudioBean> audios = troubleTool.getSavedTroubleAudios(troubleId);
        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(mContext);
        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(mContext, 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 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){
        troubleTool.getUploadedTroubleFiles(mContext, troubleId, new GetUploadFileCallback() {
            @Override
            public void onGetPhotoAudio(boolean isSuccess, List<UploadFileBean> photos, List<UploadFileBean> audios) {
                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)
                    imageGallery.addView(view);
            }
        }
        if (audios != null && audios.size() > 0){
            mAudioRecords = new ArrayList<>();
            layoutAudioRecord.setVisibility(View.VISIBLE);
            for (UploadFileBean fileBean: audios) {
                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);
            }
        }
    }

    public void loadPlanTroubleRecord(){

    }

    public void loadPlanTroubleClearRecord(){

    }

}
