package com.tofly.ghrq_route.module.sign;

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

import com.mgq.base.utils.string.StringUtil;
import com.mgq.base.utils.toast.ToastUtil;
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.OfflineWorkJobBean;
import com.tofly.ghrq_route.module.deviceInfo.DeviceInfoTool;
import com.tofly.ghrq_route.module.deviceInfo.domain.DeviceInfoBean;
import com.tofly.ghrq_route.module.gps.GpsTool;
import com.tofly.ghrq_route.module.plan.PlanTool;
import com.tofly.ghrq_route.module.sign.controller.SignCallBack;
import com.tofly.ghrq_route.module.sign.controller.SignController;
import com.tofly.ghrq_route.module.sign.domain.SignAttendedDataBean;
import com.tofly.ghrq_route.module.sign.domain.SignDataBean;
import com.tofly.ghrq_route.module.sign.domain.SignHistoryDataBean;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.ui.activity.UiSign;
import com.tofly.ghrq_route.common.util.date.DateUtils;

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

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

public class SignTool {

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

    private static SignTool signTool = null;

    private SignController signController;

    private DBDaoHelper dbDaoHelper;

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

    public static synchronized SignTool getInstance(){
        if (signTool == null){
            signTool = new SignTool();
        }
        return signTool;
    }

    public void deleteSignHistory(SignHistoryDataBean signHistory, DeviceInfoBean deviceInfo){
        /*删除本地保存的签到记录*/
        if (deviceInfo != null)
            dbDaoHelper.deleteSavedDeviceInfo(deviceInfo);

        if (signHistory != null)
            dbDaoHelper.deleteSignHistoryData(signHistory);

        deleteOfflineWorkJob(signHistory);
    }

    public void saveSignHistory(SignHistoryDataBean signHistory, DeviceInfoBean deviceInfo){
        /*签到记录保存在本地*/
        if (deviceInfo != null){
            signHistory.setDeviceInfoId(deviceInfo.getId());
            dbDaoHelper.insertOrUpdateDeviceInfo(deviceInfo);
        }

        signHistory.setState(TroubleBean.SAVED_STATE);
        dbDaoHelper.saveSignHistoryData(signHistory);

        OfflineWorkJobBean workJobBean = new OfflineWorkJobBean();
        String job_id = UUID.randomUUID().toString();
        workJobBean.setId(job_id);
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        workJobBean.setUser_id(userBean.getUserid());
        workJobBean.setJob_type(OfflineWorkJobBean.OfflineWorkJobType.JOB_SIGN_UP_OFF_ADD);
        workJobBean.setRef_id(signHistory.getId());
        if (deviceInfo != null)
            workJobBean.setRef_data_id(deviceInfo.getId());
        dbDaoHelper.insertOfflineWorkJob(workJobBean);
    }

    public void signOnOff(final Context context, final SignHistoryDataBean signHistoryData, final DeviceInfoBean deviceInfoBean, final boolean saveOnFail, final signOffCallback signOffCallback){
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            final int carMode = userBean.isCarMode() ? 1 : 0;
            signHistoryData.setCarmode(carMode);
            String userid = userBean.getUserid();
            signHistoryData.setUserid(userid);
            List<String> localPlanIds = null;
            final int sign_type = signHistoryData.getSignType();
            if (sign_type == UiSign.SIGN_ON_TYPE){
                if (!saveOnFail)
                    localPlanIds = dbDaoHelper.getOfflinePathPlanIds(userid, carMode);
            }
            saveSignHistory(signHistoryData, TroubleBean.SAVE_UPLOADING_STATE);
            if (signController == null)
                signController = new SignController(context);
            signController.signToday(context, userid, signHistoryData, deviceInfoBean, localPlanIds, new SignCallBack() {
                @Override
                public void onSignToday(boolean isSuccess, int errorCode, String errMsg, int section, int plannum, List<String> planIds) {
                    super.onSignToday(isSuccess, errorCode, errMsg, section, plannum, planIds);
                    if (isSuccess) {
                        if (errorCode == URLResponseCode.ErrorCode.SUCCESS){
                            deleteSignHistory(signHistoryData, deviceInfoBean);
                        }
                        if (section > 0) {
                            GpsTool.getInstance().setGpsDataSection(section);
                        }
                        startBackgroundService(context, sign_type);
                        if (sign_type == UiSign.SIGN_ON_TYPE) {
                            setSignPlanData(carMode, plannum, planIds);
                        }
                    }else {
                        if (saveOnFail){
                            saveSignHistory(signHistoryData, deviceInfoBean);
                            startBackgroundService(context, sign_type);
                            isSuccess = true;
                        }else {
                            deleteSignHistory(signHistoryData, deviceInfoBean);
                            //saveSignHistory(signHistoryData, TroubleBean.SAVED_STATE);
                        }
                    }
                    if (signOffCallback != null) {
                        signOffCallback.onSignOff(isSuccess, errMsg, errorCode);
                    }
                }
            });
        }else {
            if (signOffCallback != null){
                String errMsg = "签到/签退时出错，请稍后重试";
                signOffCallback.onSignOff(false, errMsg, URLResponseCode.ErrorCode.UNKNOWN_ERROR);
            }
        }
    }

    public void signOnOff(final Context context, final SignHistoryDataBean signHistoryData, final signOffCallback signOffCallback){
        DeviceInfoBean deviceInfoBean = DeviceInfoTool.getInstance().getDeviceInfo();
        signOnOff(context, signHistoryData, deviceInfoBean, true, signOffCallback);
    }

    public void signOnOffNoSave(final Context context, final SignHistoryDataBean signHistoryData, DeviceInfoBean deviceInfoBean, final signOffCallback signOffCallback){
        signOnOff(context, signHistoryData, deviceInfoBean, false, signOffCallback);
    }

    private void saveSignHistory(SignHistoryDataBean historyData, int state){
        if (historyData != null) {
            historyData.setState(state);
            dbDaoHelper.saveSignHistoryData(historyData);
        }
    }

    /**
     * 删除本地工地回报等级数据
     * */
    public void deleteOfflineWorkJob(SignHistoryDataBean historyData){
        OfflineWorkJobBean workJobBean = dbDaoHelper.getOfflineWorkJob(historyData.getId());
        if (workJobBean != null){
            dbDaoHelper.deleteOfflineWorkJob(workJobBean);
        }
    }

    private void startBackgroundService(Context context, int sign_type){
        /*if (sign_type == UiSign.SIGN_ON_TYPE) {
            BaseApp.getInstance().startAllBackgroundService(context);
        } else if (sign_type == UiSign.SIGN_OFF_TYPE) {
            BaseApp.getInstance().stopBackgroundService(context);
        }*/
    }

    private void setSignPlanData(int carmode, int plan_num, List<String> planIds) {
        SignDataBean signOnData = dbDaoHelper.getTodaySignOn();
        if (signOnData != null) {
            if (carmode == 1){/*车巡*/
                signOnData.setCarPlanNum(plan_num);
            }else {
                signOnData.setPlanNum(plan_num);
            }
            /*有要下载的离线点数据*/
            if (planIds != null && planIds.size() > 0){
                String strPlanIds = StringUtil.listToString(planIds, ',');
                signOnData.setPlanIds(strPlanIds);
                signOnData.setPlanState(0);
            }
            dbDaoHelper.insertOrUpdateSignOn(signOnData);
        }else {
            SignDataBean onSign = new SignDataBean();
            String todayDate = DateUtils.getYMD();
            onSign.setPlanDate(todayDate);
            if (carmode == 1){/*车巡*/
                onSign.setCarPlanNum(plan_num);
            }else {
                onSign.setPlanNum(plan_num);
            }
            /*有要下载的离线点数据*/
            if (planIds != null && planIds.size() > 0){
                String strPlanIds = StringUtil.listToString(planIds, ',');
                onSign.setPlanIds(strPlanIds);
                onSign.setPlanState(0);
            }else {
                onSign.setPlanState(1);
            }
            dbDaoHelper.insertOrUpdateSignOn(onSign);
        }
        DeviceInfoTool.getInstance().checkTodayPlan();
    }

    public void signOff(final Context context, final signOffCallback signOffCallback){
        String lon = "";
        String lat = "";
        String addr = "";
        Location location = GpsTool.getInstance().getLocationInfo();
        if (location != null){
            lon = String.valueOf(location.getLongitude());
            lat = String.valueOf(location.getLatitude());
        }
        SignHistoryDataBean signHistoryData = new SignHistoryDataBean(UiSign.SIGN_OFF_TYPE, lon, lat, 0, addr);
        DeviceInfoBean deviceInfoBean = DeviceInfoTool.getInstance().getDeviceInfo();
        signOnOffNoSave(context, signHistoryData, deviceInfoBean, signOffCallback);
    }

    public void getSignStatusToday(final Context context, final SignCallBack signCallBack) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            if (signController == null)
                signController = new SignController(context);
            signController.getSignStatusToday(context, userBean.getUserid(), new SignCallBack(){
                @Override
                public void onGetSignStatusToday(boolean isSuccess, int errorCode, String errMsg, int signState, int section) {
                    super.onGetSignStatusToday(isSuccess, errorCode, errMsg, signState, section);
                    if (isSuccess){
                        BaseApp.setSignState(signState);
                        if (section > 0){
                            GpsTool.getInstance().setGpsDataSection(section);
                        }
                        /*当前在线状态下，获取当天的计划列表*/
                        if (errorCode == URLResponseCode.ErrorCode.SUCCESS){
                            getTodayPlanList(context);
                        }
                        /*已签到还未签退,开启实时位置信息上传服务*/
                        if (signState == UiSign.SIGN_CHECKED_ON_TYPE) {
                            BaseApp.getInstance().startAllBackgroundService(context);
                        } else {
                            BaseApp.getInstance().stopBackgroundService(context);
                        }
                    }
                    if (signCallBack != null)
                        signCallBack.onGetSignStatusToday(isSuccess, errorCode, errMsg, signState, section);
                }
            });
        }
    }

    public void checkSignStatus(final Context context, final SignCallBack signCallBack) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            if (signController == null)
                signController = new SignController(context);
            signController.getSignStatusToday(context, userBean.getUserid(), new SignCallBack(){
                @Override
                public void onGetSignStatusToday(boolean isSuccess, int errorCode, String errMsg, int signState, int section) {
                    super.onGetSignStatusToday(isSuccess, errorCode, errMsg, signState, section);
                    if (isSuccess){
                        BaseApp.setSignState(signState);
                        /*已签到还未签退,开启实时位置信息上传服务*/
                        if (signState == UiSign.SIGN_CHECKED_ON_TYPE) {
                            BaseApp.getInstance().startAllBackgroundService(context);
                        } else {
                            BaseApp.getInstance().stopBackgroundService(context);
                        }
                    }
                    if (signCallBack != null)
                        signCallBack.onGetSignStatusToday(isSuccess, errorCode, errMsg, signState, section);
                }
            });
        }
    }

    public SignDataBean getTodaySignOn(){
        return dbDaoHelper.getTodaySignOn();
    }

    private void getTodayPlanList(Context context){
        if (true)
            return;

        PlanTool planTool = PlanTool.getInstance();
        planTool.getPlanListToday(context, null);
    }

    public void getSignListToday(Context context, final SignCallBack signCallBack) {
        int pageindex = 1;
        int pagesize = C.DEFAULT_MAX_LOAD_PAGESIZE;
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            if (signController == null)
                signController = new SignController(context);
            signController.getSignListToday(context, userBean.getUserid(), pageindex, pagesize, 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 (signCallBack != null)
                        signCallBack.onGetSignListToday(isSuccess, errorCode, errMsg, signDataBeanList, total);
                }
            });
        }
    }

    public void getDailyAttended(final Context context, String date, final SignCallBack signCallBack){
        if (date != null && !date.isEmpty()){
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null){
                if (signController == null)
                    signController = new SignController(context);
                signController.getDailyPlanAttened(context, userBean.getUserid(), date, new SignCallBack(){
                    @Override
                    public void onGetDailyPlanAttened(boolean isSuccess, int errorCode, String errMsg, List<SignAttendedDataBean> attendedList) {
                        super.onGetDailyPlanAttened(isSuccess, errorCode, errMsg, attendedList);
                        if (isSuccess){
                        }else {
                            errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                            ToastUtil.showToast(context, errMsg);
                        }
                        if (signCallBack != null)
                            signCallBack.onGetDailyPlanAttened(isSuccess, errorCode, errMsg, attendedList);
                    }
                });
            }
        }
    }

    public void uploadSignHistorys() {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        List<SignHistoryDataBean> historyDatas = dbDaoHelper.getUnuploadSignHistorys(userBean.getUserid());
        for (SignHistoryDataBean historyData : historyDatas){
            if (historyData != null){
                String deviceId = historyData.getDeviceInfoId();
                DeviceInfoBean deviceInfoBean = null;
                if (deviceId != null && !deviceId.isEmpty()) {
                    deviceInfoBean = dbDaoHelper.getDeviceInfo(deviceId);
                    //uploadSignHistory(historyData, deviceInfoBean);
                }
            }
        }
    }

    public void uploadSignHistory(Context context, final SignHistoryDataBean signHistoryData, final DeviceInfoBean deviceInfoBean){
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null){
            signController.signToday(context, userBean.getUserid(), signHistoryData, deviceInfoBean, null, new SignCallBack() {
                @Override
                public void onSignToday(boolean isSuccess, int errorCode, String errMsg, int section, int plannum, List<String> planIds) {
                    super.onSignToday(isSuccess, errorCode, errMsg, section, plannum, planIds);
                    if (isSuccess) {
                        dbDaoHelper.saveSignHistoryData(signHistoryData);
                    }
                }
            });
        }
    }


    public interface signOffCallback{
        void onSignOff(boolean isSuccess, String errMsg, int errCode);
    }
}
