package com.tofly.ghrq_route.module.buildManage;

import android.content.Context;
import android.location.Location;

import com.esri.arcgisruntime.geometry.Point;
import com.gaoyuan.weixinrecord.example.Record;
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.module.OfflineWork.domain.OfflineWorkJobBean;
import com.tofly.ghrq_route.module.OfflineWork.domain.OfflineWorkJobBean.OfflineWorkJobType;
import com.tofly.ghrq_route.module.buildManage.controller.BuildManageCallback;
import com.tofly.ghrq_route.module.buildManage.controller.BuildManageController;
import com.tofly.ghrq_route.module.buildManage.domain.BuildFileBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildHandleDataBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildLogBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManagerBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildProcessManageBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildProjectTypeBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildReportBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildSignDataBean;
import com.tofly.ghrq_route.module.gps.GpsTool;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.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.FileUtil;

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

public class BuildTool {

    private static BuildTool buildTool = null;

    private BuildManageController buildManageController;

    private UploadFileController uploadFileController;

    private DBDaoHelper dbDaoHelper;

    private BuildTool() {
        dbDaoHelper = DBDaoHelper.getInstance();
    }

    public static synchronized BuildTool getInstance() {
        if (buildTool == null) {
            buildTool = new BuildTool();
        }
        return buildTool;
    }

    /**
     * 获取工地负责人列表
     */
    public void getManagerList(final Context context, final BuildManageCallback buildManageCallback) {
        if (buildManageController == null)
            buildManageController = new BuildManageController(context);
        buildManageController.getManagerList(new BuildManageCallback() {
            @Override
            public void onGetManagerList(boolean isSuccess, int errorCode, String errMsg, List<BuildManagerBean> data) {
                super.onGetManagerList(isSuccess, errorCode, errMsg, data);
                if (isSuccess) {

                } else {
                    errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                    String strWarn = context.getResources().getString(R.string.build_project_get_err) + errMsg;
                    ToastUtil.showToast(context, strWarn);
                }
                if (buildManageCallback != null)
                    buildManageCallback.onGetManagerList(isSuccess, errorCode, errMsg, data);
            }
        });
    }

    /**
     * 获取工地类型列表
     */
    public void getBuildProjectTypeList(final Context context, final BuildManageCallback buildManageCallback) {
        UserBean user = BaseApp.getInstance().getLoginUser();
        if (user != null) {
            if (buildManageController == null)
                buildManageController = new BuildManageController(context);
            buildManageController.getBuildProjectTypeList(user.getToken(), 1, C.DEFAULT_MAX_LOAD_PAGESIZE, new BuildManageCallback() {
                @Override
                public void onGetBuildProjectTypeList(boolean isSuccess, int errorCode, String errMsg, List<BuildProjectTypeBean> buildProjectTypeList, int total) {
                    super.onGetBuildProjectTypeList(isSuccess, errorCode, errMsg, buildProjectTypeList, total);
                    if (isSuccess) {
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getResources().getString(R.string.build_project_get_err) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }
                    if (buildManageCallback != null)
                        buildManageCallback.onGetBuildProjectTypeList(isSuccess, errorCode, errMsg, buildProjectTypeList, total);
                }
            });
        }
    }

    public void getServerBuildManages(Context context, String constructionState, final BuildManageCallback buildManageCallback) {
        getBuildManageList(context, constructionState, true, buildManageCallback);
    }

    public void getLocalBuildManages(Context context, String strBuildType, final BuildManageCallback buildManageCallback) {
        getBuildManageList(context, strBuildType, false, buildManageCallback);
    }

    /**
     * 获取工地列表
     */
    public void getBuildManageList(final Context context, String constructionState, boolean online, final BuildManageCallback buildManageCallback) {
        UserBean user = BaseApp.getInstance().getLoginUser();
        if (user != null) {
            if (buildManageController == null)
                buildManageController = new BuildManageController(context);
            buildManageController.getBuildManageList(constructionState, online, 1, C.DEFAULT_MAX_LOAD_PAGESIZE, new BuildManageCallback() {
                @Override
                public void onGetBuildManageList(boolean isSuccess, int errorCode, String errMsg, List<BuildManageBean> buildManageList, int total) {
                    super.onGetBuildManageList(isSuccess, errorCode, errMsg, buildManageList, total);
                    if (isSuccess) {
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }
                    if (buildManageCallback != null)
                        buildManageCallback.onGetBuildManageList(isSuccess, errorCode, errMsg, buildManageList, total);
                }
            });
        }
    }

    public List<BuildManageBean> getLocalBuildManageList() {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        return dbDaoHelper.getBuildManages(userBean.getUserid());
    }

    /**
     * 新增工地保存
     */
    private void saveBuildManageInfo(BuildManageBean buildManage, List<TroublePictureBean> pictures, List<TroubleAudioBean> audios, List<BuildFileBean> fileBeanList) {
        if (buildManage != null) {
            OfflineWorkJobBean workJobBean1 = dbDaoHelper.getOfflineWorkJob(buildManage.getId());
            if (workJobBean1 == null) {
                int save_state = BuildManageBean.BUILD_SUBMIT_ONE;
                OfflineWorkJobBean workJobBean = new OfflineWorkJobBean();
                String job_id = UUID.randomUUID().toString();
                workJobBean.setId(job_id);
                workJobBean.setJob_type(OfflineWorkJobType.JOB_BUILD_MANAGE_ADD);
                UserBean userBean = BaseApp.getInstance().getLoginUser();
                workJobBean.setUser_id(userBean.getUserid());

                /*保存工地的数据信息*/
                buildManage.setSubmit_state("" + save_state);
                dbDaoHelper.insertOrUpdateBuildManage(buildManage);

                workJobBean.setRef_id(buildManage.getId());

                /*保存工地的图片*/
                if (pictures != null && pictures.size() > 0) {
                    List<String> pic_ids = new ArrayList<>();
                    for (TroublePictureBean pictureBean : pictures) {
                        if (pictureBean != null && FileUtil.fileExists(pictureBean.getFilepath())) {
                            String id = UUID.randomUUID().toString();
                            pictureBean.setId(id);
                            pictureBean.setTroubleid(buildManage.getId());
                            pictureBean.setStatus(save_state);
                            dbDaoHelper.insertOrUpdateTroublePicture(pictureBean);

                            pic_ids.add(id);
                        }
                    }
                    workJobBean.setRef_photo_ids(pic_ids);
                }

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

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

                /*保存工地的附件*/
                if (fileBeanList != null && fileBeanList.size() > 0) {
                    List<String> file_id = new ArrayList<>();
                    for (BuildFileBean fileBean : fileBeanList) {
                        if (fileBean != null && FileUtil.fileExists(fileBean.getFilePath())) {
                            fileBean.setBuilId(buildManage.getId());
                            fileBean.setStatus(save_state);
                            dbDaoHelper.insertOrUpdateBuildFiles(fileBean);
                            file_id.add(fileBean.getId());
                        }
                    }
                    workJobBean.setRef_data_ids(file_id);
                }
                dbDaoHelper.insertOfflineWorkJob(workJobBean);
            }
        }
    }

    /**
     * 保存过程管理
     */
    private void saveBuildProcessInfo(BuildProcessManageBean buildManage, List<TroublePictureBean> pictures, List<TroubleAudioBean> audios, List<BuildFileBean> fileBeanList) {
        if (buildManage != null) {
            OfflineWorkJobBean workJobBean1 = dbDaoHelper.getOfflineWorkJob(buildManage.getId());
            if (workJobBean1 == null) {
                int save_state = BuildManageBean.BUILD_SUBMIT_ONE;
                OfflineWorkJobBean workJobBean = new OfflineWorkJobBean();
                String job_id = UUID.randomUUID().toString();
                workJobBean.setId(job_id);
                workJobBean.setJob_type(OfflineWorkJobType.JOB_BUILD_MANAGE_PROCESS);
                UserBean userBean = BaseApp.getInstance().getLoginUser();
                workJobBean.setUser_id(userBean.getUserid());

                /*保存工地的数据信息*/
                buildManage.setSubmit_state("" + save_state);
                dbDaoHelper.insertOrUpdateProcessManage(buildManage);

                workJobBean.setRef_id(buildManage.getId());

                /*保存工地的图片*/
                if (pictures != null && pictures.size() > 0) {
                    List<String> pic_ids = new ArrayList<>();
                    for (TroublePictureBean pictureBean : pictures) {
                        if (pictureBean != null && FileUtil.fileExists(pictureBean.getFilepath())) {
                            pictureBean.setTroubleid(buildManage.getWorkOrderId());
                            pictureBean.setStatus(save_state);
                            dbDaoHelper.insertOrUpdateTroublePicture(pictureBean);

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

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

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

                /*保存工地的附件*/
                if (fileBeanList != null && fileBeanList.size() > 0) {
                    List<String> file_id = new ArrayList<>();
                    for (BuildFileBean fileBean : fileBeanList) {
                        if (fileBean != null && FileUtil.fileExists(fileBean.getFilePath())) {
                            fileBean.setBuildProcessId(buildManage.getWorkOrderId());
                            fileBean.setStatus(save_state);
                            dbDaoHelper.insertOrUpdateBuildFiles(fileBean);
                            file_id.add(fileBean.getId());
                        }
                    }
                    workJobBean.setRef_data_ids(file_id);
                }
                dbDaoHelper.insertOfflineWorkJob(workJobBean);
            }
        }
    }

    /**
     * 新工地发现上传
     */
    public void addBuildManage(final Context context, final BuildManageBean buildManage, final List<TroublePictureBean> photos,
                               final List<TroubleAudioBean> audios, final List<BuildFileBean> fileBeanList, final boolean saveOnFail, final BuildManageCallback buildManageCallback) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && buildManage != null) {
            // saveBuildManageInfo(buildManage, TroubleBean.SAVE_UPLOADING_STATE);
            if (buildManageController == null)
                buildManageController = new BuildManageController(context);
            buildManageController.addBuildManage(userBean.getToken(), buildManage, photos, audios, fileBeanList, new BuildManageCallback() {
                @Override
                public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddBuildManage(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                        deleteLocalBuildManage(buildManage, photos, audios, fileBeanList);
                    } else {
                        if (saveOnFail) {
                            saveBuildManageInfo(buildManage, photos, audios, fileBeanList);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getResources().getString(R.string.build_found_upload_info_err) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }
                    if (buildManageCallback != null)
                        buildManageCallback.onAddBuildManage(isSuccess, errorCode, errMsg);
                }
            });
        }
    }

    /**
     * 过程管理
     */
    public void addBuildManageProcess(final Context context, final BuildProcessManageBean buildManage, final List<TroublePictureBean> photos,
                                      final List<TroubleAudioBean> audios, final List<BuildFileBean> fileBeanList, final boolean saveOnFail, final BuildManageCallback buildManageCallback) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && buildManage != null) {
            saveBuildProcessManageInfo(buildManage);
            if (buildManageController == null)
                buildManageController = new BuildManageController(context);
            buildManageController.addBuildProcessManage(buildManage, photos, audios, fileBeanList, new BuildManageCallback() {
                @Override
                public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddBuildManage(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                        deleteLocalBuildProcess(buildManage, photos, audios, fileBeanList);
                    } else {
                        if (saveOnFail) {
                            buildManage.setSubmit_state("" + BuildManageBean.BUILD_SUBMIT_ONE);
                            saveBuildProcessInfo(buildManage, photos, audios, fileBeanList);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getResources().getString(R.string.build_found_upload_info_err) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }
                    if (buildManageCallback != null)
                        buildManageCallback.onAddBuildManage(isSuccess, errorCode, errMsg);
                }
            });
        }
    }

    public void addBuildManage(Context context, BuildManageBean buildManage, List<TroublePictureBean> photos,
                               List<Record> records, List<BuildFileBean> filesList, BuildManageCallback buildManageCallback) {
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(records);
        if (filesList != null && filesList.size() > 0) {
            dbDaoHelper.saveBuildFiles(filesList, "0", buildManage.getId());
        }
        addBuildManage(context, buildManage, photos, audioBeans, filesList, true, buildManageCallback);
    }

    public void addBuildProcessManage(Context context, BuildProcessManageBean data, List<TroublePictureBean> photos,
                                      List<Record> records, List<BuildFileBean> fileBeanList, BuildManageCallback buildManageCallback) {
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(records);
        if (fileBeanList != null && fileBeanList.size() > 0) {
            dbDaoHelper.saveBuildFiles(fileBeanList, "1", data.getId());
        }
        addBuildManageProcess(context, data, photos, audioBeans, fileBeanList, true, buildManageCallback);
    }

    public void addBuildManageNoSave(Context context, BuildManageBean buildManage, List<TroublePictureBean> photos,
                                     List<TroubleAudioBean> audioBeans, BuildManageCallback buildManageCallback) {
        //待修改
        //  addBuildManage(context, buildManage, photos, audioBeans, false, buildManageCallback);
    }

    private void saveBuildManageInfo(BuildManageBean buildManage, int state) {
        if (buildManage != null) {
            buildManage.setSubmit_state("" + BuildManageBean.BUILD_SUBMIT_ZERO);
            dbDaoHelper.insertOrUpdateBuildManage(buildManage);
        }
    }

    private void saveBuildProcessManageInfo(BuildProcessManageBean buildManage) {
        if (buildManage != null) {
            buildManage.setSubmit_state("" + BuildManageBean.BUILD_SUBMIT_ZERO);
            dbDaoHelper.insertOrUpdateProcessManage(buildManage);
        }
    }

//    public void saveBuildManageState(BuildManageBean buildManage, int build_state) {
//        if (buildManage != null) {
//            buildManage.setBuild_state(build_state);
//            dbDaoHelper.insertOrUpdateBuildManage(buildManage);
//        }
//    }
//
//    private void saveBuildManageOpen(BuildManageBean buildManage, int open_state) {
//        if (buildManage != null) {
//            buildManage.setIsopen(open_state);
//            dbDaoHelper.insertOrUpdateBuildManage(buildManage);
//        }
//    }

    public void deleteLocalBuildManage(BuildManageBean buildManage) {
        if (buildManage != null) {
            dbDaoHelper.deleteBuildManage(buildManage);
        }
    }

    /**
     * 删除本地工地保存数据
     */
    public void deleteLocalBuildManage(BuildManageBean buildManage, List<TroublePictureBean> pictures, List<TroubleAudioBean> audios, List<BuildFileBean> fileBeanList) {
        dbDaoHelper.deleteBuildManage(buildManage);

        if (pictures != null && pictures.size() > 0) {
            dbDaoHelper.deleteSavedTroublePictures(pictures);
            for (TroublePictureBean pictureBean : pictures) {
                String file = pictureBean.getFilepath();
                FileUtil.deleteFile(file);
            }
        }
        if (audios != null && audios.size() > 0) {
            dbDaoHelper.deleteSavedTroubleAudios(audios);
            for (TroubleAudioBean audioBean : audios) {
                String file = audioBean.getPath();
                FileUtil.deleteFile(file);
            }
        }
        if (fileBeanList != null && fileBeanList.size() > 0) {
            dbDaoHelper.deleteBuildFiles(fileBeanList);
        }

        OfflineWorkJobBean workJobBean = dbDaoHelper.getOfflineWorkJob(buildManage.getId());
        if (workJobBean != null) {
            dbDaoHelper.deleteOfflineWorkJob(workJobBean);
        }
    }

    /**
     * 删除本地工地保存数据
     */
    public void deleteLocalBuildProcess(BuildProcessManageBean buildManage, List<TroublePictureBean> pictures, List<TroubleAudioBean> audios, List<BuildFileBean> fileBeanList) {
        dbDaoHelper.deleteBuildProcess(buildManage);

        if (pictures != null && pictures.size() > 0) {
            dbDaoHelper.deleteSavedTroublePictures(pictures);
            for (TroublePictureBean pictureBean : pictures) {
                String file = pictureBean.getFilepath();
                FileUtil.deleteFile(file);
            }
        }
        if (audios != null && audios.size() > 0) {
            dbDaoHelper.deleteSavedTroubleAudios(audios);
            for (TroubleAudioBean audioBean : audios) {
                String file = audioBean.getPath();
                FileUtil.deleteFile(file);
            }
        }
        if (fileBeanList != null && fileBeanList.size() > 0) {
            dbDaoHelper.deleteBuildFiles(fileBeanList);
        }

        OfflineWorkJobBean workJobBean = dbDaoHelper.getOfflineWorkJob(buildManage.getId());
        if (workJobBean != null) {
            dbDaoHelper.deleteOfflineWorkJob(workJobBean);
        }
    }


    /**
     * 保存工地监护记录
     */
    private void saveBuildLogInfo(BuildLogBean buildLogBean, BuildManageBean buildManage) {
        if (buildLogBean != null) {
            int save_state = TroubleBean.SAVED_STATE;
            /*保存工地的数据信息*/
            buildLogBean.setState(save_state);
            dbDaoHelper.insertOrUpdateBuildLog(buildLogBean);

            String build_id = buildLogBean.getBuild_id();
            if (buildManage != null) {
                int open_state = buildLogBean.getOpen_state();
                if (open_state == BuildLogBean.BUILD_LOG_OPEN_STATE) {
                    BuildHandleDataBean buildHandleBean = new BuildHandleDataBean();
                    buildHandleBean.setBuild_id(build_id);
                    buildHandleBean.setBuild_start_date(buildLogBean.getTime());
                    buildHandleBean.setLng(buildManage.getX());
                    buildHandleBean.setLat(buildManage.getY());
                    dbDaoHelper.insertBuildHandle(buildHandleBean);
                } else if (open_state == BuildLogBean.BUILD_LOG_OPEN_STATE) {
                    dbDaoHelper.deleteBuildHandle(build_id);
                }
            }

            /*保存新的离线工作计划*/
            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(OfflineWorkJobType.JOB_BUILD_LOG_ADD);
            workJobBean.setRef_id(buildLogBean.getId());
            dbDaoHelper.insertOfflineWorkJob(workJobBean);
        }
    }

    /**
     * 更新工地监护状态
     */
    private void updateBuildLogState(final Context context, final BuildLogBean buildLog, final BuildManageBean buildManage, final boolean saveOnFail, final BuildManageCallback buildManageCallback) {
        // UserBean user = BaseApp.getInstance().getLoginUser();
        if (buildLog != null) {
            //   saveBuildLogInfo(buildLog, TroubleBean.SAVE_UPLOADING_STATE);
            if (buildManageController == null)
                buildManageController = new BuildManageController(context);
            buildManageController.updateBuildLog(buildManage, new BuildManageCallback() {
                @Override
                public void onUpdateBuildLog(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUpdateBuildLog(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                        //  deleteLocalBuildLog(buildLog);
                        // saveBuildManageOpen(buildManage, buildLog.getOpen_state());
                    } else {
//                        if (saveOnFail) {
//                            saveBuildLogInfo(buildLog, buildManage);
//                            saveBuildManageOpen(buildManage, buildLog.getOpen_state());
//                        } else {
//                            saveBuildLogInfo(buildLog, TroubleBean.SAVED_STATE);
//                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }
                    if (saveOnFail) {
                        checkTodayBuildLogPlan(context);
                    }
                    if (buildManageCallback != null)
                        buildManageCallback.onUpdateBuildLog(isSuccess, errorCode, errMsg);
                }
            });
        }
    }

    public void updateBuildLogState(Context context, BuildManageBean buildManage, BuildManageCallback buildManageCallback) {
        BuildLogBean buildLogBean = new BuildLogBean();
//        buildLogBean.setId(UUID.randomUUID().toString());
//        buildLogBean.setBuild_id(buildManage.getId());
//        buildLogBean.setOpen_state(2);
//        buildLogBean.setTime(DateUtils.getDate());
        updateBuildLogState(context, buildLogBean, buildManage, true, buildManageCallback);
    }

    public void updateBuildLogStateNoSave(Context context, BuildLogBean buildLogBean, BuildManageCallback buildManageCallback) {
        BuildManageBean buildManage = null;
        if (buildLogBean != null)
            buildManage = dbDaoHelper.getBuildManage(buildLogBean.getBuild_id());
        updateBuildLogState(context, buildLogBean, buildManage, false, buildManageCallback);
    }

    private void saveBuildLogInfo(BuildLogBean buildLogBean, int state) {
        if (buildLogBean != null) {
            buildLogBean.setState(state);
            dbDaoHelper.insertOrUpdateBuildLog(buildLogBean);
        }
    }

    /**
     * 删除本地工地监护保存数据
     */
    public void deleteLocalBuildLog(BuildLogBean buildLogBean) {
        dbDaoHelper.deleteBuildLog(buildLogBean);

        OfflineWorkJobBean workJobBean = dbDaoHelper.getOfflineWorkJob(buildLogBean.getId());
        if (workJobBean != null) {
            dbDaoHelper.deleteOfflineWorkJob(workJobBean);
        }
    }

    public void checkTodayBuildLogPlan(Context context) {
        BuildSignDataBean buildSignData = new BuildSignDataBean();
        String todayDate = DateUtils.getYMD();
        buildSignData.setPlanDate(todayDate);
        dbDaoHelper.insertOrUpdateBuildSignData(buildSignData);
        checkTodayHasBuildLogPlan(context);
    }

    public boolean checkTodayHasBuildLogPlan(Context context) {
        final BuildSignDataBean buildSignData = dbDaoHelper.getTodayBuildSignData();
        boolean hasBuildSignPlan;
        if (buildSignData == null || buildSignData.getPlanState() == 0) {
            hasBuildSignPlan = false;
            getBuildLogList(context);
        } else {
            hasBuildSignPlan = buildSignData.getHasPlan() == 1;
        }
        return hasBuildSignPlan;
    }

    public void getBuildLogList(Context context) {
        if (C.is_passed_notify)
            return;

        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            if (buildManageController == null)
                buildManageController = new BuildManageController(context);
            buildManageController.getBuildLogList(userBean.getToken(), new BuildManageCallback() {
                @Override
                public void onGetBuildLogList(boolean isSuccess, int errorCode, String errMsg, List<BuildHandleDataBean> buildLogList) {
                    super.onGetBuildLogList(isSuccess, errorCode, errMsg, buildLogList);
                    if (isSuccess) {
                    } else {
                        buildLogList = getLocalBuildLogs();
                    }
                    if (buildLogList != null) {
                        boolean hasPlan = buildLogList.size() > 0;
                        setBuildSignPlanData(hasPlan);
                    }
                }
            });
        }
    }

    public List<BuildHandleDataBean> getLocalBuildLogs() {
        return dbDaoHelper.getBuildHandleList();
    }

    private void setBuildSignPlanData(boolean hasPlan) {
        BuildSignDataBean buildSign = dbDaoHelper.getTodayBuildSignData();
        if (buildSign == null) {
            buildSign = new BuildSignDataBean();
            String todayDate = DateUtils.getYMD();
            buildSign.setPlanDate(todayDate);
            buildSign.setPlanState(1);
            buildSign.setHasPlan(hasPlan ? 1 : 0);
            dbDaoHelper.insertOrUpdateBuildSignData(buildSign);
        } else {
            dbDaoHelper.updateBuildSignHasPlan(hasPlan);
        }
    }

//    /**
//     * 更新工地停留时间
//     */
//    public void updateBuildLogTime(BuildManageBean buildManage, BuildHandleDataBean build_log) {
//        if (buildManage != null) {
//            String begin_date = build_log.getBuild_start_date();
//            String end_date = DateUtils.getDate();
//            long offset = DateUtils.getTimeOffset(begin_date, end_date);
//            String log_time = TimeUtil.secondToString(offset / 1000);
//            buildManage.setLog_time(log_time);
//        }
//    }
//
//    public boolean checkBuildInPlace(Point point, BuildManageBean buildManage) {
//        boolean isover = false;
//        if (point != null && point.getX() > 0 && point.getY() > 0) {
//            double BUILD_SCALE = BaseApp.getInstance().getBuildCheckRadius();
//            double lng = point.getX();
//            double lat = point.getY();
//            if (buildManage != null && buildManage.getIsopen() == 0) {
//                double x = buildManage.getX();
//                double y = buildManage.getY();
//                if (buildManage.getX() > 0 && buildManage.getY() > 0) {
//                    isover = GpsTool.checkIsPointOver(x, y, lng, lat, BUILD_SCALE);
//                }
//            }
//        }
//        return isover;
//    }

    public Point getLastLocation() {
        Point point = null;
        boolean isRunning = GpsTool.getInstance().isLocationServiceRunning();
        if (isRunning) {
            Location lastLoc = GpsTool.getInstance().getLocationInfo();
            if (lastLoc != null && lastLoc.getLongitude() > 0 && lastLoc.getLatitude() > 0) {
                double lng = lastLoc.getLongitude();
                double lat = lastLoc.getLatitude();
                point = new Point(lng, lat);
            }
        }
        return point;
    }

    public BuildHandleDataBean getBuildLog(String build_id) {
        return dbDaoHelper.getBuildHandle(build_id);
    }

    public interface GetBuildNotice {
        void buildHasNoticeFile(boolean isSuccess, boolean hasNoticeFile, List<TroublePictureBean> photos, List<TroubleAudioBean> audios);
    }

    /**
     * 获取工地告知书文件
     */
    public void getBuildNoticeFiles(final Context context, BuildManageBean buildManage, final GetBuildNotice getBuildNotice) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && buildManage != null) {
            if (uploadFileController == null)
                uploadFileController = new UploadFileController(context);
            final String build_id = buildManage.getId();
            uploadFileController.getUploadFileList(userBean.getToken(), build_id,
                    UploadFileBean.FILE_TABLE_BUILD_MANAGE, 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<TroublePictureBean> photos = new ArrayList<>();
                            List<TroubleAudioBean> audios = new ArrayList<>();
                            if (isSuccess) {
                                if (fileList != null && fileList.size() > 0) {
                                    for (UploadFileBean fileBean : fileList) {
                                        if (fileBean != null && fileBean.getFilenote() != null) {
                                            //String fileNote = fileBean.getFilenote();
                                            String audioLength = fileBean.getAudiolength();
                                            if (audioLength.equalsIgnoreCase("0")) {
                                                TroublePictureBean pictureBean = new TroublePictureBean();
                                                pictureBean.setId(fileBean.getId());
                                                pictureBean.setTroubleid(build_id);
                                                pictureBean.setFilenote(UploadFileBean.FILE_NOTE_BUILD_NOTICE_PHOTO);
                                                pictureBean.setFile(fileBean.getFilename());
                                                pictureBean.setCreateTime(fileBean.getUpload_time());
                                                pictureBean.setStatus(TroublePictureBean.PHOTO_UPLOADED);
                                                photos.add(pictureBean);
                                                dbDaoHelper.insertTroublePicture(pictureBean);
                                            } else {
                                                TroubleAudioBean audioBean = new TroubleAudioBean();
                                                audioBean.setId(fileBean.getId());
                                                audioBean.setTroubleid(build_id);
                                                audioBean.setCreateTime(fileBean.getUpload_time());
                                                audioBean.setFilenote(UploadFileBean.FILE_NOTE_BUILD_NOTICE_AUDIO);
                                                audioBean.setUrl(fileBean.getFilename());
                                                audioBean.setSecond(Integer.parseInt(fileBean.getAudiolength()));
                                                audioBean.setStatus(TroublePictureBean.PHOTO_UPLOADED);
                                                audios.add(audioBean);
                                                dbDaoHelper.insertTroubleAudio(audioBean);
                                            }
                                        }
                                    }
                                }
                            } else {
                                errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                                ToastUtil.showToast(context, errMsg);
                            }
                            List<TroublePictureBean> localPhotos = getLocalBuildPhotos(build_id, TroublePictureBean.PHOTO_LOCAL_STATE);
                            if (localPhotos != null) {
                                for (TroublePictureBean localPhoto : localPhotos) {
                                    TroublePictureBean server_photo = findServerBuildPhoto(photos, localPhoto.getId());
                                    if (server_photo != null) {
                                        server_photo.setFilepath(localPhoto.getFilepath());
                                    } else {
                                        photos.add(0, localPhoto);
                                    }
                                }
                            }
                            List<TroubleAudioBean> localAudios = getLocalBuildAudios(build_id, TroublePictureBean.PHOTO_LOCAL_STATE);
                            if (localAudios != null)
                                audios.addAll(0, localAudios);
                            boolean hasNotice = photos.size() > 0;
                            if (getBuildNotice != null)
                                getBuildNotice.buildHasNoticeFile(isSuccess, hasNotice, photos, audios);
                        }
                    });
        }
    }

    private TroublePictureBean findServerBuildPhoto(List<TroublePictureBean> serverPhotos, String photo_id) {
        TroublePictureBean serverPhoto = null;
        if (serverPhotos != null) {
            for (TroublePictureBean pictureBean : serverPhotos) {
                if (pictureBean.getId().equals(photo_id)) {
                    serverPhoto = pictureBean;
                    break;
                }
            }
        }
        return serverPhoto;
    }

    /**
     * 增加告知书图片
     */
    public void addBuildNoticePhoto(final Context context, final String build_id, final TroublePictureBean picture, final boolean saveOnFail, final UploadFileCallBack fileCallback) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && build_id != null) {
            picture.setTroubleid(build_id);
            picture.setFilenote(UploadFileBean.FILE_NOTE_BUILD_NOTICE_PHOTO);
            saveBuildNoticePhoto(picture, TroublePictureBean.PHOTO_UPLOADING);
            if (uploadFileController == null)
                uploadFileController = new UploadFileController(context);
            final String photoPath = picture.getFilepath();
            String create_time = picture.getCreateTime();
            uploadFileController.addUploadNoticePhoto(userBean.getToken(), build_id, photoPath, UploadFileBean.FILE_NOTE_BUILD_NOTICE_PHOTO, create_time, new UploadFileCallBack() {
                @Override
                public void onAddUploadFile(boolean isSuccess, int errorCode, String errMsg, UploadFileBean fileBean) {
                    super.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                    if (isSuccess) {
                        deleteLocalBuildPhoto(picture);
                        deleteBuildNoticePhotoOfflineWork(picture);
                        if (fileBean != null) {
                            picture.setId(fileBean.getId());
                            if (photoPath != null && !photoPath.isEmpty()) {
                                picture.setFilepath(photoPath);
                            }
                            String url = fileBean.getFilename();
                            if (url != null && !url.isEmpty()) {
                                picture.setFile(url);
                            }
                        }
                        saveBuildNoticePhoto(picture, TroublePictureBean.PHOTO_UPLOADED);
                    } else {
                        if (saveOnFail) {
                            addBuildNoticePhotoOfflineWork(build_id, picture);
                        }
                        saveBuildNoticePhoto(picture, TroublePictureBean.PHOTO_LOCAL_STATE);
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }
                    if (fileCallback != null)
                        fileCallback.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                }
            });
        }
    }

    public void addBuildNoticePhoto(final Context context, final String build_id, final TroublePictureBean picture, final UploadFileCallBack fileCallback) {
        addBuildNoticePhoto(context, build_id, picture, true, fileCallback);
    }

    public void addBuildNoticePhotoNoSave(final Context context, final String build_id, final TroublePictureBean picture, final UploadFileCallBack fileCallback) {
        addBuildNoticePhoto(context, build_id, picture, false, fileCallback);
    }

    private void addBuildNoticePhotoOfflineWork(String build_id, TroublePictureBean picture) {
        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(OfflineWorkJobType.JOB_BUILD_NOTICE_PHOTO_ADD);
        workJobBean.setRef_id(picture.getId());
        workJobBean.setRef_data_id(build_id);
        dbDaoHelper.insertOfflineWorkJob(workJobBean);
    }

    private void deleteBuildNoticePhotoOfflineWork(TroublePictureBean picture) {
        OfflineWorkJobBean workJobBean = dbDaoHelper.getOfflineWorkJob(picture.getId());
        if (workJobBean != null)
            dbDaoHelper.deleteOfflineWorkJob(workJobBean);
    }

    /**
     * 增加告知书音频
     */
    public void addBuildNoticeAudio(final Context context, final String build_id, final TroubleAudioBean audioBean, final boolean saveOnFail, final UploadFileCallBack fileCallback) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && build_id != null) {
            audioBean.setTroubleid(build_id);
            audioBean.setFilenote(UploadFileBean.FILE_NOTE_BUILD_NOTICE_AUDIO);
            saveBuildNoticeAudio(audioBean, TroublePictureBean.PHOTO_UPLOADING);
            if (uploadFileController == null)
                uploadFileController = new UploadFileController(context);
            final String photoPath = audioBean.getPath();
            final String checkTime = audioBean.getCreateTime();
            final int audiolength = audioBean.getSecond();
            UserBean user = BaseApp.getInstance().getLoginUser();
            uploadFileController.addUploadNoticeAudio(user.getToken(), build_id, photoPath, UploadFileBean.FILE_NOTE_BUILD_NOTICE_PHOTO, audiolength, checkTime, new UploadFileCallBack() {
                @Override
                public void onAddUploadFile(boolean isSuccess, int errorCode, String errMsg, UploadFileBean fileBean) {
                    super.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                    if (isSuccess) {
                        deleteLocalBuildAudio(audioBean);
                        deleteBuildNoticeAudioOfflineWork(audioBean);
                        if (fileBean != null) {
                            String filepath = fileBean.getFilename();
                            if (filepath != null && !filepath.isEmpty()) {
                                String url = filepath;
                                audioBean.setUrl(url);
                                String audioId = fileBean.getId();
                                if (audioId != null && !audioId.isEmpty()) {
                                    audioBean.setId(audioId);
                                }
                            }
                        }
                        saveBuildNoticeAudio(audioBean, TroublePictureBean.PHOTO_UPLOADED);
                    } else {
                        if (saveOnFail) {
                            addBuildNoticeAudioOfflineWork(build_id, audioBean);
                        }
                        saveBuildNoticeAudio(audioBean, TroublePictureBean.PHOTO_LOCAL_STATE);

                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }
                    if (fileCallback != null)
                        fileCallback.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                }
            });
        }
    }

    public void addBuildNoticeAudio(final Context context, String build_id, final TroubleAudioBean audioBean, final UploadFileCallBack fileCallback) {
        addBuildNoticeAudio(context, build_id, audioBean, true, fileCallback);
    }

    public void addBuildNoticeAudioNoSave(final Context context, String build_id, final TroubleAudioBean audioBean, final UploadFileCallBack fileCallback) {
        addBuildNoticeAudio(context, build_id, audioBean, false, fileCallback);
    }

    private void addBuildNoticeAudioOfflineWork(String build_id, TroubleAudioBean audioBean) {
        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(OfflineWorkJobType.JOB_BUILD_NOTICE_AUDIO_ADD);
        workJobBean.setRef_id(audioBean.getId());
        workJobBean.setRef_data_id(build_id);
        dbDaoHelper.insertOfflineWorkJob(workJobBean);
    }

    private void deleteBuildNoticeAudioOfflineWork(TroubleAudioBean audioBean) {
        OfflineWorkJobBean workJobBean = dbDaoHelper.getOfflineWorkJob(audioBean.getId());
        if (workJobBean != null)
            dbDaoHelper.deleteOfflineWorkJob(workJobBean);
    }

    /**
     * 删除已上传的告知书图片
     */
    public void removeBuildNoticePhoto(final Context context, final TroublePictureBean pictureBean, final UploadFileCallBack fileCallBack) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && pictureBean != null) {
            if (uploadFileController == null)
                uploadFileController = new UploadFileController(context);
            final String file_id = pictureBean.getId();
            uploadFileController.removeUploadFile(userBean.getToken(), file_id, new UploadFileCallBack() {
                @Override
                public void onRemoveUploadFile(boolean isSuccess, int errorCode, String errMsg) {
                    super.onRemoveUploadFile(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                        dbDaoHelper.deleteSavedTroublePicture(pictureBean);
                        FileUtil.deleteFile(pictureBean.getFilepath());
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }
                    if (fileCallBack != null)
                        fileCallBack.onRemoveUploadFile(isSuccess, errorCode, errMsg);
                }
            });
        }
    }

    private void saveBuildNoticePhoto(final TroublePictureBean pictureBean, int photo_state) {
        if (pictureBean != null) {
            pictureBean.setStatus(photo_state);
            dbDaoHelper.insertOrUpdateTroublePicture(pictureBean);
        }
    }

    public void deleteLocalBuildPhoto(TroublePictureBean pictureBean) {
        if (pictureBean != null) {
            dbDaoHelper.deleteSavedTroublePicture(pictureBean);
            //FileUtil.deleteFile(pictureBean.getFilepath());
        }
    }

    public void addLocalBuildAudio(TroubleAudioBean audioBean) {
        dbDaoHelper.insertOrUpdateTroubleAudio(audioBean);
    }

    private void saveBuildNoticeAudio(final TroubleAudioBean audioBean, int audio_state) {
        if (audioBean != null) {
            audioBean.setStatus(audio_state);
            dbDaoHelper.insertOrUpdateTroubleAudio(audioBean);
        }
    }

    public void deleteLocalBuildAudio(TroubleAudioBean audioBean) {
        if (audioBean != null) {
            dbDaoHelper.deleteSavedTroubleAudio(audioBean);
            //FileUtil.deleteFile(audioBean.getPath());
        }
    }

    public List<TroublePictureBean> getLocalBuildPhotos(String build_id, int state) {
        return dbDaoHelper.queryTroublePictures(build_id, state);
    }

    public List<TroubleAudioBean> getLocalBuildAudios(String build_id, int state) {
        return dbDaoHelper.queryTroubleAudios(build_id, state);
    }

    /**
     * 新增工地回报登记保存
     */
    private void saveBuildReport(BuildReportBean buildReport, List<TroublePictureBean> pictures, List<TroubleAudioBean> audios) {
        if (buildReport != null) {
            int save_state = TroubleBean.SAVED_STATE;
            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(OfflineWorkJobType.JOB_BUILD_REPORT_ADD);

            /*保存工地的数据信息*/
            buildReport.setSave_state(save_state);
            dbDaoHelper.insertOrUpdateBuildReport(buildReport);

            workJobBean.setRef_id(buildReport.getId());

            /*保存工地的图片*/
            for (TroublePictureBean pictureBean : pictures) {
                List<String> pic_ids = new ArrayList<>();
                if (pictureBean != null && FileUtil.fileExists(pictureBean.getFilepath())) {
                    pictureBean.setTroubleid(buildReport.getId());
                    pictureBean.setStatus(save_state);
                    dbDaoHelper.insertOrUpdateTroublePicture(pictureBean);

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

            /*保存工地的音频*/
            String filetype = "amr";
            for (TroubleAudioBean audioBean : audios) {
                List<String> audio_ids = new ArrayList<>();
                if (audioBean != null && FileUtil.fileExists(audioBean.getPath())) {
                    String audioId = UUID.randomUUID().toString();
                    audioBean.setId(audioId);
                    audioBean.setTroubleid(buildReport.getId());
                    audioBean.setFiletype(filetype);
                    audioBean.setStatus(save_state);
                    dbDaoHelper.insertOrUpdateTroubleAudio(audioBean);

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

            dbDaoHelper.insertOfflineWorkJob(workJobBean);
        }
    }

    /**
     * 新增工地回报登记上传
     */
    public void addBuildReport(final Context context, final BuildReportBean buildReport, final List<TroublePictureBean> photos,
                               final List<TroubleAudioBean> audios, final boolean saveOnFail, final BuildManageCallback buildManageCallback) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && buildReport != null) {
            saveBuildReport(buildReport, TroubleBean.SAVE_UPLOADING_STATE);
            if (buildManageController == null)
                buildManageController = new BuildManageController(context);
            buildManageController.uploadBuildReport(userBean.getToken(), userBean.getUserid(), buildReport, photos, audios, new BuildManageCallback() {
                @Override
                public void onUploadBuildReport(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUploadBuildReport(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                        deleteLocalBuildReport(buildReport, photos, audios);
                    } else {
                        if (saveOnFail) {
                            saveBuildReport(buildReport, photos, audios);
                        } else {
                            saveBuildReport(buildReport, TroubleBean.SAVED_STATE);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }
                    if (buildManageCallback != null)
                        buildManageCallback.onUploadBuildReport(isSuccess, errorCode, errMsg);
                }
            });
        }
    }

    public void addBuildReport(final Context context, BuildReportBean buildReport, List<TroublePictureBean> photos,
                               List<Record> records, BuildManageCallback buildManageCallback) {
        List<TroubleAudioBean> audios = TroubleAudioBean.getAudioBeans(records);
        addBuildReport(context, buildReport, photos, audios, true, buildManageCallback);
    }

    public void addBuildReportNoSave(final Context context, BuildReportBean buildReport, List<TroublePictureBean> photos,
                                     List<TroubleAudioBean> audios, BuildManageCallback buildManageCallback) {
        addBuildReport(context, buildReport, photos, audios, false, buildManageCallback);
    }

    private void saveBuildReport(BuildReportBean buildReport, int report_state) {
        if (buildReport != null) {
            buildReport.setSave_state(report_state);
            dbDaoHelper.insertOrUpdateBuildReport(buildReport);
        }
    }

    public void getBuildReportList(final Context context, final BuildManageBean buildManage, final BuildManageCallback buildManageCallback) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (buildManage != null) {
            if (buildManageController == null)
                buildManageController = new BuildManageController(context);
            buildManageController.getBuildReportList(userBean.getToken(), buildManage.getId(), 1, C.DEFAULT_MAX_LOAD_PAGESIZE, new BuildManageCallback() {
                @Override
                public void onGetBuildReportList(boolean isSuccess, int errorCode, String errMsg, List<BuildReportBean> buildReportList, int total) {
                    super.onGetBuildReportList(isSuccess, errorCode, errMsg, buildReportList, total);
                    List<BuildReportBean> reportList = new ArrayList<>();
                    if (isSuccess) {
                        if (buildReportList != null) {
                            reportList.addAll(buildReportList);
                        }
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }
                    List<BuildReportBean> localReportList = dbDaoHelper.getBuildReportList(buildManage.getId(), TroubleBean.SAVED_STATE);
                    if (localReportList != null)
                        reportList.addAll(localReportList);
                    int total_count = reportList.size();
                    if (buildManageCallback != null)
                        buildManageCallback.onGetBuildReportList(isSuccess, errorCode, errMsg, reportList, total_count);
                }
            });
        }
    }

    /**
     * 删除本地工地回报等级数据
     */
    public void deleteLocalBuildReport(BuildReportBean buildReport, List<TroublePictureBean> pictures, List<TroubleAudioBean> audios) {
        dbDaoHelper.deleteBuildReport(buildReport);

        if (pictures != null && pictures.size() > 0) {
            dbDaoHelper.deleteSavedTroublePictures(pictures);
            for (TroublePictureBean pictureBean : pictures) {
                String file = pictureBean.getFilepath();
                FileUtil.deleteFile(file);
            }
        }
        if (audios != null && audios.size() > 0) {
            dbDaoHelper.deleteSavedTroubleAudios(audios);
            for (TroubleAudioBean audioBean : audios) {
                String file = audioBean.getPath();
                FileUtil.deleteFile(file);
            }
        }

        OfflineWorkJobBean workJobBean = dbDaoHelper.getOfflineWorkJob(buildReport.getId());
        if (workJobBean != null) {
            dbDaoHelper.deleteOfflineWorkJob(workJobBean);
        }
    }

    public void getUploadedBuildReportFiles(Context context, String reportId, final GetUploadFileCallback getUploadFileCallback) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            if (uploadFileController == null)
                uploadFileController = new UploadFileController(context);
            uploadFileController.getUploadFileList(userBean.getToken(), reportId,
                    UploadFileBean.FILE_TABLE_BUILD_REPORT, 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.isFileTypeImage()) {
                                        uploadPhotos.add(fileBean);
                                    } else if (fileBean.isFileTypeAudio()) {
                                        uploadAudios.add(fileBean);
                                    }
                                }
                            }
                            getUploadFileCallback.onGetPhotoAudio(isSuccess, uploadPhotos, uploadAudios);
                        }
                    });
        }
    }

    public void getUploadAudioFromServer(final Context context, final String reportId, final String url, int audioLength,
                                         final String fileNote, final TroubleTool.GetAudioCallback getAudioCallback) {
        TroubleTool troubleTool = TroubleTool.getInstance();
        troubleTool.getTroubleAudioFromServer(context, reportId, url, audioLength, fileNote, getAudioCallback);
    }

    public void deleteBuildReport(final Context context, BuildReportBean buildReport, final BuildManageCallback buildManageCallback) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (buildReport != null) {
            final String reportid = buildReport.getId();
            if (buildManageController == null)
                buildManageController = new BuildManageController(context);
            buildManageController.removeBuildReport(userBean.getToken(), reportid, new BuildManageCallback() {
                @Override
                public void onRemoveBuildReport(boolean isSuccess, int errorCode, String errMsg) {
                    super.onRemoveBuildReport(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }
                    if (buildManageCallback != null)
                        buildManageCallback.onRemoveBuildReport(isSuccess, errorCode, errMsg);
                }
            });
        }
    }
}
