/**
* @Author: zou.yingbin
* @Create  : 2021/5/24 14:42
* @Modify  : 2021/5/24 14:42
 */

package mtpcache

import (
	"fmt"
	"mtp2_if/db"
	"sync"
	"time"
)

var vWeekMgr WeekDateMgr

// WeekDate 周日期信息
type WeekDate struct {
	CurDate   string `json:"curdate"  xorm:"'CurDate'"`     // 当前日期(yyyymmdd)
	BeginDate string `json:"begindate"  xorm:"'BeginDate'"` // 周开始日期(yyyy-mm-dd)
	EndDate   string `json:"enddate"  xorm:"'EndDate'"`     // 周结束日期(yyyy-mm-dd)
	Week      int32  `json:"week"  xorm:"'Week'"`           // 第几周
	WeekIW    string `json:"weekiw"  xorm:"'WeekIW'"`       // 周日期iw(yyyyiw)
}

// WeekDateMgr 周日期缓存
type WeekDateMgr struct {
	mtx  sync.RWMutex
	data map[string]WeekDate
}

func init() {
	go func() {
		time.Sleep(time.Second * 5)
		vWeekMgr.load("")
	}()
}

func (r *WeekDateMgr) load(curDate string) {
	var sqlId string
	if len(curDate) > 0 {
		// 查指定日期信息
		sqlId = "select" +
			"  '%v' curdate," +
			"  to_char(trunc(to_date('%v', 'yyyymmdd'), 'IW'), 'yyyymmdd') begindate," +
			"  to_char(trunc(to_date('%v', 'yyyymmdd'), 'IW') + 6, 'yyyymmdd') enddate," +
			"  to_char(to_date('%v', 'yyyymmdd'), 'yyyyiw') weekiw," +
			"  to_char(to_date('%v', 'yyyymmdd'), 'iw') week" +
			" from dual t"
		sqlId = fmt.Sprintf(sqlId, curDate, curDate, curDate, curDate, curDate)
	} else {
		// 查当前日期信息
		sqlId = "select" +
			"  to_char(sysdate, 'yyyymmdd') curdate," +
			"  to_char(trunc(to_date(to_char(sysdate, 'yyyymmdd'), 'yyyymmdd'), 'IW'), 'yyyymmdd') begindate," +
			"  to_char(trunc(to_date(to_char(sysdate, 'yyyymmdd'), 'yyyymmdd'), 'IW') + 6, 'yyyymmdd') enddate," +
			"  to_char(sysdate, 'yyyyiw') weekiw," +
			"  to_char(sysdate, 'iw') week" +
			" from dual t"
	}
	r.mtx.Lock()
	defer r.mtx.Unlock()
	sData := make([]WeekDate, 0)
	e := db.GetEngine()
	if e == nil {
		return
	}
	if err := e.SQL(sqlId).Find(&sData); err == nil {
		if r.data == nil {
			r.data = map[string]WeekDate{}
		}
		for i := range sData {
			r.data[sData[i].CurDate] = sData[i]
		}
	}
}

// WeekIW 获取yyyyiw
func (r *WeekDateMgr) WeekIW(curDate string) string {
	r.mtx.RLock()
	defer r.mtx.RUnlock()
	if d, ok := r.data[curDate]; ok {
		return d.WeekIW
	}
	return ""
}

// Get 获取周信息
func (r *WeekDateMgr) Get(curDate string) (WeekDate, bool) {
	r.mtx.RLock()
	defer r.mtx.RUnlock()
	if d, ok := r.data[curDate]; ok {
		return d, true
	}
	return WeekDate{}, false
}

// GetWeekInfo 获取周信息 curData(yyyymmdd)
func GetWeekInfo(curDate string) (WeekDate, bool) {
	if d, ok := vWeekMgr.Get(curDate); ok {
		return d, ok
	} else {
		vWeekMgr.load(curDate)
	}
	return vWeekMgr.Get(curDate)
}

// GetWeekIW 获取yyyyiw
func GetWeekIW(curDate string) string {
	if d := vWeekMgr.WeekIW(curDate); d != "" {
		return d
	} else {
		vWeekMgr.load(curDate)
	}
	return vWeekMgr.WeekIW(curDate)
}
