package models

import (
	"fmt"
	"sync"
	"time"
)

var cstZone = time.FixedZone("CST", 8*3600)

const (
	//TimeFormat = "2006-01-02 15:04:05"

	DateFormat  = "2006-01-02"
	MDateFormat = "2006-01"
)

func TodayZeroFormat() string {
	return TodayZero().Format(TimeFormat)
}

func TodayZeroDateFormat() string {
	return TodayZero().Format(DateFormat)
}

func ZeroDateFormat(days int) string {
	return TodayZeroAddDays(days).Format(DateFormat)
}

func TodayZero() time.Time {
	t := time.Now()
	tm := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, cstZone)

	//return time.Now().In(cstZone)
	return tm
}

func TodayZeroAddDays(days int) time.Time {
	return TodayZero().AddDate(0, 0, days)
}

func YesterdayZero() time.Time {
	return TodayZeroAddDays(-1)
}

func Now() time.Time {
	return time.Now().In(cstZone)
}

func TimeFormatDate(stamp int64) string {
	return time.Unix(stamp, 0).Format(DateFormat)
}

func Yesterday() time.Time {
	return TodayAddDays(-1)
}

func TodayAddDays(days int) time.Time {
	return Now().AddDate(0, 0, days)
}

var fluxMutexMap map[string]*sync.Mutex

func GetFluxMutexMap() map[string]*sync.Mutex {
	if fluxMutexMap == nil {
		fluxMutexMap = make(map[string]*sync.Mutex, 0)
	}
	return fluxMutexMap
}

func GetFluxMutex(mutexKey string) *sync.Mutex {
	mutexMap := GetFluxMutexMap()
	if v, ok := mutexMap[mutexKey]; ok {
		return v
	} else {
		mutexMap[mutexKey] = new(sync.Mutex)
		return mutexMap[mutexKey]
	}
}

func ShareCardRetrieveCardAuditMutex(key string) *sync.Mutex {
	return GetFluxMutex(fmt.Sprintf("ShareCardRetrieveCardAudit:%s", key))
}

func InDayZero(day int) time.Time {
	t := time.Now()
	tm := time.Date(t.Year(), t.Month(), day, 0, 0, 0, 0, cstZone)
	return tm
}

func MonthDateAdd(month int) string {
	return Now().AddDate(0, month, 0).Format("2006-01")
}
