package util

import (
	qu "qfw/util"
	"strings"
	"time"
)

var Workfig map[string]map[string]string
var morning_on, morning_off, afternoon_on, afternoon_off string

func InitWorkfig() {
	morning_on = Workfig["morning"]["on"]
	morning_off = Workfig["morning"]["off"]
	afternoon_on = Workfig["afternoon"]["on"]
	afternoon_off = Workfig["afternoon"]["off"]
}

//获取完成时间
func CompleteTime(urgent string) int64 {
	duration := Workfig["urgency"][urgent]
	do := int64(0)
	if strings.Contains(duration, "h") { //单位为小时,需要计算
		do = qu.Int64All(strings.Replace(duration, "h", "", -1)) * int64(3600)
	} else {
		return 0
	}
	endtime := time.Now()
	for i := 0; i < 100; i++ { //轮询调度直到，剩余工时为零
		if do > 0 {
			do, endtime = getWorkTime(do, endtime)
		} else {
			break
		}
	}
	return endtime.Unix()
}

/*计算剩余工时，和完成时间
do:工时
t:时间
spare:剩余工时
endtime:完成时间
*/
func getWorkTime(do int64, t time.Time) (spare int64, endtime time.Time) {
	mon, _ := time.ParseInLocation(qu.Date_Full_Layout, t.Format(qu.Date_Short_Layout)+" "+morning_on+":00", time.Local)
	moff, _ := time.ParseInLocation(qu.Date_Full_Layout, t.Format(qu.Date_Short_Layout)+" "+morning_off+":00", time.Local)
	aon, _ := time.ParseInLocation(qu.Date_Full_Layout, t.Format(qu.Date_Short_Layout)+" "+afternoon_on+":00", time.Local)
	aoff, _ := time.ParseInLocation(qu.Date_Full_Layout, t.Format(qu.Date_Short_Layout)+" "+afternoon_off+":00", time.Local)
	if t.Unix() <= mon.Unix() {
		//早上上班前
		work := moff.Unix() - mon.Unix()
		if work >= do {
			spare = 0
			endtime = mon.Add(time.Duration(do) * time.Second)
		} else {
			spare = do - work
			endtime = moff
		}
	} else if t.Unix() >= mon.Unix() && t.Unix() < moff.Unix() {
		//中午下班前
		work := moff.Unix() - t.Unix()
		if work >= do {
			spare = 0
			endtime = t.Add(time.Duration(do) * time.Second)
		} else {
			spare = do - work
			endtime = moff
		}
	} else if t.Unix() >= moff.Unix() && t.Unix() < aon.Unix() {
		//下午上班前
		work := aoff.Unix() - aon.Unix()
		if work >= do {
			spare = 0
			endtime = aon.Add(time.Duration(do) * time.Second)
		} else {
			spare = do - work
			endtime = aoff
		}
	} else if t.Unix() >= aon.Unix() && t.Unix() <= aoff.Unix() {
		//下午下班前
		work := aoff.Unix() - t.Unix()
		if work >= do {
			spare = 0
			endtime = t.Add(time.Duration(do) * time.Second)
		} else {
			spare = do - work
			endtime = mon.AddDate(0, 0, 1)
		}
	} else {
		//下午下班
		endtime = mon.AddDate(0, 0, 1)
	}

	//判断星期天
	if endtime.Weekday().String() == "Sunday" {
		endtime = endtime.AddDate(0, 0, 1)
	} else if endtime.Weekday().String() == "Saturday" {
		endtime = endtime.AddDate(0, 0, 2)
	}
	return spare, endtime
}
