package com.tofly.ghrq_route.module.trouble;

import android.content.Context;

import com.gaoyuan.weixinrecord.example.Record;
import com.mgq.base.utils.logger.LogRecorder;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.module.OfflineWork.OfflineWorkTool;
import com.tofly.ghrq_route.module.OfflineWork.domain.OfflineWorkJobBean;
import com.tofly.ghrq_route.module.job.NotifyMsgDaoHelper;
import com.tofly.ghrq_route.module.notifyManage.NotifyManageBean;
import com.tofly.ghrq_route.module.trouble.controller.TroubleCallBack;
import com.tofly.ghrq_route.module.trouble.controller.TroubleController;
import com.tofly.ghrq_route.module.trouble.domain.AuditSchemeBean;
import com.tofly.ghrq_route.module.trouble.domain.RestrictFileBean;
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.uploadFile.GetUploadFileCallback;
import com.tofly.ghrq_route.module.uploadFile.controller.UploadFileCallBack;
import com.tofly.ghrq_route.module.uploadFile.controller.UploadFileController;
import com.tofly.ghrq_route.module.uploadFile.domain.UploadFileBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.file.FileSizeUtil;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.common.util.file.MimeUtil;
import com.tofly.ghrq_route.common.util.recorder.AudioRecordHelper;

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

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

public class TroubleTool {

    //private static final String TAG = TroubleTool.class.getName();

    private static TroubleTool troubleTool = null;

    private TroubleController troubleController;

    private UploadFileController uploadFileController;

    private TroubleDaoHelper troubleDaoHelper;

    private NotifyMsgDaoHelper notifyMsgDaoHelper;

    private OfflineWorkTool offlineWorkTool;

    private TroubleTool(){
        troubleDaoHelper = TroubleDaoHelper.getInstance();
        notifyMsgDaoHelper = NotifyMsgDaoHelper.getInstance();
        offlineWorkTool = OfflineWorkTool.getInstance();
    }

    public static synchronized TroubleTool getInstance(){
        if (troubleTool == null){
            troubleTool = new TroubleTool();
        }
        return troubleTool;
    }

    /**
     * 隐患上报
     * */
    /*保存隐患数据*/
    private void saveDanger(TroubleBean trouble, List<TroublePictureBean> pictureBeans, List<TroubleAudioBean> audioBeans, boolean auto_commit) {
        if (trouble != null) {
            /*保存隐患的数据信息*/
            String troubleId = trouble.getId();
            if (troubleId.isEmpty()){
                troubleId = UUID.randomUUID().toString();
                trouble.setId(troubleId);
            }

            int save_state = auto_commit ? TroubleBean.SAVED_STATE : TroubleBean.SAVED_NO_COMMIT_STATE;

            trouble.setFindTime(DateUtils.getCurrentDate());
            trouble.setSave_state(save_state);
            if (trouble.getUserid() == null || trouble.getUserid().isEmpty()) {
                UserBean userBean = BaseApp.getInstance().getLoginUser();
                if (userBean != null)
                    trouble.setUserid(userBean.getUserid());
            }
            troubleDaoHelper.insertOrUpdateTrouble(trouble);

            OfflineWorkJobBean workJobBean = new OfflineWorkJobBean();
            String job_id = UUID.randomUUID().toString();
            workJobBean.setId(job_id);
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            workJobBean.setUser_id(userBean.getUserid());
            workJobBean.setJob_type(OfflineWorkJobBean.OfflineWorkJobType.JOB_DANGER_DANGER_ADD);
            workJobBean.setRef_id(troubleId);

            /*保存隐患的图片*/
            if (pictureBeans != null && pictureBeans.size() > 0) {
                List<String> pic_ids = new ArrayList<>();
                for (TroublePictureBean pictureBean : pictureBeans) {
                    if (pictureBean != null && FileUtil.fileExists(pictureBean.getFilepath())) {
                        pictureBean.setTroubleid(troubleId);
                        pictureBean.setStatus(save_state);
                        troubleDaoHelper.insertOrUpdateTroublePicture(pictureBean);

                        pic_ids.add(pictureBean.getId());
                    }
                }
                workJobBean.setRef_photo_ids(pic_ids);
            }

            /*保存隐患的音频*/
            String filetype = "amr";
            if (audioBeans != null && audioBeans.size() > 0) {
                List<String> audio_ids = new ArrayList<>();
                for (TroubleAudioBean audioBean : audioBeans) {
                    if (audioBean != null && FileUtil.fileExists(audioBean.getPath())) {
                        String audioId = UUID.randomUUID().toString();
                        audioBean.setId(audioId);
                        audioBean.setTroubleid(troubleId);
                        audioBean.setFiletype(filetype);
                        audioBean.setStatus(save_state);
                        troubleDaoHelper.insertOrUpdateTroubleAudio(audioBean);

                        audio_ids.add(audioId);
                    }
                }
                workJobBean.setRef_audio_ids(audio_ids);
            }

            if (auto_commit)
                offlineWorkTool.insertOfflineWorkJob(workJobBean);
        }
    }

    public void saveDangerWithRecords(TroubleBean trouble, List<TroublePictureBean> pictureBeans, List<Record> records) {
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(records);
        saveDanger(trouble, pictureBeans, audioBeans, false);
    }

    private void updateLocalPhotoAudio(TroubleBean troubleBean, List<TroublePictureBean> pictureBeans, List<TroubleAudioBean> audioBeans){
        troubleDaoHelper.deleteSavedTrouble(troubleBean);
        /*删除本地的离线上传任务*/
        OfflineWorkJobBean workJobBean = offlineWorkTool.getOfflineWorkJob(troubleBean.getId());
        if (workJobBean != null){
            offlineWorkTool.deleteOfflineWorkJob(workJobBean);
        }

        /*更新本地隐患的图片*/
        for (TroublePictureBean pictureBean : pictureBeans) {
            if (pictureBean != null) {
                troubleDaoHelper.deleteSavedTroublePicture(pictureBean);
                FileUtil.deleteFile(pictureBean.getFilepath());
            }
        }

        /*更新本地隐患的音频*/
        for (TroubleAudioBean audioBean : audioBeans){
            if (audioBean != null) {
                troubleDaoHelper.deleteSavedTroubleAudio(audioBean);
                FileUtil.deleteFile(audioBean.getPath());
            }
        }
    }

    private void saveTroubleBean(TroubleBean troubleBean, int state){
        if (troubleBean != null) {
            troubleBean.setSave_state(state);
            troubleDaoHelper.insertOrUpdateTrouble(troubleBean);
        }
    }

    private void uploadNewTrouble(final Context context, final TroubleBean troubleBean, final List<TroublePictureBean> photos,
                                  final List<TroubleAudioBean> audios, final List<TroubleAudioBean> files, final boolean saveOnFail, final TroubleCallBack troubleCallBack) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && troubleBean != null) {
            final int old_state = troubleBean.getSave_state();
            saveTroubleBean(troubleBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleBean.setFindTime(DateUtils.getCurrentDate());
            troubleController.addTroubleNew(context, troubleBean, photos, audios, files, new TroubleCallBack() {
                @Override
                public void onAddTrouble(boolean isSuccess, int errorCode, String errMsg, String troubleId) {
                    super.onAddTrouble(isSuccess, errorCode, errMsg, troubleId);
                    if (isSuccess) {
/*                        String strWarn = context.getString(R.string.dangerreport_next_upload_ok);
                        ToastUtil.showToast(context, strWarn);*/

                        updateLocalPhotoAudio(troubleBean, photos, audios);
                    } else {
                        if (saveOnFail)
                            saveDanger(troubleBean, photos, audios, true);
                        else {
                            saveTroubleBean(troubleBean, old_state);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }

                    if (troubleCallBack != null){
                        troubleCallBack.onAddTrouble(isSuccess, errorCode, errMsg, troubleId);
                    }
                }
            });
        }
    }

/*    public void uploadNewTrouble(final Context context, final TroubleBean troubleBean, final List<TroublePictureBean> photos,
                                 final List<Record> records, final TroubleCallBack troubleCallBack){
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(records);
        uploadNewTrouble(context, troubleBean, photos, audioBeans, true, troubleCallBack);
    }*/

    public void uploadNewTrouble(final Context context, final TroubleBean troubleBean, final List<TroublePictureBean> photos,
                                 final List<Record> records, List<TroubleAudioBean> files, final TroubleCallBack troubleCallBack){
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(records);
        uploadNewTrouble(context, troubleBean, photos, audioBeans, files, false, troubleCallBack);
    }

    public void uploadNewTroubleNoSave(final Context context, final TroubleBean troubleBean, final List<TroublePictureBean> photos,
                                       final List<TroubleAudioBean> audios, List<TroubleAudioBean> files, final TroubleCallBack troubleCallBack){
        uploadNewTrouble(context, troubleBean, photos, audios, files, false, troubleCallBack);
    }

    /**
     * 隐患列表
     * */

    /*从服务器获取隐患列表*/
    public void getTroubleListOnline(Context context, int select_state, String keyword, int pageindex, TroubleCallBack troubleCallBack){
        getUploadTroubles(context, select_state, keyword, pageindex, troubleCallBack);
    }

    public void getUploadTroubles(final Context context, int select_state, String keyword, int pageindex, final TroubleCallBack troubleCallBack){
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        final int pagesize = C.DEFAULT_LOAD_PAGESIZE;
        if (userBean != null){
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleController.getTroubleList(context, userBean.getUserid(), select_state, keyword, pageindex, pagesize, new TroubleCallBack(){
                @Override
                public void onGetTroubleList(boolean isSuccess, int errorCode, String errMsg, List<TroubleBean> troubleBeanList, int total) {
                    super.onGetTroubleList(isSuccess, errorCode, errMsg, troubleBeanList, total);
                    if (isSuccess){
                    }else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }

                    if (troubleCallBack != null)
                        troubleCallBack.onGetTroubleList(isSuccess, errorCode, errMsg, troubleBeanList, total);
                }
            });
        }
    }

    public List<TroubleBean> getSavedTroubles(){
        List<TroubleBean> savedTroubles = null;
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            savedTroubles = troubleDaoHelper.getTroubleList(userBean.getUserid(), TroubleBean.SAVED_NO_COMMIT_STATE, TroubleBean.TROUBLE_TYPE_DANGER);
        }
        return savedTroubles;
    }

    private void loadTroubleInfo(final Context context, String troubleId, boolean online, final TroubleCallBack troubleCallBack){
        if (troubleId != null && !troubleId.isEmpty()){
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null) {
                if (troubleController == null)
                    troubleController = new TroubleController(context);
                troubleController.getTroubleInfo(context, troubleId, online, new TroubleCallBack() {
                    @Override
                    public void onGetTroubleInfo(boolean isSuccess, int errorCode, String errMsg, TroubleBean troubleBean) {
                        super.onGetTroubleInfo(isSuccess, errorCode, errMsg, troubleBean);
                        if (isSuccess) {
                        } else {
                            errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                            ToastUtil.showToast(context, errMsg);
                        }
                        if (troubleCallBack != null)
                            troubleCallBack.onGetTroubleInfo(isSuccess, errorCode, errMsg, troubleBean);
                    }
                });
            }
        }
    }

    public void loadTroubleFromServer(Context context, String troubleId, final TroubleCallBack troubleCallBack){
        loadTroubleInfo(context, troubleId, true, troubleCallBack);
    }

    public void loadTroubleFromLocal(Context context, String troubleId, final TroubleCallBack troubleCallBack){
        loadTroubleInfo(context, troubleId, false, troubleCallBack);
    }

    public void loadTroubleInfo(final Context context, final String troubleId, final TroubleCallBack troubleCallBack){
        loadTroubleFromServer(context, troubleId, new TroubleCallBack(){
            @Override
            public void onGetTroubleInfo(boolean isSuccess, int errorCode, String errMsg, TroubleBean troubleBean) {
                super.onGetTroubleInfo(isSuccess, errorCode, errMsg, troubleBean);
                if (isSuccess){
                    troubleCallBack.onGetTroubleInfo(true, errorCode, errMsg, troubleBean);
                }else {
                    loadTroubleFromLocal(context, troubleId, troubleCallBack);
                }
            }
        });
    }

    public TroubleBean getLocalTrouble(String troubleId){
        return troubleDaoHelper.queryTrouble(troubleId);
    }

    public void getTroubleEventType(Context context, TroubleCallBack troubleCallBack) {
        if (troubleController == null)
            troubleController = new TroubleController(context);
        troubleController.getTroubleEventType(context, new TroubleCallBack(){
            @Override
            public void onGetDatas(boolean isSuccess, int errorCode, String errMsg, List dataList, int total) {
                super.onGetDatas(isSuccess, errorCode, errMsg, dataList, total);
                if (isSuccess) {
                } else {
                    errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                    ToastUtil.showToast(context, errMsg);
                }
                if (troubleCallBack != null)
                    troubleCallBack.onGetDatas(isSuccess, errorCode, errMsg, dataList, total);
            }
        });
    }

    private void ondutyUserCheckTrouble(final Context context, final TroubleBean troubleBean, final List<TroublePictureBean> photos,
                                  final List<TroubleAudioBean> audios, List<TroubleAudioBean> files, final boolean saveOnFail, final TroubleCallBack troubleCallBack) {
        if (troubleBean != null) {
            final int old_state = troubleBean.getSave_state();
            saveTroubleBean(troubleBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleController.ondutyUserCheckTrouble(context, troubleBean, photos, audios, files, new TroubleCallBack() {
                @Override
                public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onSetData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
/*                        String strWarn = context.getString(R.string.upload_ok);
                        ToastUtil.showToast(context, strWarn);*/

                        updateLocalPhotoAudio(troubleBean, photos, audios);
                    } else {
                        if (saveOnFail)
                            saveDanger(troubleBean, photos, audios, true);
                        else {
                            saveTroubleBean(troubleBean, old_state);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }

                    if (troubleCallBack != null){
                        troubleCallBack.onSetData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    public void ondutyUserCheckTroubleNoSave(final Context context, final TroubleBean troubleBean, final List<TroublePictureBean> photos,
                                       final List<Record> records, List<TroubleAudioBean> files, final TroubleCallBack troubleCallBack){
        List<TroubleAudioBean> audios = TroubleAudioBean.getAudioBeans(records);
        ondutyUserCheckTrouble(context, troubleBean, photos, audios, files, false, troubleCallBack);
    }

    private void undertakerVerifyTrouble(final Context context, final TroubleBean troubleBean, final boolean saveOnFail, final TroubleCallBack troubleCallBack) {
        if (troubleBean != null) {
            final int old_state = troubleBean.getSave_state();
            saveTroubleBean(troubleBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleController.undertakerVerifyTrouble(context, troubleBean, new TroubleCallBack() {
                @Override
                public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onSetData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
/*                        String strWarn = context.getString(R.string.upload_ok);
                        ToastUtil.showToast(context, strWarn);*/

                        deleteSavedTrouble(troubleBean);
                    } else {
                        if (saveOnFail)
                            saveTroubleBean(troubleBean);
                        else {
                            deleteSavedTrouble(troubleBean);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }

                    if (troubleCallBack != null){
                        troubleCallBack.onSetData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    public void undertakerVerifyTroubleNoSave(final Context context, final TroubleBean troubleBean, final TroubleCallBack troubleCallBack){
        undertakerVerifyTrouble(context, troubleBean, false, troubleCallBack);
    }

    private void undertakerHandleTrouble(final Context context, final TroubleBean troubleBean, final List<TroublePictureBean> photos,
                                        final List<TroubleAudioBean> audios, List<TroubleAudioBean> files, final boolean saveOnFail, final TroubleCallBack troubleCallBack) {
        if (troubleBean != null) {
            final int old_state = troubleBean.getSave_state();
            saveTroubleBean(troubleBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleController.undertakerHandleTrouble(context, troubleBean, photos, audios, files, new TroubleCallBack() {
                @Override
                public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onSetData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
/*                        String strWarn = context.getString(R.string.upload_ok);
                        ToastUtil.showToast(context, strWarn);*/

                        updateLocalPhotoAudio(troubleBean, photos, audios);
                    } else {
                        if (saveOnFail)
                            saveDanger(troubleBean, photos, audios, true);
                        else {
                            saveTroubleBean(troubleBean, old_state);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }

                    if (troubleCallBack != null){
                        troubleCallBack.onSetData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    public void undertakerHandleTroubleNoSave(final Context context, final TroubleBean troubleBean, final List<TroublePictureBean> photos,
                                             final List<Record> records, List<TroubleAudioBean> files, final TroubleCallBack troubleCallBack){
        List<TroubleAudioBean> audios = TroubleAudioBean.getAudioBeans(records);
        undertakerHandleTrouble(context, troubleBean, photos, audios, files, false, troubleCallBack);
    }

    private void underSectaryVerifyAssignTrouble(final Context context, final TroubleBean troubleBean, AuditSchemeBean schemeBean, final boolean saveOnFail, final TroubleCallBack troubleCallBack) {
        if (troubleBean != null) {
            final int old_state = troubleBean.getSave_state();
            saveTroubleBean(troubleBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleController.underSectaryVerifyAssignTrouble(context, troubleBean, schemeBean, new TroubleCallBack() {
                @Override
                public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onSetData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
/*                        String strWarn = context.getString(R.string.upload_ok);
                        ToastUtil.showToast(context, strWarn);*/

                        deleteSavedTrouble(troubleBean);
                    } else {
                        if (saveOnFail)
                            saveTroubleBean(troubleBean);
                        else {
                            deleteSavedTrouble(troubleBean);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }

                    if (troubleCallBack != null){
                        troubleCallBack.onSetData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    public void underSectaryVerifyAssignTroubleNoSave(final Context context, final TroubleBean troubleBean, AuditSchemeBean schemeBean, final TroubleCallBack troubleCallBack){
        underSectaryVerifyAssignTrouble(context, troubleBean, schemeBean, false, troubleCallBack);
    }

    private void ondutyMakeScheme(Context context, String troubleId, int flag, AuditSchemeBean schemeBean, final boolean saveOnFail, final TroubleCallBack troubleCallBack) {
        if (troubleId != null) {
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleController.ondutyMakeScheme(context, troubleId, flag, schemeBean, new TroubleCallBack() {
                @Override
                public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onSetData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
/*                        String strWarn = context.getString(R.string.upload_ok);
                        ToastUtil.showToast(context, strWarn);*/
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }

                    if (troubleCallBack != null){
                        troubleCallBack.onSetData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    public void ondutyMakeSchemeNoSave(final Context context, final String troubleId, int flag, AuditSchemeBean schemeBean, final TroubleCallBack troubleCallBack){
        ondutyMakeScheme(context, troubleId, flag, schemeBean, false, troubleCallBack);
    }

    private void sectaryVerifyScheme(final Context context, final TroubleBean troubleBean, final boolean saveOnFail, final TroubleCallBack troubleCallBack) {
        if (troubleBean != null) {
            saveTroubleBean(troubleBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleController.sectaryVerifyScheme(context, troubleBean, new TroubleCallBack() {
                @Override
                public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onSetData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
/*                        String strWarn = context.getString(R.string.upload_ok);
                        ToastUtil.showToast(context, strWarn);*/

                        deleteSavedTrouble(troubleBean);
                    } else {
                        if (saveOnFail)
                            saveTroubleBean(troubleBean);
                        else {
                            deleteSavedTrouble(troubleBean);
                        }

                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }

                    if (troubleCallBack != null){
                        troubleCallBack.onSetData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    public void sectaryVerifySchemeNoSave(final Context context, final TroubleBean troubleBean, final TroubleCallBack troubleCallBack){
        sectaryVerifyScheme(context, troubleBean, false, troubleCallBack);
    }

    private void ondutyHandleScheme(final Context context, final TroubleBean troubleBean, String notes, final List<TroublePictureBean> photos,
                                         final List<TroubleAudioBean> audios, List<TroubleAudioBean> files, final boolean saveOnFail, final TroubleCallBack troubleCallBack) {
        if (troubleBean != null) {
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleController.ondutyHandleScheme(context, troubleBean, notes, photos, audios, files, new TroubleCallBack() {
                @Override
                public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onSetData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
/*                        String strWarn = context.getString(R.string.upload_ok);
                        ToastUtil.showToast(context, strWarn);*/
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }

                    if (troubleCallBack != null){
                        troubleCallBack.onSetData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    public void ondutyHandleSchemeNoSave(final Context context, final TroubleBean troubleBean, String notes, final List<TroublePictureBean> photos,
                                              final List<Record> records, List<TroubleAudioBean> files, final TroubleCallBack troubleCallBack){
        List<TroubleAudioBean> audios = TroubleAudioBean.getAudioBeans(records);
        ondutyHandleScheme(context, troubleBean, notes, photos, audios, files, false, troubleCallBack);
    }

    private void undersectaryVerifyHandle(final Context context, final TroubleBean troubleBean, final boolean saveOnFail, final TroubleCallBack troubleCallBack) {
        if (troubleBean != null) {
            saveTroubleBean(troubleBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleController.undersectaryVerifyHandle(context, troubleBean, new TroubleCallBack() {
                @Override
                public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onSetData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
/*                        String strWarn = context.getString(R.string.upload_ok);
                        ToastUtil.showToast(context, strWarn);*/

                        deleteSavedTrouble(troubleBean);
                    } else {
                        if (saveOnFail)
                            saveTroubleBean(troubleBean);
                        else {
                            deleteSavedTrouble(troubleBean);
                        }

                        String strWarn = context.getString(R.string.upload_fail_for) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }

                    if (troubleCallBack != null){
                        troubleCallBack.onSetData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    public void undersectaryVerifyHandleNoSave(final Context context, final TroubleBean troubleBean, final TroubleCallBack troubleCallBack){
        undersectaryVerifyHandle(context, troubleBean, false, troubleCallBack);
    }

    private void updatePipeDevice(final Context context, final TroubleBean troubleBean, final boolean saveOnFail, final TroubleCallBack troubleCallBack) {
        if (troubleBean != null) {
            saveTroubleBean(troubleBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (troubleController == null)
                troubleController = new TroubleController(context);
            troubleController.updatePipeDevice(context, troubleBean, new TroubleCallBack() {
                @Override
                public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onSetData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
/*                        String strWarn = context.getString(R.string.upload_ok);
                        ToastUtil.showToast(context, strWarn);*/

                        deleteSavedTrouble(troubleBean);
                    } else {
                        if (saveOnFail)
                            saveTroubleBean(troubleBean);
                        else {
                            deleteSavedTrouble(troubleBean);
                        }

                        String strWarn = context.getString(R.string.upload_fail_for) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }

                    if (troubleCallBack != null){
                        troubleCallBack.onSetData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    public void updatePipeDeviceNoSave(final Context context, final TroubleBean troubleBean, final TroubleCallBack troubleCallBack) {
        updatePipeDevice(context, troubleBean, false, troubleCallBack);
    }

    private void saveTroubleBean(TroubleBean troubleBean){
        if (troubleBean != null) {
            troubleDaoHelper.insertOrUpdateTrouble(troubleBean);
        }
    }

    public void deleteSavedTrouble(TroubleBean troubleBean) {
        troubleDaoHelper.deleteSavedTrouble(troubleBean);
    }


    public void saveTroublePicture(TroublePictureBean pictureBean){
        if (pictureBean != null) {
            troubleDaoHelper.insertOrUpdateTroublePicture(pictureBean);
        }
    }

    public TroublePictureBean getSavedTroublePictureByUrl(String fileUrl) {
        return troubleDaoHelper.queryTroublePictureByUrl(fileUrl);
    }

    public List<TroublePictureBean> getSavedTroublePictures(String troubleId){
        return troubleDaoHelper.queryTroublePictures(troubleId);
    }

    private void deleteSavedTroublePictures(String troubleId){
        List<TroublePictureBean> pictureBeans = troubleDaoHelper.queryTroublePictures(troubleId, TroubleBean.UPLOADED_STATE);
        if (pictureBeans != null){
            for (TroublePictureBean pictureBean : pictureBeans){
                troubleDaoHelper.deleteSavedTroublePicture(pictureBean);
                String file_path = pictureBean.getFilepath();
                if (file_path != null && FileUtil.fileExists(file_path)){
                    FileUtil.deleteFile(file_path);
                }
            }
        }
    }

    public List<TroubleAudioBean> getSavedTroubleAudios(String troubleId){
        return troubleDaoHelper.queryTroubleAudios(troubleId);
    }

    public TroubleAudioBean getTroubleAudio(String url){
        return troubleDaoHelper.queryTroubleAudio(url);
    }

    public TroubleAudioBean getTroubleAudioByFileNote(String fileNote){
        return troubleDaoHelper.queryTroubleAudioByFileNote(fileNote);
    }

    public void getUploadedTroubleFiles(Context context, final String troubleId, final GetUploadFileCallback getUploadFileCallback){
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            if (uploadFileController == null)
                uploadFileController = new UploadFileController(context);
            uploadFileController.getUploadFileList(userBean.getToken(), troubleId,
                    UploadFileBean.FILE_TABLE_TROUBLE,1, C.DEFAULT_MAX_LOAD_PAGESIZE, new UploadFileCallBack() {
                @Override
                public void onGetUploadFileList(boolean isSuccess, int errorCode, String errMsg, List<UploadFileBean> fileList) {
                    super.onGetUploadFileList(isSuccess, errorCode, errMsg, fileList);
                    List<UploadFileBean> uploadPhotos = new ArrayList<>();
                    List<UploadFileBean> uploadAudios = new ArrayList<>();
                    if (isSuccess && fileList != null) {
                        for (UploadFileBean fileBean : fileList) {
                            if (fileBean.getFilenote().equals(UploadFileBean.FILE_NOTE_DANGER_PHOTO_BEFORE)) {
                                uploadPhotos.add(fileBean);
                            } else if (fileBean.getFilenote().equals(UploadFileBean.FILE_NOTE_DANGER_AUDIO_BEFORE)) {
                                uploadAudios.add(fileBean);
                            }
                        }
                        if (errorCode == URLResponseCode.ErrorCode.SUCCESS){
                            deleteSavedTroublePictures(troubleId);
                            saveServerPhotos(uploadPhotos);
                        }
                    }
                    getUploadFileCallback.onGetPhotoAudio(isSuccess, uploadPhotos, uploadAudios);
                }
            });
        }
    }


    public interface GetAudioCallback{
        void onGetAudioRecord(boolean isSuccess, Record record);
    }

    public void getTroubleAudioFromServer(final Context context, final String troubleId, final String url, int audioLength,
                                               final String fileNote, final GetAudioCallback getAudioCallback) {
        boolean bHasCache = false;
        TroubleAudioBean audioBean = getTroubleAudio(url);
        String filePath = null;
        if (audioBean != null) {
            filePath = audioBean.getPath();
            if (filePath != null && FileUtil.fileExists(filePath)) {
                bHasCache = true;
            }
        }
        if (bHasCache) {
            Record record = new Record(filePath, audioBean.getSecond(), audioBean.getCreateTime());
            getAudioCallback.onGetAudioRecord(true, record);
        } else {
            final int length = audioLength;
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null) {
                if (troubleController == null)
                    troubleController = new TroubleController(context);
                String real_url = NetRequestURL.newApi_dyrq.getFormattedAudio(url);
                final String audio_id = audioBean != null ? audioBean.getId() : UUID.randomUUID().toString();
                troubleController.getTroubleAudio(userBean.getToken(), real_url, new TroubleCallBack() {
                    @Override
                    public void onGetTroubleAudio(boolean isSuccess, int errorCode, String errMsg, String path) {
                        super.onGetTroubleAudio(isSuccess, errorCode, errMsg, path);
                        Record record = null;
                        if (isSuccess) {
                            int audioLength = AudioRecordHelper.getAudioLength(path);
                            audioLength = Math.round((float) (audioLength / 1000));
                            record = new Record(path, audioLength);
                            TroubleAudioBean audioBean = TroubleAudioBean.getAudioBean(record);
                            audioBean.setId(audio_id);
                            audioBean.setTroubleid(troubleId);
                            audioBean.setUrl(url);
                            audioBean.setFilenote(fileNote);
                            audioBean.setStatus(TroublePictureBean.PHOTO_UPLOADED);
                            troubleDaoHelper.insertOrUpdateTroubleAudio(audioBean);

                            /*从服务器上下载成功之后，删除之前上传成功的本地缓存*/
                            //dbDaoHelper.deleteTroubleAudios(troubleId, TroubleBean.UPLOADED_STATE);
                        }

                        getAudioCallback.onGetAudioRecord(isSuccess, record);
                    }
                });
            }
        }
    }

    public interface GetFileCallback{
        void onGetTroubleFile(boolean isSuccess, TroubleAudioBean fileBean);
    }

    public void getTroubleFileFromServer(final Context context, final String troubleId, final String url, String fileName,
                                         final String fileNote, final GetFileCallback getFileCallback) {
        boolean bHasCache = false;
        TroubleAudioBean audioBean = getTroubleAudio(url);
        String filePath = null;
        if (audioBean != null) {
            filePath = audioBean.getPath();
            if (filePath != null && FileUtil.fileExists(filePath)) {
                bHasCache = true;
            }
        }
        if (bHasCache) {
            audioBean.setFilenote(fileNote);
            String filetype = MimeUtil.getMimeType(filePath);
            audioBean.setFiletype(filetype);
            audioBean.setStatus(TroublePictureBean.PHOTO_UPLOADED);
            getFileCallback.onGetTroubleFile(true, audioBean);
        } else {
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null) {
                if (troubleController == null)
                    troubleController = new TroubleController(context);
                String real_url = NetRequestURL.newApi_dyrq.getFormattedDownFile(url, fileName);
                final String audio_id = audioBean != null ? audioBean.getId() : UUID.randomUUID().toString();
                troubleController.getTroubleFile(context, real_url, fileName, null, new TroubleCallBack() {
                    @Override
                    public void onGetTroubleFile(boolean isSuccess, int errorCode, String errMsg, String path) {
                        super.onGetTroubleFile(isSuccess, errorCode, errMsg, path);
                        TroubleAudioBean audioBean = null;
                        if (isSuccess) {
                            double filesize = FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_KB);
                            Record record = new Record(path, (int) filesize);
                            TroubleAudioBean audioBean1 = TroubleAudioBean.getAudioBean(record);
                            audioBean1.setId(audio_id);
                            audioBean1.setTroubleid(troubleId);
                            audioBean1.setUrl(url);
                            audioBean1.setFilenote(fileNote);
                            String filetype = MimeUtil.getMimeType(path);
                            audioBean1.setFiletype(filetype);
                            audioBean1.setStatus(TroublePictureBean.PHOTO_UPLOADED);
                            troubleDaoHelper.insertOrUpdateTroubleAudio(audioBean1);

                            /*从服务器上下载成功之后，删除之前上传成功的本地缓存*/
                            //dbDaoHelper.deleteTroubleAudios(troubleId, TroubleBean.UPLOADED_STATE);
                            audioBean = audioBean1;
                        }

                        getFileCallback.onGetTroubleFile(isSuccess, audioBean);
                    }
                });
            }
        }
    }

    public void saveServerPhotos(List<UploadFileBean> fileBeans){
        for (UploadFileBean fileBean : fileBeans){
            TroublePictureBean savedPicture = troubleDaoHelper.queryTroublePictureByUrl(fileBean.getFilename());
            if (savedPicture == null){
                TroublePictureBean pictureBean = new TroublePictureBean();
                String pictureId  = fileBean.getId();
                pictureBean.setId(pictureId);
                pictureBean.setTroubleid(fileBean.getTableid());
                pictureBean.setFilenote(fileBean.getFilenote());
                pictureBean.setCreateTime(fileBean.getUpload_time());
                pictureBean.setFileurl(fileBean.getFilename());
                pictureBean.setStatus(TroubleBean.SERVER_STATE);
                troubleDaoHelper.insertOrUpdateTroublePicture(pictureBean);
            }
        }
    }

    public interface GetVideoCallback {
        void onGetVideoRecord(boolean isSuccess, TroublePictureBean pictureBean);
    }

    public String getVideoFileName(TroublePictureBean videoBean) {
        String url = videoBean.getFile();
        int index = url.indexOf("sign=");
        int endIndex = url.indexOf("&", index);
        String fileName = url.substring(index + 5, endIndex);
        return fileName;
    }

    public void getTroubleVideoFromServer(final Context context, final String troubleId, final String url, String fileName,
                                          final String fileNote, final GetVideoCallback getVideoCallback) {
        boolean bHasCache = false;
        TroublePictureBean localVideoBean = getTroublePictureByUrl(url);
        String filePath;
        if (localVideoBean != null) {
            filePath = localVideoBean.getFilepath();
            if (filePath != null && FileUtil.fileExists(filePath)) {
                bHasCache = true;
            }
        }
        if (bHasCache) {
            getVideoCallback.onGetVideoRecord(true, localVideoBean);
        } else {
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null) {
                if (troubleController == null)
                    troubleController = new TroubleController(context);
                String real_url = NetRequestURL.newApi_dyrq.getFormattedDownFile(url, fileName);
                final String video_id = localVideoBean != null ? localVideoBean.getId() : UUID.randomUUID().toString();
                troubleController.getTroubleFile(context, real_url, fileName, null, new TroubleCallBack() {
                    @Override
                    public void onGetTroubleFile(boolean isSuccess, int errorCode, String errMsg, String path) {
                        super.onGetTroubleFile(isSuccess, errorCode, errMsg, path);
                        TroublePictureBean pictureBean = null;
                        if (isSuccess) {
                            pictureBean = new TroublePictureBean();
                            pictureBean.setId(video_id);
                            pictureBean.setTroubleid(troubleId);
                            pictureBean.setFileurl(url);
                            pictureBean.setFilenote(fileNote);
                            pictureBean.setFile(fileName);
                            pictureBean.setFilepath(path);
                            String filetype = MimeUtil.getMimeType(path);
                            pictureBean.setFiletype(filetype);
                            pictureBean.setStatus(TroublePictureBean.PHOTO_UPLOADED);
                            troubleDaoHelper.insertOrUpdateTroublePicture(pictureBean);
                        }

                        getVideoCallback.onGetVideoRecord(isSuccess, pictureBean);
                    }
                });
            }
        }
    }

    public TroublePictureBean getTroublePicture(String pic_id) {
        return troubleDaoHelper.queryTroublePicture(pic_id);
    }

    public TroublePictureBean getTroublePictureByUrl(String url) {
        return troubleDaoHelper.queryTroublePictureByUrl(url);
    }

    public NotifyManageBean getNotifyMsgBean(String trouble_id) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            return notifyMsgDaoHelper.getTroubleNotifyMsgBean(userBean.getUserid(), trouble_id);
        }
        return null;
    }

    public List<NotifyManageBean> getUnNotifyMsgBean() {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            return notifyMsgDaoHelper.getTroubleUnNotifyMsgBean(userBean.getUserid());
        }
        return null;
    }

    public void setMsgBeanNotified(List<NotifyManageBean> msgBeans) {
        if (msgBeans != null) {
            for (NotifyManageBean msgBean : msgBeans) {
                msgBean.setIsNotify(true);
            }
            notifyMsgDaoHelper.upadteNotifyMsgBeans(msgBeans);
        }
    }

    public void setMsgBeanRead(NotifyManageBean msgBean) {
        if (msgBean != null) {
            msgBean.setIsRead(true);
            notifyMsgDaoHelper.upadteNotifyMsgBean(msgBean);
        }
    }

    /**
     * 获取服务器限制安装文件(.aa文件)最新信息
     */
    public void getRestrictFileInfo(Context context) {
        if (troubleController == null)
            troubleController = new TroubleController(context);
        troubleController.getRestrictFileInfo(context, new TroubleCallBack() {
            @Override
            public void onGetRestrictFileInfo(boolean isSuccess, int errorCode, String errMsg, RestrictFileBean fileInfo) {
                super.onGetRestrictFileInfo(isSuccess, errorCode, errMsg, fileInfo);
                if (isSuccess) {
                    getRestrictFile(context, fileInfo);
                } else {
                    String logMsg = String.format("获取服务器限制文件信息(pgwl.aa)失败! \n");
                    LogRecorder.writeDeviceToolLog(context, logMsg, BaseApp.getInstance().getUserId());
                }
            }
        });
    }

    private static final String RESTRICT_FILE_NAME = "pgwl.aa";
    public void getRestrictFile(Context context, RestrictFileBean fileInfo) {
        boolean bHasCache = false;
        TroubleAudioBean audioBean = getTroubleAudioByFileNote(RESTRICT_FILE_NAME);
        if (audioBean != null) {
            String filePath = audioBean.getPath();
            String server_time = fileInfo.getCreatTime();
            String local_time = audioBean.getCreateTime();
            if (filePath != null && FileUtil.fileExists(filePath)) {
                if (server_time.equals(local_time)) {
                    bHasCache = true;
                }
            }
        }
        if (bHasCache) {
        } else {
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null) {
                if (troubleController == null)
                    troubleController = new TroubleController(context);
                String url = fileInfo.getFilePath();
                String fileName = fileInfo.getFileName();
                String real_url = NetRequestURL.newApi_dyrq.getFormattedDownFile(url, fileName);
                final String audio_id = audioBean != null ? audioBean.getId() : UUID.randomUUID().toString();
                String dirPath = FileUtil.sdRootDir();
                troubleController.getTroubleFile(context, real_url, fileName, dirPath, new TroubleCallBack() {
                    @Override
                    public void onGetTroubleFile(boolean isSuccess, int errorCode, String errMsg, String path) {
                        super.onGetTroubleFile(isSuccess, errorCode, errMsg, path);
                        if (isSuccess) {
                            double filesize = FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_KB);
                            Record record = new Record(path, (int) filesize);
                            TroubleAudioBean audioBean1 = TroubleAudioBean.getAudioBean(record);
                            audioBean1.setId(audio_id);
                            audioBean1.setUrl(url);
                            audioBean1.setFilenote(RESTRICT_FILE_NAME);
                            audioBean1.setCreateTime(fileInfo.getCreatTime());
                            audioBean1.setStatus(TroublePictureBean.PHOTO_UPLOADED);
                            troubleDaoHelper.insertOrUpdateTroubleAudio(audioBean1);
                        }else {
                            String logMsg = String.format("从服务器下载最新的限制文件(pgwl.aa)失败! \n");
                            LogRecorder.writeDeviceToolLog(context, logMsg, userBean.getUserid());
                        }
                    }
                });
            }
        }
    }
}
