package com.brilliance.isc.common.taskdistributor.util;

import com.brilliance.isc.bo.TaskDistConfig;
import com.brilliance.isc.bo.TaskDistUser;
import com.brilliance.isc.common.taskdistributor.enums.WorkRank;
import com.brilliance.isc.common.taskdistributor.exception.TaskDistException;
import com.brilliance.mda.runtime.mda.util.Strings;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class TimeUtils {
    public static Time strToDate(String strDate) {
        String str = strDate;
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        Date d = null;
        Time time = null;
        try {
            d = format.parse(str);
            time = new Time(d.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return time;
    }

    public static boolean isModeTime(String startTime,String endTime){
        Time time1 = strToDate(startTime);
        Time time2 = strToDate(endTime);
        Date date  = new Date();
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        String str = df.format(date);
        Time curTime = strToDate(str);
        boolean isLunchtime = false;
        if(curTime.getTime() >time1.getTime() && curTime.getTime() < time2.getTime()){
            isLunchtime = true;
        }
        return isLunchtime;
    }

    /**
     * 是否临近下班时间且任务为占用时间较长的业务
     * @param config
     */
    public static boolean isNearToOffDutyTime(TaskDistConfig config, TaskDistUser usr){
        String  OffDutyTime = "";
        boolean isNearToOffDutyTime = false;
        if(Objects.equals(usr.getWorkRank(), WorkRank.MORNING_SHIFT.getValue())){
            OffDutyTime = config.getMorningEndTime();
        }else if(Objects.equals(usr.getWorkRank(),WorkRank.NIGHT_SHIFT.getValue())){
            OffDutyTime = config.getNightEndTime();
        }
        if(Objects.isNull(OffDutyTime) || Strings.isEmpty(OffDutyTime)){
           throw  new TaskDistException("请配置下班时间！");
        }

        //TODO 从数据库获取此时间
        int nearToOffDutyTime = config.getNearOffworkTime();
        Date date  = new Date();
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        String str = df.format(date);
        Time curTime = strToDate(str);
        if((curTime.getTime() + nearToOffDutyTime * 60 * 1000) > strToDate(OffDutyTime).getTime()){
            isNearToOffDutyTime = true;
        }
        return isNearToOffDutyTime;
    }

}
