package com.tofly.ghrq_route.module.OfflineWork;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.module.OfflineWork.domain.OfflineJobNeedData;
import com.tofly.ghrq_route.module.OfflineWork.domain.OfflineJobNeedData.OfflineWorkNeedType;
import com.tofly.ghrq_route.module.OfflineWork.domain.OfflineWorkEvent;
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.BuildTool;
import com.tofly.ghrq_route.module.buildManage.controller.BuildManageCallback;
import com.tofly.ghrq_route.module.buildManage.domain.BuildFileBean;
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.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.deviceInfo.domain.DeviceInfoBean;
import com.tofly.ghrq_route.module.gps.GpsTool;
import com.tofly.ghrq_route.module.gps.controller.GPSCallBack;
import com.tofly.ghrq_route.module.gps.domain.GPSDataBean;
import com.tofly.ghrq_route.module.job.JobTool;
import com.tofly.ghrq_route.module.job.controller.JobCallBack;
import com.tofly.ghrq_route.module.job.domain.JobBean;
import com.tofly.ghrq_route.module.plan.PlanTool;
import com.tofly.ghrq_route.module.plan.controller.PlanCallBack;
import com.tofly.ghrq_route.module.plan.domain.OfflinePathBean;
import com.tofly.ghrq_route.module.plan.domain.PlanBean;
import com.tofly.ghrq_route.module.planPointRepair.PointRepairTool;
import com.tofly.ghrq_route.module.planPointRepair.controller.PointRepairCallBack;
import com.tofly.ghrq_route.module.planPointRepair.domain.MaintainAdjustParam;
import com.tofly.ghrq_route.module.planPointRepair.domain.MaintainCommonParam;
import com.tofly.ghrq_route.module.planPointRepair.domain.PlanPointRepair;
import com.tofly.ghrq_route.module.rushrepair.RushRepairTool;
import com.tofly.ghrq_route.module.rushrepair.controller.RushRepairCallback;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairBean;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairProcessBean;
import com.tofly.ghrq_route.module.sign.SignTool;
import com.tofly.ghrq_route.module.sign.controller.SignCallBack;
import com.tofly.ghrq_route.module.sign.domain.SignHistoryDataBean;
import com.tofly.ghrq_route.module.sketch.SketchTool;
import com.tofly.ghrq_route.module.sketch.controller.SketchCallback;
import com.tofly.ghrq_route.module.sketch.domain.SketchBean;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.systemConfig.controller.ServerSysConfigCallBack;
import com.tofly.ghrq_route.module.systemConfig.domain.ServerSysConfigBean;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.controller.TroubleCallBack;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.troubleType.TroubleTypeTool;
import com.tofly.ghrq_route.module.troubleType.controller.TroubleTypeCallBack;
import com.tofly.ghrq_route.module.troubleType.domain.SysDeviceTypeBean;
import com.tofly.ghrq_route.module.troubleType.domain.TroubleTypeBean;
import com.tofly.ghrq_route.module.uploadFile.controller.UploadFileCallBack;
import com.tofly.ghrq_route.module.uploadFile.domain.UploadFileBean;
import com.tofly.ghrq_route.module.uploadPhoto.UploadPhotoTool;
import com.tofly.ghrq_route.module.uploadPhoto.controller.UploadPhotoCallBack;
import com.tofly.ghrq_route.module.uploadPhoto.domain.UploadPhotoBean;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.module.user.domain.UserMapDataBean;
import com.tofly.ghrq_route.module.user.domain.UserOnlineMapDataBean;
import com.tofly.ghrq_route.common.ui.activity.UiSign;
import com.tofly.ghrq_route.common.util.EventBusUtil;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.file.FileUtil;

import org.greenrobot.eventbus.EventBus;

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


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

public class OfflineWorkTool {

    private static OfflineWorkTool offlineWorkTool = null;

    private OfflineWorkReceiver offlineWorkReceiver;

    private DBDaoHelper dbDaoHelper;

    private ConnectivityManager connectivityManager;

    private boolean mbNetConnected = false;

    private boolean mbServerConnected = true;

    private int mServerConnectErrorCount = 0;

    private final int MAX_SERVER_CONNECT_ERROR = 2;

    private boolean mbIsFirstConnect = true;

    private static boolean isOffline = false;
    private static boolean isLoginServer = false;

    private List<OfflineWorkJobBean> mOfflineWorkJobs = null;

    private boolean mbCheckingWorkJobs = false;

    private OfflineWorkTool() {
        dbDaoHelper = DBDaoHelper.getInstance();
        connectivityManager = (ConnectivityManager) BaseApp.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public static boolean isOffline() {
        return isOffline;
    }

    public static void setOffline(boolean offline) {
        if (isOffline && !offline) {  //离线-->在线
            //clearBackApiServerData();  2019-10-10 已取消
        }

        isOffline = offline;
        OfflineWorkEvent offlineWorkEvent = isOffline ? new OfflineWorkEvent(OfflineWorkEvent.DEVICE_IS_OFFLINE)
                : new OfflineWorkEvent(OfflineWorkEvent.DEVICE_IS_ONLINE);
        EventBusUtil.postEvent(offlineWorkEvent);
    }

    public static boolean isLoginServer() {
        return isLoginServer;
    }

    public static void setLoginServer(boolean loginServer) {
        isLoginServer = loginServer;
    }

    public boolean isServerConnected() {
        return mbServerConnected;
    }

    public void setServerConnected(boolean connected) {
        mbServerConnected = connected;
    }

    public static synchronized OfflineWorkTool getInstance() {
        if (offlineWorkTool == null) {
            offlineWorkTool = new OfflineWorkTool();
        }
        return offlineWorkTool;
    }


    public void startChecking(Context context) {
        //mContext = context;

        offlineWorkReceiver = new OfflineWorkReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(offlineWorkReceiver, filter);

        //checkDeviceInfo(DeviceInfoBean.WORK_STATE_ING);
        mbCheckingWorkJobs = false;
        checkTodayWork(context);
    }

    public void stopChecking(Context context) {
        if (offlineWorkReceiver != null)
            context.unregisterReceiver(offlineWorkReceiver);
    }

    public void checkTodayWork(Context context) {
        checkServerStatus(context);
        checkNeedLogin(context);
        checkSignStatus(context);
        checkOnceGpsUpload(context);
        checkTodayWorkNeeds(context);
        checkOfflineWork(context);
    }

    private void checkOfflineWork(Context context) {
        checkOfflineWorkJobs(context);
    }

    private void checkNeedLogin(Context context) {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.userLogin(context);
    }

    private void checkSignStatus(Context context) {
        SignTool signTool = SignTool.getInstance();
        signTool.checkSignStatus(context, null);
    }

    private void checkServerStatus(final Context context) {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.userLoginTestServer(context, "", "", false, new UserCallBack() {
            @Override
            public void onLogin(boolean isSuccess, int errorCode, String errMsg, UserBean user) {
                super.onLogin(isSuccess, errorCode, errMsg, user);
                boolean isLastConnected = mbServerConnected;
                if (errorCode == URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT || errorCode == URLResponseCode.ErrorCode.ADDR_FOUND_FAILED) {
                    mbServerConnected = false;
                    mServerConnectErrorCount++;
                } else {
                    mbServerConnected = true;
                    mServerConnectErrorCount = 0;
                }

                if (mbServerConnected != isLastConnected) {
                    OfflineWorkEvent offlineWorkEvent = new OfflineWorkEvent(OfflineWorkEvent.SERVER_IS_REACHABLE, mbServerConnected);
                    EventBusUtil.postEvent(offlineWorkEvent);
                }

                if (mServerConnectErrorCount >= MAX_SERVER_CONNECT_ERROR) {
                    setOffline(true);
                }
            }
        });
    }

    private void checkOnceGpsUpload(Context context) {
        if (BaseApp.getSignState() == UiSign.SIGN_CHECKED_ON_TYPE) {
            return;
        }

        BaseApp.getInstance().startBackgroundAmapServiceForOnce(context);
    }

    public void checkTodayWorkNeeds(Context context) {
        checkTodayBasicNeeds(context);
        checkTodayBuildNeeds(context);
        checkTodayPlanNeeds(context);
    }

    private void checkTodayBasicNeeds(Context context) {
        if (isOffline || !BaseApp.isNetworkConnected())
            return;

        for (int type = 0; type < OfflineWorkNeedType.NEED_BASIC_TYPE_COUNT; type++) {
            getWorkNeed(context, type);
        }
    }

    private void checkTodayPlanNeeds(Context context) {
        if (isOffline || !BaseApp.isNetworkConnected())
            return;

        getTodayPlanList(context);
    }

    private void checkTodayBuildNeeds(Context context) {
        if (isOffline || !BaseApp.isNetworkConnected())
            return;


        geTodayBuildList(context);
    }

    private void getWorkNeed(Context context, int need_type) {
        switch (need_type) {
            case OfflineWorkNeedType.NEED_SIGN_HISTORY_TYPE:
                getTodaySignHistory(context);
                break;
            case OfflineWorkNeedType.NEED_DANGER_DEVICE_TYPE:
                getDangerDeviceTypeList(context);
                break;
            case OfflineWorkNeedType.NEED_DANGER_DANGER_TYPE:
                getDangerDangerTypeList(context);
                break;
            case OfflineWorkNeedType.NEED_PHOTO_PHOTO_TYPE:
                getPhotoPhotoTypeList(context);
                break;
            case OfflineWorkNeedType.NEED_USER_MAP_CONFIG_TYPE:
                getUserMapConfigList(context);
                break;
            case OfflineWorkNeedType.NEED_BUILD_PROJECT_LIST_TYPE:
                getBuildProjectTypeList(context);
                break;
            case OfflineWorkNeedType.NEED_PLAN_ADJUST_DEVICE_PARAMS_TYPE:
                getAdjustDeviceInputParams(context);
                break;
            case OfflineWorkNeedType.NEED_PLAN_COMMON_DEVICE_PARAMS_TYPE:
                getCommonDeviceInputParams(context);
                break;
//            case OfflineWorkNeedType.NEED_BUILD_NEW_INFO:
//                getBuildNew(context);
//                break;
//            case OfflineWorkNeedType.NEED_BUILD_PROCESS:
//                getBuildProcess(context);
//                break;
//            case OfflineWorkNeedType.NEED_RUSH_REPAIR_NEW_INFO:
//                getRushRepairNew(context);
//                break;
//            case OfflineWorkNeedType.NEED_RUSH_REPAIR_PROCESS:
//                getRushRepairProcess(context);
//                break;
        }
    }

    private void getBuildNew(Context context) {
        List<OfflineWorkJobBean> data = dbDaoHelper.getOfflineWorkJobs(OfflineWorkJobBean.OfflineWorkJobType.JOB_BUILD_MANAGE_ADD);
        if (data != null && data.size() > 0) {
            for (OfflineWorkJobBean offlineWorkJobBean : data) {
                BuildManageBean buildManageBean = dbDaoHelper.getBuildManage(offlineWorkJobBean.getRef_id());
                List<String> photoId = offlineWorkJobBean.getRef_photo_ids();
                List<String> audioId = offlineWorkJobBean.getRef_audio_ids();
                List<String> fileId = offlineWorkJobBean.getRef_data_ids();
                List<TroublePictureBean> photos = new ArrayList<>();
                List<TroubleAudioBean> audioBeans = new ArrayList<>();
                List<BuildFileBean> buildFileBeans = new ArrayList<>();
                if (photoId != null && photoId.size() > 0) {
                    for (String s : photoId) {
                        photos.add(dbDaoHelper.getTroublePicture(s));
                    }
                }
                if (audioId != null && audioId.size() > 0) {
                    for (String s : audioId) {
                        audioBeans.add(dbDaoHelper.getTroubleAudio(s));
                    }
                }
                if (fileId != null && fileId.size() > 0) {
                    for (String s : fileId) {
                        buildFileBeans.add(dbDaoHelper.getBuildFile(s, 1));
                    }
                }
                BuildTool buildTool = BuildTool.getInstance();
                buildTool.addBuildManage(context, buildManageBean, photos, audioBeans, buildFileBeans, true, new BuildManageCallback() {
                    @Override
                    public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                        super.onAddBuildManage(isSuccess, errorCode, errMsg);
                        if (isSuccess) {
                            Toast.makeText(context, "上传离线工地成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }
    }

    private void getBuildProcess(Context context) {
        List<OfflineWorkJobBean> data = dbDaoHelper.getOfflineWorkJobs(OfflineWorkJobBean.OfflineWorkJobType.JOB_BUILD_MANAGE_PROCESS);
        if (data != null) {
            for (OfflineWorkJobBean offlineWorkJobBean : data) {
                BuildProcessManageBean buildProcessManageBean = dbDaoHelper.getBuildProcess(offlineWorkJobBean.getRef_id());
                List<String> photoId = offlineWorkJobBean.getRef_photo_ids();
                List<String> audioId = offlineWorkJobBean.getRef_audio_ids();
                List<String> fileId = offlineWorkJobBean.getRef_data_ids();
                List<TroublePictureBean> photos = new ArrayList<>();
                List<TroubleAudioBean> audioBeans = new ArrayList<>();
                List<BuildFileBean> buildFileBeans = new ArrayList<>();
                if (photoId != null && photoId.size() > 0) {
                    for (String s : photoId) {
                        photos.add(dbDaoHelper.getTroublePicture(s));
                    }
                }
                if (audioId != null && audioId.size() > 0) {
                    for (String s : audioId) {
                        audioBeans.add(dbDaoHelper.getTroubleAudio(s));
                    }
                }
                if (fileId != null && fileId.size() > 0) {
                    for (String s : fileId) {
                        buildFileBeans.add(dbDaoHelper.getBuildFile(s, 2));
                    }
                }
                BuildTool buildTool = BuildTool.getInstance();
                buildTool.addBuildManageProcess(context, buildProcessManageBean, photos, audioBeans, buildFileBeans, true, new BuildManageCallback() {
                    @Override
                    public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                        super.onAddBuildManage(isSuccess, errorCode, errMsg);
                        if (isSuccess) {
                            Toast.makeText(context, "上传离线工地过程管理成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }
    }

    private void getRushRepairNew(Context context) {
        List<OfflineWorkJobBean> data = dbDaoHelper.getOfflineWorkJobs(OfflineWorkJobBean.OfflineWorkJobType.JOB_RUSH_REPAIR_ADD);
        if (data != null) {
            for (OfflineWorkJobBean offlineWorkJobBean : data) {
                RushRepairBean rushRepairBean = dbDaoHelper.getRushRepairBean(offlineWorkJobBean.getRef_id());
                List<String> photoId = offlineWorkJobBean.getRef_photo_ids();
                List<String> audioId = offlineWorkJobBean.getRef_audio_ids();
                List<String> fileId = offlineWorkJobBean.getRef_data_ids();
                List<TroublePictureBean> photos = new ArrayList<>();
                List<TroubleAudioBean> audioBeans = new ArrayList<>();
                List<BuildFileBean> buildFileBeans = new ArrayList<>();
                if (photoId != null && photoId.size() > 0) {
                    for (String s : photoId) {
                        photos.add(dbDaoHelper.getTroublePicture(s));
                    }
                }
                if (audioId != null && audioId.size() > 0) {
                    for (String s : audioId) {
                        audioBeans.add(dbDaoHelper.getTroubleAudio(s));
                    }
                }
                if (fileId != null && fileId.size() > 0) {
                    for (String s : fileId) {
                        buildFileBeans.add(dbDaoHelper.getBuildFile(s, 3));
                    }
                }
                RushRepairTool rushRepairTool = RushRepairTool.getInstance();
                rushRepairTool.addBuildJobManage(context, rushRepairBean, photos, audioBeans, buildFileBeans, true, new RushRepairCallback() {
                    @Override
                    public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                        super.onAddBuildManage(isSuccess, errorCode, errMsg);
                        if (isSuccess) {
                            Toast.makeText(context, "上传离线抢维修成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }
    }

    private void getRushRepairProcess(Context context) {
        List<OfflineWorkJobBean> data = dbDaoHelper.getOfflineWorkJobs(OfflineWorkJobBean.OfflineWorkJobType.JOB_RUSH_REPAIR_PROCESS);
        if (data != null) {
            for (OfflineWorkJobBean offlineWorkJobBean : data) {
                RushRepairProcessBean rushRepairProcessBean = dbDaoHelper.getRushRepairProcess(offlineWorkJobBean.getRef_id());
                List<String> photoId = offlineWorkJobBean.getRef_photo_ids();
                List<String> audioId = offlineWorkJobBean.getRef_audio_ids();
                List<String> fileId = offlineWorkJobBean.getRef_data_ids();
                List<TroublePictureBean> photos = new ArrayList<>();
                List<TroubleAudioBean> audioBeans = new ArrayList<>();
                List<BuildFileBean> buildFileBeans = new ArrayList<>();
                if (photoId != null && photoId.size() > 0) {
                    for (String s : photoId) {
                        photos.add(dbDaoHelper.getTroublePicture(s));
                    }
                }
                if (audioId != null && audioId.size() > 0) {
                    for (String s : audioId) {
                        audioBeans.add(dbDaoHelper.getTroubleAudio(s));
                    }
                }
                if (fileId != null && fileId.size() > 0) {
                    for (String s : fileId) {
                        buildFileBeans.add(dbDaoHelper.getBuildFile(s, 4));
                    }
                }
                RushRepairTool rushRepairTool = RushRepairTool.getInstance();
                rushRepairTool.addRushManageProcess(context, rushRepairProcessBean, photos, audioBeans, buildFileBeans, true, new RushRepairCallback() {
                    @Override
                    public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                        super.onAddBuildManage(isSuccess, errorCode, errMsg);
                        if (isSuccess) {
                            Toast.makeText(context, "上传离线抢维修过程管理成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }
    }

    private void getDangerDeviceTypeList(Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getDangerDeviceType = jobNeedData.getDevice_type();
        if (getDangerDeviceType == 0) {
            TroubleTypeTool troubleTypeTool = TroubleTypeTool.getInstance();
            troubleTypeTool.getSysDeviceTypeList(context, new TroubleTypeCallBack() {
                @Override
                public void onGetSysDeviceTypeList(boolean isSuccess, int errorCode, String errMsg, List<SysDeviceTypeBean> equipments) {
                    super.onGetSysDeviceTypeList(isSuccess, errorCode, errMsg, equipments);
                    if (isSuccess) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_DANGER_DEVICE_TYPE);
                    }
                }
            });
        }
    }

    private void getTodaySignHistory(Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getSignHistory = jobNeedData.getToday_sign_history();
        if (getSignHistory == 0) {
            SignTool signTool = SignTool.getInstance();
            signTool.getSignListToday(context, new SignCallBack() {
                @Override
                public void onGetSignListToday(boolean isSuccess, int errorCode, String errMsg, List<SignHistoryDataBean> signDataBeanList, int total) {
                    super.onGetSignListToday(isSuccess, errorCode, errMsg, signDataBeanList, total);
                    if (isSuccess) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_SIGN_HISTORY_TYPE);
                    }
                }
            });
        }
    }

    private void getDangerDangerTypeList(Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getDangerType = jobNeedData.getDanger_type();
        if (getDangerType == 0) {
            TroubleTypeTool troubleTypeTool = TroubleTypeTool.getInstance();
            troubleTypeTool.getTroubleTypeList(context, new TroubleTypeCallBack() {
                @Override
                public void onGetTroubleTypeList(boolean isSuccess, int errorCode, String errMsg, List<TroubleTypeBean> troubleTypes) {
                    super.onGetTroubleTypeList(isSuccess, errorCode, errMsg, troubleTypes);
                    if (isSuccess) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_DANGER_DANGER_TYPE);
                    }
                }
            });
        }
    }

    private void getPhotoPhotoTypeList(Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getPhotoType = jobNeedData.getPhoto_type();
        if (getPhotoType == 0) {
            UploadPhotoTool uploadPhotoTool = UploadPhotoTool.getInstance();
            uploadPhotoTool.getPhotoTypeConfigList(context, new ServerSysConfigCallBack() {
                @Override
                public void onGetSysConfigList(boolean isSuccess, int errorCode, String errMsg, List<ServerSysConfigBean> configList, int total) {
                    super.onGetSysConfigList(isSuccess, errorCode, errMsg, configList, total);
                    if (isSuccess) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_PHOTO_PHOTO_TYPE);
                    }
                }
            });
        }
    }

    private void getUserMapConfigList(Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getMapConfig = jobNeedData.getMap_config_type();
        if (getMapConfig == 0) {
            UserInfoTool userInfoTool = UserInfoTool.getInstance();
            userInfoTool.getUserMapConfigData(context, new UserCallBack() {
                @Override
                public void onGetMapConfigData(boolean isSuccess, int errorCode, String errMsg, List<UserOnlineMapDataBean> urlConfigDataBean, List<UserMapDataBean> userMapDataBeanList) {
                    super.onGetMapConfigData(isSuccess, errorCode, errMsg, urlConfigDataBean, userMapDataBeanList);
                    if (isSuccess) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_USER_MAP_CONFIG_TYPE);
                    }
                }
            });
        }
    }

    private void getTodayPlanList(final Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getPlanList = jobNeedData.getPlan_list();
        if (getPlanList == 0) {
            PlanTool planTool = PlanTool.getInstance();
            planTool.getPlanListToday(context, new PlanCallBack() {
                @Override
                public void onGetPlanList(boolean isSuccess, int errorCode, String errMsg, List<PlanBean> planList, int total) {
                    super.onGetPlanList(isSuccess, errorCode, errMsg, planList, total);
                    if (isSuccess) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_PLAN_PLAN_LIST_TYPE);

                        /*获取巡检计划的隐患内容*/
                        //getPlansDangerInfo(context);
                    }
                }
            });
        } else {
            /*获取巡检计划的隐患内容*/
            //getPlansDangerInfo(context);
        }
    }

    private void getPlanPoint() {
        PlanTool planTool = PlanTool.getInstance();
        planTool.needTodayPlanPoint();
    }

    private int mPlanDangerIndex = 0;
    private boolean mGetDangersAllSuccess = true;

    private synchronized void getPlansDangerInfo(Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getDangerList = jobNeedData.getDanger_info();
        if (getDangerList == 0) {
            PlanTool planTool = PlanTool.getInstance();
            List<PlanBean> planBeans = planTool.getLocalPlans();
            List<OfflinePathBean> allDangerPoints = new ArrayList<>();
            if (planBeans != null && planBeans.size() > 0) {
                for (final PlanBean planBean : planBeans) {
                    if (planBean != null && planBean.isDangerDeviceType()) {
                        List<OfflinePathBean> points = planTool.getLocalPlanPoints(planBean.getPlan_id());
                        allDangerPoints.addAll(points);
                    }
                }
            }
            if (allDangerPoints.size() > 0) {
                mPlanDangerIndex = 0;
                mGetDangersAllSuccess = true;
                getPlanDangerInfo(context, allDangerPoints);
            }
        }
    }

    private synchronized void getPlanDangerInfo(final Context context, final List<OfflinePathBean> dangers) {
        TroubleTool troubleTool = TroubleTool.getInstance();
        OfflinePathBean dangerPoint = dangers.get(mPlanDangerIndex);
        troubleTool.loadTroubleInfo(context, dangerPoint.getTrouble_id(), new TroubleCallBack() {
            @Override
            public void onGetTroubleInfo(boolean isSuccess, int errorCode, String errMsg, TroubleBean troubleBean) {
                super.onGetTroubleInfo(isSuccess, errorCode, errMsg, troubleBean);
                if (!isSuccess) {
                    mGetDangersAllSuccess = false;
                }
                mPlanDangerIndex++;
                if (mPlanDangerIndex < dangers.size()) {
                    getPlanDangerInfo(context, dangers);
                } else {
                    if (mGetDangersAllSuccess) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_PLAN_DANGER_INFO_TYPE);
                    }
                }
            }
        });
    }


    private synchronized void getAdjustDeviceInputParams(Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getRouteParams = jobNeedData.getAdjust_device_route_params();
        if (getRouteParams == 0) {
            PointRepairTool repairTool = PointRepairTool.getInstance();
            repairTool.getAdjustDeviceSettingListFromServer(context, new PointRepairCallBack() {
                @Override
                public void onGetAdjustDeviceSettingList(boolean isSuccess, int errorCode, String errMsg, List<MaintainAdjustParam> paramList, int total) {
                    super.onGetAdjustDeviceSettingList(isSuccess, errorCode, errMsg, paramList, total);
                    if (isSuccess) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_PLAN_ADJUST_DEVICE_PARAMS_TYPE);
                    }
                }
            });
        }
    }

    private synchronized void getCommonDeviceInputParams(Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getRouteParams = jobNeedData.getValve_device_route_params();
        if (getRouteParams == 0) {
            PointRepairTool repairTool = PointRepairTool.getInstance();
            repairTool.getCommonDeviceSettingListFromLocal(context, new PointRepairCallBack() {
                @Override
                public void onGetCommonDeviceSettingList(boolean isSuccess, int errorCode, String errMsg, List<MaintainCommonParam> paramList, int total) {
                    super.onGetCommonDeviceSettingList(isSuccess, errorCode, errMsg, paramList, total);
                    if (isSuccess) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_PLAN_COMMON_DEVICE_PARAMS_TYPE);
                    }
                }
            });
        }
    }

    private void getBuildProjectTypeList(Context context) {
        if (C.is_passed_notify)
            return;

        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getBuildProjects = jobNeedData.getBuild_project_list();
        if (getBuildProjects == 0) {
            BuildTool buildTool = BuildTool.getInstance();
            buildTool.getBuildProjectTypeList(context, 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) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_BUILD_PROJECT_LIST_TYPE);
                    }
                }
            });
        }
    }

    private void geTodayBuildList(final Context context) {
        if (C.is_passed_notify)
            return;

        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getBuilds = jobNeedData.getBuild_list();
        if (getBuilds == 0) {
            BuildTool buildTool = BuildTool.getInstance();
            buildTool.getBuildManageList(context, null, true, 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) {
                        setOfflineJobNeedData(OfflineWorkNeedType.NEED_BUILD_BUILD_LIST_TYPE);

                        /*获取工地告知书文件*/
                        getBuildNoticeFiles(context);
                    }
                }
            });
        } else {
            getBuildNoticeFiles(context);
        }
    }

    private int mNoticeIndex = 0;
    private boolean mGetNoticeAllSuccess = true;

    private synchronized void getBuildNoticeFiles(Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        int getBuildNotices = jobNeedData.getBuild_notice_files();
        if (getBuildNotices == 0) {
            BuildTool buildTool = BuildTool.getInstance();
            final List<BuildManageBean> buildManages = buildTool.getLocalBuildManageList();
            mGetNoticeAllSuccess = true;
            mNoticeIndex = 0;
            for (BuildManageBean buildManage : buildManages) {
                // boolean hasNotice = buildManage.getHasBuildNotice();
                boolean hasNotice = false;
                if (hasNotice) {
                    buildTool.getBuildNoticeFiles(context, buildManage, (isSuccess, hasNoticeFile, photos, audios) -> {
                        mNoticeIndex++;
                        if (isSuccess) {
                        } else {
                            mGetNoticeAllSuccess = false;
                        }
                        if (mNoticeIndex == buildManages.size()) {
                            if (mGetNoticeAllSuccess) {
                                setOfflineJobNeedData(OfflineWorkNeedType.NEED_BUILD_BUILD_NOTICE_FILE_TYPE);
                            }
                        }
                    });
                }
            }
        }
    }

    private void setOfflineJobNeedData(int need_type) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        String time = DateUtils.getDate();
        switch (need_type) {
            case OfflineWorkNeedType.NEED_SIGN_HISTORY_TYPE:
                jobNeedData.setToday_sign_history(1);
                jobNeedData.setSign_history_date(time);
                break;
            case OfflineWorkNeedType.NEED_DANGER_DEVICE_TYPE:
                jobNeedData.setDevice_type(1);
                jobNeedData.setDevice_type_date(time);
                break;
            case OfflineWorkNeedType.NEED_DANGER_DANGER_TYPE:
                jobNeedData.setDanger_type(1);
                jobNeedData.setDanger_type_date(time);
                break;
            case OfflineWorkNeedType.NEED_PHOTO_PHOTO_TYPE:
                jobNeedData.setPhoto_type(1);
                jobNeedData.setPhoto_type_date(time);
                break;
            case OfflineWorkNeedType.NEED_USER_MAP_CONFIG_TYPE:
                jobNeedData.setMap_config_type(1);
                jobNeedData.setMap_config_date(time);
                break;
            case OfflineWorkNeedType.NEED_BUILD_PROJECT_LIST_TYPE:
                jobNeedData.setBuild_project_list(1);
                jobNeedData.setBuild_project_list_date(time);
                break;
            case OfflineWorkNeedType.NEED_PLAN_ADJUST_DEVICE_PARAMS_TYPE:
                jobNeedData.setAdjust_device_route_params(1);
                jobNeedData.setAdjust_route_params_date(time);
            case OfflineWorkNeedType.NEED_PLAN_COMMON_DEVICE_PARAMS_TYPE:
                jobNeedData.setValve_device_route_params(1);
                jobNeedData.setVavle_route_params_date(time);
            case OfflineWorkNeedType.NEED_PLAN_PLAN_LIST_TYPE:
                jobNeedData.setPlan_list(1);
                jobNeedData.setPlan_list_date(time);
                break;
            case OfflineWorkNeedType.NEED_PLAN_DANGER_INFO_TYPE:
                jobNeedData.setDanger_info(1);
                jobNeedData.setDanger_info_date(time);
                break;
            case OfflineWorkNeedType.NEED_PLAN_DEVICE_ROUTE_PARAMS_TYPE:
                break;
            case OfflineWorkNeedType.NEED_PLAN_OFFLINE_POINT_LIST_TYPE:
                jobNeedData.setPlan_offline_points(1);
                jobNeedData.setPlan_offline_date(time);
                break;
            case OfflineWorkNeedType.NEED_BUILD_BUILD_LIST_TYPE:
                jobNeedData.setBuild_list(1);
                jobNeedData.setBuild_list_date(time);
                break;
            case OfflineWorkNeedType.NEED_BUILD_BUILD_NOTICE_FILE_TYPE:
                jobNeedData.setBuild_notice_files(1);
                jobNeedData.setBuild_notice_date(time);
                break;
        }
        dbDaoHelper.updateTodayJobNeedData(jobNeedData);
    }

    public void resetPlanBuildWork(Context context) {
        OfflineJobNeedData jobNeedData = dbDaoHelper.getTodayJobNeedData();
        jobNeedData.setPlan_list(0);
        jobNeedData.setDanger_info(0);
        jobNeedData.setBuild_list(0);
        jobNeedData.setBuild_notice_files(0);
        dbDaoHelper.updateTodayJobNeedData(jobNeedData);
        checkTodayWorkNeeds(context);
    }


    public long getOfflineWorkJobsCount() {
        long total_count;
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean == null)
            return 0;

        long job_counts = dbDaoHelper.getOfflineWorkJobsCount(userBean.getUserid());

        String user_id = userBean.getUserid();
        int planMode = userBean.getCar_mode();
        long unUpload_points_count = dbDaoHelper.getUnUploadPointsCount(user_id, planMode);

        long unUpload_gps_count = dbDaoHelper.getSavedGpsCount();

        total_count = job_counts + unUpload_points_count + unUpload_gps_count;

        return total_count;
    }

    public List<OfflineWorkJobBean> getOfflineWorkJobs() {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean == null)
            return null;

        return dbDaoHelper.getOfflineWorkJobs(userBean.getUserid());
    }

    public long getUnUploadGpsCount() {
        return dbDaoHelper.getSavedGpsCount();
    }

    private int mWorkJobIndex = 0;

    private synchronized void checkOfflineWorkJobs(Context context) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean == null)
            return;

        if (isOffline || !BaseApp.isNetworkConnected())
            return;

        List<OfflineWorkJobBean> jobBeans = dbDaoHelper.getOfflineWorkJobs(userBean.getUserid());
        if (jobBeans != null && jobBeans.size() > 0) {
            if (!mbCheckingWorkJobs) {
                mOfflineWorkJobs = jobBeans;
                mbCheckingWorkJobs = true;
                mWorkJobIndex = 0;
                checkOfflineWorkJob(context);
            }
        } else {
            checkUnUploadOverPoints();
        }
    }

    private synchronized void checkOfflineWorkJob(Context context) {
        if (mOfflineWorkJobs == null)
            return;

        if (mWorkJobIndex == mOfflineWorkJobs.size()) {
            mbCheckingWorkJobs = false;
            mOfflineWorkJobs = null;
            EventBusUtil.postEvent(new OfflineWorkEvent(OfflineWorkEvent.OFFLINE_JOB_UPLOAED));
            checkUnUploadOverPoints();
            return;
        }

        OfflineWorkJobBean workJobBean = mOfflineWorkJobs.get(mWorkJobIndex);
        int job_type = workJobBean.getJob_type();
        switch (job_type) {
            case OfflineWorkJobType.JOB_SIGN_UP_OFF_ADD:
                signHistoryWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_UPLOAD_PHOTO_ADD:
                uploadPhotoWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_PLAN_INFO_CHANGED:
                planInfoWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_DANGER_DANGER_ADD:
                dangerUploadWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_DANGER_PLAN_ROUTE_ADD:
                dangerAddRouteWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_DANGER_PLAN_CLEAR_ADD:
                dangerAddClearWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_COMMON_DEVICE_ROUTE_ADD:
                commonDeviceAddRepairWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_ADJUST_DEVICE_ROUTE_ADD:
                adjustDeviceAddRepairWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_BUILD_MANAGE_ADD:
                buildUploadWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_BUILD_REPORT_ADD:
                buildAddReportWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_BUILD_LOG_ADD:
                buildAddLogWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_BUILD_NOTICE_PHOTO_ADD:
                buildAddNoticePhotoWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_BUILD_NOTICE_AUDIO_ADD:
                buildAddNoticeAudioWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_MY_JOB_ADD:
                jobUploadWork(context, workJobBean);
                break;
            case OfflineWorkJobType.JOB_MY_SKETCH_ADD:
                sketchUploadWork(context, workJobBean);
                break;
        }
    }

    private List<TroublePictureBean> getRefPictures(OfflineWorkJobBean workJobBean) {
        List<String> photo_ids = workJobBean.getRef_photo_ids();
        List<TroublePictureBean> pictureBeans = new ArrayList<>();
        if (photo_ids != null) {
            for (String photo_id : photo_ids) {
                if (photo_id != null && !photo_id.isEmpty()) {
                    TroublePictureBean pictureBean = dbDaoHelper.queryTroublePicture(photo_id);
                    if (pictureBean != null) {
                        String filePath = pictureBean.getFilepath();
                        if (filePath != null && FileUtil.fileExists(filePath)) {
                            pictureBeans.add(pictureBean);
                        }
                    }
                }
            }
        }
        return pictureBeans;
    }

    private List<TroubleAudioBean> getRefAudios(OfflineWorkJobBean workJobBean) {
        List<String> audio_ids = workJobBean.getRef_audio_ids();
        List<TroubleAudioBean> audioBeans = new ArrayList<>();
        if (audio_ids != null) {
            for (String audio_id : audio_ids) {
                if (audio_id != null && !audio_id.isEmpty()) {
                    TroubleAudioBean audioBean = dbDaoHelper.queryTroubleAudioById(audio_id);
                    if (audioBean != null) {
                        String filePath = audioBean.getPath();
                        if (filePath != null && FileUtil.fileExists(filePath)) {
                            audioBeans.add(audioBean);
                        }
                    }
                }
            }
        }
        return audioBeans;
    }

    private void signHistoryWork(final Context context, OfflineWorkJobBean workJobBean) {
        String sign_id = workJobBean.getRef_id();
        String device_id = workJobBean.getRef_data_id();
        SignHistoryDataBean signHistoryData = dbDaoHelper.getSignHistoryData(sign_id);
        if (signHistoryData != null) {
            DeviceInfoBean deviceInfoBean = dbDaoHelper.getDeviceInfo(device_id);
            SignTool signTool = SignTool.getInstance();
            signTool.signOnOffNoSave(context, signHistoryData, deviceInfoBean, (isSuccess, errMsg, errCode) -> {
                mWorkJobIndex++;
                checkOfflineWorkJob(context);
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void uploadPhotoWork(final Context context, OfflineWorkJobBean workJobBean) {
        String photo_data_id = workJobBean.getRef_id();
        UploadPhotoBean uploadPhotoBean = dbDaoHelper.getUploadPhoto(photo_data_id);
        if (uploadPhotoBean != null) {
            List<TroublePictureBean> pictureBeans = getRefPictures(workJobBean);
            List<TroubleAudioBean> audioBeans = getRefAudios(workJobBean);
            UploadPhotoTool uploadPhotoTool = UploadPhotoTool.getInstance();
            uploadPhotoTool.uploadNewPhotoNoSave(context, uploadPhotoBean, pictureBeans, audioBeans, new UploadPhotoCallBack() {
                @Override
                public void onAddUploadPhotoInfo(boolean isSuccess, int errorCode, String errMsg, String photoId) {
                    super.onAddUploadPhotoInfo(isSuccess, errorCode, errMsg, photoId);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void planInfoWork(Context context, OfflineWorkJobBean workJobBean) {
        mWorkJobIndex++;
        checkOfflineWorkJob(context);
    }

    private void dangerUploadWork(final Context context, OfflineWorkJobBean workJobBean) {
        String trouble_id = workJobBean.getRef_id();
        TroubleTool troubleTool = TroubleTool.getInstance();
        TroubleBean troubleBean = troubleTool.getLocalTrouble(trouble_id);
        ;
        if (troubleBean != null) {
            List<TroublePictureBean> pictureBeans = getRefPictures(workJobBean);
            List<TroubleAudioBean> audioBeans = getRefAudios(workJobBean);
            troubleTool.uploadNewTroubleNoSave(context, troubleBean, pictureBeans, audioBeans, null, new TroubleCallBack() {
                @Override
                public void onAddTrouble(boolean isSuccess, int errorCode, String errMsg, String troubleId) {
                    super.onAddTrouble(isSuccess, errorCode, errMsg, troubleId);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void dangerAddRouteWork(final Context context, OfflineWorkJobBean workJobBean) {

    }

    private void dangerAddClearWork(final Context context, OfflineWorkJobBean workJobBean) {

    }

    private void commonDeviceAddRepairWork(final Context context, OfflineWorkJobBean workJobBean) {
        String repair_id = workJobBean.getRef_id();
        PlanPointRepair repairInfo = dbDaoHelper.getLocalRepairInfo(repair_id);
        String point_id = repairInfo.getPoint_id();
        String plan_id = repairInfo.getPlan_id();
        OfflinePathBean planPoint = dbDaoHelper.getPlanOfflinePath(point_id, plan_id);
        if (repairInfo != null && !repairInfo.isUpdating()) {
            List<TroublePictureBean> pictureBeans = getRefPictures(workJobBean);
            PointRepairTool repairTool = PointRepairTool.getInstance();
            repairTool.uploadCommonDeviceRepairRecordNoSave(context, repairInfo, pictureBeans, new PointRepairCallBack() {
                @Override
                public void onAddPointChildRepair(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddPointChildRepair(isSuccess, errorCode, errMsg);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void adjustDeviceAddRepairWork(final Context context, OfflineWorkJobBean workJobBean) {
        String repair_id = workJobBean.getRef_id();
        PlanPointRepair repairInfo = dbDaoHelper.getLocalRepairInfo(repair_id);
        if (repairInfo != null) {
            List<TroublePictureBean> pictureBeans = getRefPictures(workJobBean);
            PointRepairTool repairTool = PointRepairTool.getInstance();
            repairTool.uploadAdjustDeviceRepairRecordNoSave(context, repairInfo, pictureBeans, new PointRepairCallBack() {
                @Override
                public void onAddPointChildRepair(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddPointChildRepair(isSuccess, errorCode, errMsg);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void buildUploadWork(final Context context, OfflineWorkJobBean workJobBean) {
        String build_id = workJobBean.getRef_id();
        BuildManageBean buildManage = dbDaoHelper.getBuildManage(build_id);
        if (buildManage != null) {
            List<TroublePictureBean> pictureBeans = getRefPictures(workJobBean);
            List<TroubleAudioBean> audioBeans = getRefAudios(workJobBean);
            BuildTool buildTool = BuildTool.getInstance();
            buildTool.addBuildManageNoSave(context, buildManage, pictureBeans, audioBeans, new BuildManageCallback() {
                @Override
                public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddBuildManage(isSuccess, errorCode, errMsg);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void buildAddReportWork(final Context context, OfflineWorkJobBean workJobBean) {
        String report_id = workJobBean.getRef_id();
        BuildReportBean reportBean = dbDaoHelper.getBuildReport(report_id);
        if (reportBean != null) {
            List<TroublePictureBean> pictureBeans = getRefPictures(workJobBean);
            List<TroubleAudioBean> audioBeans = getRefAudios(workJobBean);
            BuildTool buildTool = BuildTool.getInstance();
            buildTool.addBuildReportNoSave(context, reportBean, pictureBeans, audioBeans, new BuildManageCallback() {
                @Override
                public void onUploadBuildReport(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUploadBuildReport(isSuccess, errorCode, errMsg);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void buildAddLogWork(final Context context, OfflineWorkJobBean workJobBean) {
        String log_id = workJobBean.getRef_id();
        BuildLogBean buildLogBean = dbDaoHelper.getLocalBuildLog(log_id);
        if (buildLogBean != null) {
            BuildTool buildTool = BuildTool.getInstance();
            buildTool.updateBuildLogStateNoSave(context, buildLogBean, new BuildManageCallback() {
                @Override
                public void onUpdateBuildLog(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUpdateBuildLog(isSuccess, errorCode, errMsg);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void buildAddNoticePhotoWork(final Context context, OfflineWorkJobBean workJobBean) {
        String photo_id = workJobBean.getRef_id();
        String build_id = workJobBean.getRef_data_id();
        TroublePictureBean pictureBean = dbDaoHelper.queryTroublePicture(photo_id);
        if (pictureBean != null && build_id != null) {
            BuildTool buildTool = BuildTool.getInstance();
            buildTool.addBuildNoticePhotoNoSave(context, build_id, pictureBean, new UploadFileCallBack() {
                @Override
                public void onAddUploadFile(boolean isSuccess, int errorCode, String errMsg, UploadFileBean fileBean) {
                    super.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void buildAddNoticeAudioWork(final Context context, OfflineWorkJobBean workJobBean) {
        String audio_id = workJobBean.getRef_id();
        String build_id = workJobBean.getRef_data_id();
        TroubleAudioBean audioBean = dbDaoHelper.queryTroubleAudioById(audio_id);
        if (audioBean != null && build_id != null) {
            BuildTool buildTool = BuildTool.getInstance();
            buildTool.addBuildNoticeAudioNoSave(context, build_id, audioBean, new UploadFileCallBack() {
                @Override
                public void onAddUploadFile(boolean isSuccess, int errorCode, String errMsg, UploadFileBean fileBean) {
                    super.onAddUploadFile(isSuccess, errorCode, errMsg, fileBean);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void jobUploadWork(final Context context, OfflineWorkJobBean workJobBean) {
        JobTool jobTool = JobTool.getInstance();
        String job_id = workJobBean.getRef_id();
        JobBean jobBean = jobTool.getLocalJobBean(job_id);
        if (jobBean != null) {
            List<TroublePictureBean> pictureBeans = getRefPictures(workJobBean);
            jobTool.uploadJobDataNoSave(context, jobBean, pictureBeans, new JobCallBack() {
                @Override
                public void onUploadJobData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUploadJobData(isSuccess, errorCode, errMsg);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void sketchUploadWork(final Context context, OfflineWorkJobBean workJobBean) {
        SketchTool sketchTool = SketchTool.getInstance();
        String sketch_id = workJobBean.getRef_id();
        SketchBean sketchBean = sketchTool.getLocalSketchBean(sketch_id);
        if (sketchBean != null) {
            sketchTool.uploadSketchDataNoSave(context, sketchBean, new SketchCallback() {
                @Override
                public void onUploadSketchData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUploadSketchData(isSuccess, errorCode, errMsg);
                    mWorkJobIndex++;
                    checkOfflineWorkJob(context);
                }
            });
        } else {
            mWorkJobIndex++;
            checkOfflineWorkJob(context);
        }
    }

    private void checkUnUploadOverPoints() {
        if (mbCheckingWorkJobs)
            return;

        GpsTool gpsTool = GpsTool.getInstance();
        long count = gpsTool.getUnUploadPointsCount();
        if (count <= 0) {
            checkUnUploadGpsLocs();
            return;
        }

        mbCheckingWorkJobs = true;
        gpsTool.checkPathOverUpload(new PlanCallBack() {
            @Override
            public void onUpdatePointOver(boolean isSuccess, int errorCode, String errMsg, List<String> transfer_ids) {
                super.onUpdatePointOver(isSuccess, errorCode, errMsg, transfer_ids);

                EventBus.getDefault().post(new OfflineWorkEvent(OfflineWorkEvent.OFFLINE_JOB_UPLOAED));

                checkUnUploadGpsLocs();
            }
        });
    }

    private void checkUnUploadGpsLocs() {
        mbCheckingWorkJobs = true;

        long count = getUnUploadGpsCount();
        if (count <= 0) {
            mbCheckingWorkJobs = false;
            return;
        }

        GpsTool gpsTool = GpsTool.getInstance();
        gpsTool.checkSavedGpsInfo(new GPSCallBack() {
            @Override
            public void onUploadBatchGpsInfo(boolean isSuccess, int errorCode, String errMsg, List<GPSDataBean> repeatDatas) {
                super.onUploadBatchGpsInfo(isSuccess, errorCode, errMsg, repeatDatas);
                mbCheckingWorkJobs = false;
            }
        });
    }

    final class OfflineWorkReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                boolean bLastConnected = mbNetConnected;
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isAvailable()) {
                    mbNetConnected = true;
                    checkNeedLogin(context);
                } else {
                    mbNetConnected = false;
                    setOffline(true);
                }

                if (bLastConnected != mbNetConnected) {
                    checkServerStatus(context);
                }

                if (!mbIsFirstConnect) {
                    OfflineWorkEvent offlineWorkEvent = new OfflineWorkEvent(OfflineWorkEvent.NETWORK_IS_REACHABLE, mbNetConnected);
                    EventBusUtil.postEvent(offlineWorkEvent);
                }

                mbIsFirstConnect = false;
            }
        }
    }

    /**
     * 创建一个新的离线待提交任务，后台会自动检查待提交的任务并上传
     *
     * @param ref_id  离线工作任务相关联的id 例如: 隐患的id, 工单的id
     * @param jobType 工作类型 {@link OfflineWorkJobBean.OfflineWorkJobType}
     */
    public OfflineWorkJobBean newOfflineWorkJob(String ref_id, int jobType) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        OfflineWorkJobBean workJobBean = new OfflineWorkJobBean();
        String work_id = UUID.randomUUID().toString();
        workJobBean.setId(work_id);

        if (userBean != null) {
            workJobBean.setUser_id(userBean.getUserid());
        }
        workJobBean.setJob_type(jobType);
        workJobBean.setRef_id(ref_id);

        return workJobBean;
    }

    public void insertOfflineWorkJob(OfflineWorkJobBean workJobBean) {
        dbDaoHelper.insertOfflineWorkJob(workJobBean);
    }

    public OfflineWorkJobBean getOfflineWorkJob(String ref_id) {
        return dbDaoHelper.getOfflineWorkJob(ref_id);
    }

    public void deleteOfflineWorkJob(OfflineWorkJobBean workJobBean) {
        dbDaoHelper.deleteOfflineWorkJob(workJobBean);
    }

    public void deleteOfflineWorkJob(String ref_id) {
        OfflineWorkJobBean workJobBean = getOfflineWorkJob(ref_id);
        if (workJobBean != null)
            dbDaoHelper.deleteOfflineWorkJob(workJobBean);
    }
}
