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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.esri.arcgisruntime.geometry.Point;
import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.AudioRecordButton;
import com.gaoyuan.weixinrecord.manager.MediaManager;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.mgq.base.utils.toast.ToastUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.common.ui.activity.UiBuildManageDetail;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.module.buildManage.BuildTool;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBean;
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.TroublePictureBean;
import com.tofly.ghrq_route.module.uploadFile.controller.UploadFileCallBack;
import com.tofly.ghrq_route.module.uploadFile.domain.UploadFileBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.ui.activity.UiBigImageList;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.date.TimeUtil;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.common.util.image.ImageUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;
import com.tofly.ghrq_route.common.util.recorder.AudioRecordHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.hzw.graffiti.WaterMarkParams;

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

public class BuildInfoFragment extends Fragment {
    @BindView(R.id.cardview_build_detail)
    CardView cardView;
    @BindView(R.id.text_build_name)
    TextView textBuildName;
    @BindView(R.id.image_navigate)
    ImageView imageNavigate;
    @BindView(R.id.text_build_addr)
    TextView textBuildAddr;
    @BindView(R.id.text_build_state)
    TextView textBuildState;
    @BindView(R.id.layout_notice_warrant)
    LinearLayout layoutNotice;
    @BindView(R.id.layout_notice_audio)
    LinearLayout layoutNoticeAudio;
    @BindView(R.id.dangerreport1_addaudio)
    MyAudioRecordButton btnAddAudio;
    @BindView(R.id.audio_record_gallery)
    LinearLayout layoutAudioGallery;
    @BindView(R.id.layout_addaudio_area)
    LinearLayout layoutAddAudioArea;
    @BindView(R.id.text_build_company)
    TextView textBuildCompany;
    @BindView(R.id.text_build_charger)
    TextView textBuildCharger;
    @BindView(R.id.text_charger_phone)
    TextView textChargerPhone;
    @BindView(R.id.text_charge_company)
    TextView textChargeCompany;
    @BindView(R.id.text_create_time)
    TextView textCreateTime;
    @BindView(R.id.text_project_type)
    TextView textProjectType;
    @BindView(R.id.btn_repair_route_addr)
    Button btnGotoAddr;
    @BindView(R.id.btn_repair_route_route)
    Button btnRoute;
    @BindArray(R.array.build_state)
    String[] buildStates;
    Unbinder unbinder;

    private Activity mContext;

    private View mRootView;

    private BuildManageBean mBuildManage;
    private UiBuildManageDetail buildManageDetail;
    private List<TroublePictureBean> mPicturesUpload;
    private PhotoHelper photoHelper;
    private PermissionHelper permissionHelper;
    private BuildTool buildTool;

    private List<Record> mAudiosUpload = new ArrayList<>();
    private List<TroubleAudioBean> mTroubleAudios = new ArrayList<>();
    private List<AnimationDrawable> mAnimationDrawables = new ArrayList<>();

    private boolean isEditable = true;

    public BuildInfoFragment(BuildManageBean buildManage, PermissionHelper permissionHelper, PhotoHelper photoHelper) {
        this.mBuildManage = buildManage;
        this.permissionHelper = permissionHelper;
        this.photoHelper = photoHelper;
        buildTool = BuildTool.getInstance();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView == null) {
            mContext = getActivity();
            buildManageDetail = (UiBuildManageDetail) mContext;
            mRootView = inflater.inflate(R.layout.fragment_build_info, container, false);
        } else {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (parent != null) {
                parent.removeView(mRootView);
            }
        }
        unbinder = ButterKnife.bind(this, mRootView);

        return mRootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (permissionHelper == null)
            permissionHelper = new PermissionHelper(mContext);
        initView();
        initListener();
    }

    private void initView() {
        if (mBuildManage != null) {
            /*工地名称*/
            String buildName = mBuildManage.getSiteName();
            textBuildName.setText(buildName);

            /*工地地址*/
            String buildAddr = mBuildManage.getConstructionAddress();
            textBuildAddr.setText(buildAddr);

//            /*工地状态*/
//            int state = mBuildManage.getBuild_state();
//            if (state >= 0 && state + 1 < buildStates.length) {
//                textBuildState.setText(buildStates[state + 1]);
//            }

            /*施工单位*/
            String builcCompany = mBuildManage.getConstructionUnit();
            textBuildCompany.setText(builcCompany);

            /*施工负责人*/
            String sceneCharger = mBuildManage.getConstructionPerson();
            textBuildCharger.setText(sceneCharger);

            /*施工负责人电话*/
            String projectChargerPhone = mBuildManage.getPersonInChargePhone();
            textChargerPhone.setText(projectChargerPhone);

            /*主管单位*/
            String chargeCompany = mBuildManage.getManageUnit();
            textChargeCompany.setText(chargeCompany);

//            /*建档日期*/
//            String createTime = mBuildManage.getCreate_time();
//            textCreateTime.setText(createTime);
//
//            /*工地类型*/
//            String projectType = mBuildManage.getProject_type_name();
//            textProjectType.setText(projectType);


            //mPicturesUpload = mBuildManage.getGaozhishu();
            //mTroubleAudios = mBuildManage.getGaozhishuAudio();
            buildTool.getBuildNoticeFiles(mContext, mBuildManage, new BuildTool.GetBuildNotice() {
                @Override
                public void buildHasNoticeFile(boolean isSuccess, boolean hasNoticeFile, List<TroublePictureBean> photos, List<TroubleAudioBean> audios) {
                    mPicturesUpload = photos;
                    mTroubleAudios = audios;
                    if (photos != null && photos.size() > 0){
                        getPhotoViewFromPath();
                    }
                    if (audios != null && audios.size() > 0){
                        getRecordViewFromAudio();
                    }
                }
            });

        }
    }

    private void initListener(){
        AudioRecordHelper audioRecordHelper = new AudioRecordHelper(mContext, permissionHelper, btnAddAudio);
        audioRecordHelper.initRecordButton();
        AudioRecordButton.AudioFinishRecorderListener mRecorderListener = new AudioRecordButton.AudioFinishRecorderListener() {
            @Override
            public void onFinished(float seconds, String filePath) {
                String time = DateUtils.getDate(new Date().getTime());
                int audioLength = (int) seconds <= 0 ? 1 : (int) seconds;

                final TroubleAudioBean audioBean = new TroubleAudioBean();
                String audioId = UUID.randomUUID().toString();
                audioBean.setId(audioId);
                audioBean.setTroubleid(mBuildManage.getId());
                audioBean.setSecond(audioLength);
                audioBean.setCreateTime(time);
                audioBean.setPath(filePath);
                audioBean.setStatus(TroublePictureBean.PHOTO_LOCAL_STATE);
                buildTool.addBuildNoticeAudio(mContext, mBuildManage.getId(), audioBean, new UploadFileCallBack(){
                    @Override
                    public void onAddUploadFile(boolean isSuccess, int errorCode, String errMsg, UploadFileBean fileBean) {
                        super.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                        mTroubleAudios.add(audioBean);
                        getRecordViewFromAudio();
                    }
                });
            }
        };
        btnAddAudio.setAudioFinishRecorderListener(mRecorderListener);
        btnAddAudio.setOnAudioStartPrepareListener(new AudioRecordButton.AudioStartPrepareListener() {
            @Override
            public void onStartPrepare() {
                //重置动画
                for (AnimationDrawable ad : mAnimationDrawables) {
                    ad.selectDrawable(0);
                    ad.stop();
                }
                //重置数据状态
                resetData();
                //停止播放
                MediaManager.release();
            }
        });
    }

    private void showAddPictureDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext).
                setItems(new String[]{"拍照", "从手机相册选择"},
                        (arg0, i) -> {
                            if (i == 0) {
                                getPicFromSysCamera();
                            }else if (i == 1) {
                                getPicFromSysAlbums();
                            }
                        });
        dialog.setCancelable(true);
        dialog.show();
    }

    private WaterMarkParams getWaterMarkParams(){
        WaterMarkParams params = null;
        if (mBuildManage != null && buildManageDetail != null){
            params = new WaterMarkParams();
            params.mbNeedGps = 1;
            String address = buildManageDetail.getCurBDAddress();
            Point location = buildManageDetail.getCurLocation();
            if (location != null){
                double lon = location.getX();
                double lat = location.getY();
                BigDecimal decimal = new BigDecimal(lon);
                lon = decimal.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                decimal = new BigDecimal(lat);
                lat = decimal.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                params.mLongitude = Double.toString(lon);
                params.mLatitude = Double.toString(lat);
            }
            params.mGpsFlag = 0;
            params.mAddress = address;
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null){
                params.mUser = userBean.getRealName();
                params.mCompany = userBean.getCompany_name();
            }
            params.mReportTime = DateUtils.getDate(new Date().getTime());
        }
        return params;
    }

    private void getPicFromSysCamera() {
        if (photoHelper == null)
            photoHelper = new PhotoHelper(mContext, permissionHelper);
        photoHelper.requestCameraPhoto(true, this::getWaterMarkParams, new PhotoHelper.PhotoListener() {
            @Override
            public void getPhoto(boolean success, String errStr, final TroublePictureBean pictureBean) {
                if (success) {
                    if (pictureBean != null) {
                        String time = DateUtils.getDate();
                        pictureBean.setCreateTime(time);
                        pictureBean.setStatus(TroublePictureBean.PHOTO_LOCAL_STATE);
                        buildTool.addBuildNoticePhoto(mContext, mBuildManage.getId(), pictureBean, new UploadFileCallBack(){
                            @Override
                            public void onAddUploadFile(boolean isSuccess, int errorCode, String errMsg, UploadFileBean fileBean) {
                                super.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                                mPicturesUpload.add(pictureBean);//本地缓存
                                getPhotoViewFromPath();
                            }
                        });
                    }
                } else {
                    ToastUtil.showToast(mContext, errStr);
                }
            }
        });
    }

    private void getPicFromSysAlbums() {
        photoHelper.requestImagePhoto(true, this::getWaterMarkParams, (success, errStr, pictureBean) -> {
            if (success) {
                if (pictureBean != null) {
                    String time = DateUtils.getDate();
                    pictureBean.setCreateTime(time);
                    pictureBean.setStatus(TroublePictureBean.PHOTO_LOCAL_STATE);
                    buildTool.addBuildNoticePhoto(mContext, mBuildManage.getId(), pictureBean, new UploadFileCallBack(){
                        @Override
                        public void onAddUploadFile(boolean isSuccess, int errorCode, String errMsg, UploadFileBean fileBean) {
                            super.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                            mPicturesUpload.add(pictureBean);//本地缓存
                            getPhotoViewFromPath();
                        }
                    });
                }
            } else {
                ToastUtil.showToast(mContext, errStr);
            }
        });
    }

    private ArrayList<String> getPicsPath(){
        ArrayList<String> pics = new ArrayList<>();
        for (TroublePictureBean pictureBean : mPicturesUpload){
            if (pictureBean != null){
                String real_path = pictureBean.getFilepath();
                if (pictureBean.getStatus() == TroublePictureBean.PHOTO_UPLOADED) {
                    real_path = pictureBean.getRealPath();
                }
                pics.add(real_path);
            }
        }
        return pics;
    }

    @SuppressLint("InflateParams")
    public void getPhotoViewFromPath() {
        layoutNotice.setVisibility(View.VISIBLE);
        layoutNotice.removeAllViews();
        int total  = mPicturesUpload.size();
        for (int i = 0; i <= total ; i+=3){
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            final HorizontalScrollView scrollView = new HorizontalScrollView(mContext);
            scrollView.setLayoutParams(layoutParams);

            final LinearLayout layoutGallery = new LinearLayout(mContext);
            layoutParams.setMargins(10, 0,10, 0);
            layoutGallery.setLayoutParams(layoutParams);
            layoutGallery.setGravity(Gravity.CENTER_VERTICAL);
            layoutGallery.setWeightSum(3.0f);
            layoutGallery.setOrientation(LinearLayout.HORIZONTAL);

            scrollView.addView(layoutGallery);
            for (int j = i; j < i+3 && j <= total; j++){
                final View rootView = LayoutInflater.from(mContext).inflate(R.layout.item_notice_photo, null);
                TextView textPhotoType = rootView.findViewById(R.id.text_photo_type);
                final ImageView imageUploadPhoto = rootView.findViewById(R.id.image_upload_photo);
                ImageView imageAddPhoto = rootView.findViewById(R.id.image_add_photo);
                final ProgressBar progressUpload = rootView.findViewById(R.id.progress_upload);
                final TextView textUploadHint = rootView.findViewById(R.id.text_upload_hint);
                final ImageView imageOperation = rootView.findViewById(R.id.image_upload_operation);
                final ImageView imageFailed = rootView.findViewById(R.id.image_failed);

                if (j != total){
                    imageAddPhoto.setVisibility(View.GONE);

                    final TroublePictureBean picture = mPicturesUpload.get(j);
                    rootView.setTag(picture);

                    String photoType = picture.getCreateTime();
                    textPhotoType.setText(photoType);

                    final String photoPath = picture.getFilepath();
                    final String url = picture.getFile();
                    int state = picture.getStatus();
                    if (state == TroublePictureBean.PHOTO_LOCAL_STATE) {
                        Bitmap bitmap = ImageUtil.getimage(photoPath, 100, 100);
                        imageUploadPhoto.setImageBitmap(bitmap);
                        /*if (mBuildManage != null) {
                            picture.setStatus(TroublePictureBean.PHOTO_UPLOADING);
                            imageOperation.setVisibility(View.GONE);
                            progressUpload.setVisibility(View.VISIBLE);
                            textUploadHint.setText("正在上传");
                            addBuildNoticePhoto(picture, rootView);
                        }*/
                    } else if (state == TroublePictureBean.PHOTO_UPLOADED) {
                        if (url != null || photoPath != null) {
                            String real_url;
                            if (photoPath == null || !FileUtil.fileExists(photoPath)) {
                                real_url = NetRequestURL.getHttpHead() + url;
                            }else {
                                real_url = "file://" + photoPath;
                            }
                            ImageLoader loader = ImageLoader.getInstance();
                            loader.displayImage(real_url, imageUploadPhoto, new ImageLoadingListener() {
                                @Override
                                public void onLoadingStarted(String s, View view) {
                                    progressUpload.setVisibility(View.VISIBLE);
                                    imageUploadPhoto.setVisibility(View.GONE);
                                }

                                @Override
                                public void onLoadingFailed(String s, View view, FailReason failReason) {
                                    progressUpload.setVisibility(View.GONE);
                                    imageFailed.setVisibility(View.VISIBLE);
                                }

                                @Override
                                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                                    progressUpload.setVisibility(View.GONE);
                                    imageUploadPhoto.setVisibility(View.VISIBLE);
                                }

                                @Override
                                public void onLoadingCancelled(String s, View view) {

                                }
                            });
                            imageOperation.setVisibility(View.GONE);
                            progressUpload.setVisibility(View.GONE);
                            textUploadHint.setVisibility(View.GONE);
                        }
                    } else if (state == TroublePictureBean.PHOTO_SAVED_STATE){
                        Bitmap bitmap = ImageUtil.getimage(photoPath, 100, 100);
                        imageUploadPhoto.setImageBitmap(bitmap);
                        imageOperation.setVisibility(View.GONE);
                        progressUpload.setVisibility(View.GONE);
                        textUploadHint.setVisibility(View.GONE);
                    }

                    rootView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // 点击图片查看大图
                            TroublePictureBean pictureBean = (TroublePictureBean) view.getTag();
                            String PicAbsolutePath = pictureBean.getFilepath();
                            if (pictureBean.getStatus() == TroublePictureBean.PHOTO_UPLOADED){
                                PicAbsolutePath = pictureBean.getRealPath();
                            }
                            Bundle mBundle = new Bundle();
                            mBundle.putString(ImageUtil.CURRENT_PATH_KEY, PicAbsolutePath);
                            mBundle.putStringArrayList(ImageUtil.PICS_PATH_KEY, getPicsPath());
                            Intent intent = new Intent(mContext, UiBigImageList.class);
                            intent.putExtras(mBundle);
                            startActivity(intent);
                        }
                    });

                    imageOperation.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            picture.setStatus(TroublePictureBean.PHOTO_UPLOADING);
                            imageOperation.setVisibility(View.GONE);
                            progressUpload.setVisibility(View.VISIBLE);
                            textUploadHint.setText("正在上传");
                            addBuildNoticePhoto(picture, rootView);
                        }
                    });

                    rootView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(final View view) {
                            if (isEditable){
                                String title = "删除图片";
                                String content = "是否删除图片?";
                                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                                builder.setTitle(title);
                                builder.setMessage(content);
                                builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        TroublePictureBean pictureBean = (TroublePictureBean) view.getTag();
                                        if (pictureBean.getStatus() != TroublePictureBean.PHOTO_UPLOADED) {
                                            FileUtil.deleteFile(pictureBean.getFilepath());
                                            //layoutGallery.removeView(view);
                                            buildTool.deleteLocalBuildPhoto(pictureBean);
                                            mPicturesUpload.remove(picture);
                                            getPhotoViewFromPath();
                                        } else {
                                            removeUploadFile(pictureBean);
                                        }
                                    }
                                });
                                builder.setNegativeButton(android.R.string.cancel, null);
                                builder.show();
                            }
                            return true;
                        }
                    });
                }else {
                    imageUploadPhoto.setVisibility(View.GONE);
                    textPhotoType.setVisibility(View.GONE);
                    progressUpload.setVisibility(View.GONE);
                    imageOperation.setVisibility(View.GONE);
                    imageAddPhoto.setVisibility(View.VISIBLE);
                    imageAddPhoto.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showAddPictureDialog();
                        }
                    });
                }
                layoutGallery.addView(rootView);
            }
            layoutNotice.addView(scrollView);
        }
    }

    private void addBuildNoticePhoto(final TroublePictureBean picture, final View rootView) {
        final ImageView imageUploadPhoto = rootView.findViewById(R.id.image_upload_photo);
        final TextView textUploadHint = rootView.findViewById(R.id.text_upload_hint);
        final ImageView imageOperation = rootView.findViewById(R.id.image_upload_operation);
        final ProgressBar progressUpload = rootView.findViewById(R.id.progress_upload);
        final ImageView imageFailed = rootView.findViewById(R.id.image_failed);
        buildTool.addBuildNoticePhoto(mContext, mBuildManage.getId(), picture, new UploadFileCallBack(){
            @Override
            public void onAddUploadFile(boolean isSuccess, int errorCode, String errMsg, UploadFileBean fileBean) {
                super.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                if (isSuccess) {
                    textUploadHint.setText("上传成功");
                    progressUpload.setVisibility(View.GONE);
                    imageOperation.setVisibility(View.GONE);
                    if (fileBean != null) {
                        String filepath = fileBean.getFilename();
                        if (filepath != null && !filepath.isEmpty()) {
                            String url = NetRequestURL.getHttpHead() + filepath;
                            ImageLoader loader = ImageLoader.getInstance();
                            loader.displayImage(url, imageUploadPhoto, new ImageLoadingListener() {
                                @Override
                                public void onLoadingStarted(String s, View view) {
                                    progressUpload.setVisibility(View.VISIBLE);
                                    imageUploadPhoto.setVisibility(View.GONE);
                                }

                                @Override
                                public void onLoadingFailed(String s, View view, FailReason failReason) {
                                    progressUpload.setVisibility(View.GONE);
                                    imageFailed.setVisibility(View.VISIBLE);
                                }

                                @Override
                                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                                    progressUpload.setVisibility(View.GONE);
                                    imageUploadPhoto.setVisibility(View.VISIBLE);
                                }

                                @Override
                                public void onLoadingCancelled(String s, View view) {

                                }
                            });
                            textUploadHint.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    textUploadHint.setVisibility(View.GONE);
                                }
                            }, 2000);
                        }
                    }
                } else {
                    textUploadHint.setText("上传失败");
                    progressUpload.setVisibility(View.GONE);
                    imageOperation.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void getAudiosFromServer(List<UploadFileBean> audios){
        if (audios != null && audios.size() > 0){
            mAudiosUpload = new ArrayList<>();
            layoutAudioGallery.removeAllViews();
            for (UploadFileBean fileBean: audios) {
                final String url = NetRequestURL.getHttpHead() + fileBean.getFilename();
                int audioLength;
                if (fileBean.getAudiolength() != null){
                    try{
                        audioLength = Integer.parseInt(fileBean.getAudiolength());
                    }catch (NumberFormatException e){
                        audioLength = 1;
                    }
                }else {
                    audioLength = 1;
                }
                String time = fileBean.getUpload_time();

                TroubleAudioBean audioBean = new TroubleAudioBean();
                String audioId = UUID.randomUUID().toString();
                audioBean.setId(audioId);
                audioBean.setTroubleid(mBuildManage.getId());
                audioBean.setSecond(audioLength);
                audioBean.setCreateTime(time);
                audioBean.setUrl(url);
                audioBean.setStatus(TroublePictureBean.PHOTO_UPLOADED);
                mTroubleAudios.add(audioBean);

                getRecordViewFromAudio();
            }
        }
    }

    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 void getRecordViewFromAudio(){
        if (layoutAudioGallery != null)
            layoutAudioGallery.removeAllViews();
        mAudiosUpload.clear();

        int total  = mTroubleAudios.size();
        for (int i = 0; i < total; i++){
            final View rootView = LayoutInflater.from(mContext).inflate(R.layout.item_notice_audio, null);
            final LinearLayout layoutAudio = rootView.findViewById(R.id.layout_audio_signal);
            final TextView textPhotoType = rootView.findViewById(R.id.text_photo_type);
            final ProgressBar progressUpload = rootView.findViewById(R.id.progress_upload);
            final TextView textTime = rootView.findViewById(R.id.text_audio_time);
            final LinearLayout layoutHint = rootView.findViewById(R.id.layout_upload_hint);
            final TextView textUploadHint = rootView.findViewById(R.id.text_upload_hint);
            final ImageView imageOperation = rootView.findViewById(R.id.image_upload_operation);
            final ImageView imageFailed = rootView.findViewById(R.id.image_failed);

            final TroubleAudioBean audioBean = mTroubleAudios.get(i);

            String photoType = audioBean.getCreateTime();
            textPhotoType.setText(photoType);

            final String photoPath = audioBean.getPath();
            final String url = audioBean.getUrl();
            int audioLength = audioBean.getSecond();
            int state = audioBean.getStatus();
            final String time = audioBean.getCreateTime();
            if (state == TroublePictureBean.PHOTO_LOCAL_STATE) {
                final Record recordModel = new Record(photoPath, audioLength, time);
                mAudiosUpload.add(recordModel);
                rootView.setTag(R.id.tag_build_info_audio, audioBean);
                rootView.setTag(R.id.tag_build_info_record, recordModel);
                layoutAudio.setVisibility(View.VISIBLE);
                progressUpload.setVisibility(View.GONE);

                String strlen = TimeUtil.audioSecondToString(audioLength);
                textTime.setText(strlen);
                /*layoutHint.setVisibility(View.VISIBLE);
                textUploadHint.setText("点击上传");*/
            } else if (state == TroublePictureBean.PHOTO_UPLOADED) {
                if (url != null) {
                    buildTool.getUploadAudioFromServer(mContext, mBuildManage.getId(), url, audioLength, audioBean.getFilenote(), new TroubleTool.GetAudioCallback() {
                        @Override
                        public void onGetAudioRecord(boolean isSuccess, Record record) {
                            progressUpload.setVisibility(View.GONE);
                            if (isSuccess){
                                mAudiosUpload.add(record);
                                rootView.setTag(R.id.tag_build_info_audio, audioBean);
                                rootView.setTag(R.id.tag_build_info_record, record);
                                layoutAudio.setVisibility(View.VISIBLE);
                            }else {
                                imageFailed.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                    layoutHint.setVisibility(View.GONE);
                    imageOperation.setVisibility(View.GONE);
                    progressUpload.setVisibility(View.GONE);
                    String strlen = TimeUtil.audioSecondToString(audioLength);
                    textTime.setText(strlen);
                }
            } else if (state == TroublePictureBean.PHOTO_SAVED_STATE){
                Record record  = new Record(photoPath, audioBean.getSecond(), audioBean.getCreateTime());
                mAudiosUpload.add(record);
                rootView.setTag(R.id.tag_build_info_audio, audioBean);
                rootView.setTag(R.id.tag_build_info_record, record);
                layoutAudio.setVisibility(View.VISIBLE);
                progressUpload.setVisibility(View.GONE);

                String strlen = TimeUtil.audioSecondToString(audioLength);
                textTime.setText(strlen);
                /*layoutHint.setVisibility(View.VISIBLE);
                textUploadHint.setText("点击上传");
                imageOperation.setVisibility(View.VISIBLE);*/
            }

            rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Record record1 = (Record) view.getTag(R.id.tag_build_info_record);
                    if (record1 != null){
                        record1.setPlayed(true);
                        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();
                                        }
                                    });
                        }
                    }
                }
            });

            layoutHint.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (audioBean.getStatus() != TroublePictureBean.PHOTO_UPLOADED){
                        audioBean.setStatus(TroublePictureBean.PHOTO_UPLOADING);
                        imageOperation.setVisibility(View.GONE);
                        progressUpload.setVisibility(View.VISIBLE);
                        textUploadHint.setText("正在上传");
                        addBuildNoticeAudio(audioBean, rootView);
                    }
                }
            });

            rootView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(final View view) {
                    final TroubleAudioBean audioBean1 = (TroubleAudioBean) view.getTag(R.id.tag_build_info_audio);
                    final Record record1 = (Record) view.getTag(R.id.tag_build_info_record);
                    if (isEditable && audioBean1.getStatus() != TroublePictureBean.PHOTO_UPLOADED){
                        String title = "删除语音";
                        String content = "是否删除语音?";
                        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                        builder.setTitle(title);
                        builder.setMessage(content);
                        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String audio_path = record1.getPath();
                                FileUtil.deleteFile(audio_path);
                                buildTool.deleteLocalBuildAudio(audioBean1);
                                mAudiosUpload.remove(record1);
                                mTroubleAudios.remove(audioBean1);
                                getRecordViewFromAudio();
                            }
                        });
                        builder.setNegativeButton(android.R.string.cancel, null);
                        builder.show();
                    }
                    return true;
                }
            });
            layoutAudioGallery.addView(rootView);
        }
    }

    private void addBuildNoticeAudio(final TroubleAudioBean audioBean, final View rootView) {
        final LinearLayout layoutHint = rootView.findViewById(R.id.layout_upload_hint);
        final TextView textUploadHint = rootView.findViewById(R.id.text_upload_hint);
        final ImageView imageOperation = rootView.findViewById(R.id.image_upload_operation);
        final ProgressBar progressUpload = rootView.findViewById(R.id.progress_upload);
        buildTool.addBuildNoticeAudio(mContext, mBuildManage.getId(), audioBean, new UploadFileCallBack(){
            @Override
            public void onAddUploadFile(boolean isSuccess, int errorCode, String errMsg, UploadFileBean fileBean) {
                super.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                progressUpload.setVisibility(View.GONE);
                if (isSuccess){
                    textUploadHint.setText("上传成功");
                    imageOperation.setVisibility(View.GONE);
                    layoutHint.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            layoutHint.setVisibility(View.GONE);
                        }
                    }, 1000);
                }else {
                    textUploadHint.setText("上传失败");
                    imageOperation.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void removeUploadFile(final TroublePictureBean pictureBean) {
        String strUploading = getString(R.string.repair_update_deleting_photo);
        ProgressManager.getInstance().showProgress(mContext, null, strUploading, false);
        buildTool.removeBuildNoticePhoto(mContext, pictureBean, new UploadFileCallBack(){
            @Override
            public void onRemoveUploadFile(boolean isSuccess, int errorCode, String errMsg) {
                super.onRemoveUploadFile(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    //layoutNotice.removeView(view);
                    mPicturesUpload.remove(pictureBean);
                    getPhotoViewFromPath();
                }
            }
        });
    }

    private void onBtnRoute(){
        buildManageDetail.onTurnToBaiduRoute();
    }

    @OnClick({R.id.btn_repair_route_route, R.id.btn_repair_route_addr})
    void onClick(View view) {
        if (view.getId() == R.id.btn_repair_route_route) {
            onBtnRoute();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

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

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

        //重置数据状态
        if (mAudiosUpload != null) {
            for (Record record : mAudiosUpload) {
                record.setPlaying(false);
            }
        }
        MediaManager.release();//重置
    }
}
