package main

import (
	_ "eta/eta_mini_ht_api/common/component"
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/common/contants"
	"eta/eta_mini_ht_api/common/exception"
	"eta/eta_mini_ht_api/domian/report"
	"eta/eta_mini_ht_api/models/eta"
	"eta/eta_mini_ht_api/models/ht"
	_ "eta/eta_mini_ht_api/routers"
	_ "eta/eta_mini_ht_api/task"
	"github.com/beego/beego/v2/server/web"
	"sync"
	"time"
)

func main() {
	if web.BConfig.RunMode == "dev" {
		web.BConfig.WebConfig.DirectoryIndex = true
		web.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
	}

	//web.ErrorHandler("*", exception.ControllerAdvice())
	web.BConfig.RecoverFunc = exception.PanicAdvice
	go func() {
		//内存数据预热预加载
		logger.Info("开始预加载数据")
		//初始化研报库
		initReport()
	}()
	logger.Info("初始化成功")
	web.Run()
}

func initReport() {
	var wg sync.WaitGroup
	wg.Add(2)
	logger.Info("开始初始化研报库")
	go func() {
		defer wg.Done()
		for {
			id, err := report.GetETALatestReportId()
			var etaReportList []eta.ETAReport
			etaReportList, err = eta.GetETAReports(id)
			if err != nil {
				logger.Error("获取ETA研报列表失败：%v", err)
			}
			if len(etaReportList) > 0 {
				err = report.InitETAReportList(etaReportList)
				if err != nil {
					logger.Error("同步ETA研报列表失败：%v", err)
				}
			} else {
				logger.Info(contants.TaskFormat, "同步ETA研报库结束")
				break
			}
		}
	}()
	go func() {
		defer wg.Done()
		for {
			id, err := report.GetHTLatestReportId()
			var htReportList []ht.HTReport
			htReportList, err = ht.GetHTReports(id)
			if err != nil {
				logger.Error("获取ETA研报列表失败：%v", err)
			}
			if len(htReportList) > 0 {
				for i := 0; i < len(htReportList); i++ {
					timestamp := int64(htReportList[i].PublishTime)
					t := time.UnixMilli(timestamp)
					htReportList[i].PublishedTime = t.Format(time.DateTime)
					plateId := htReportList[i].PlateId
					plate, err := ht.GetPermissionNameById(plateId)
					if err != nil || plate.ParentId == 0 {
						htReportList[i].PermissionName = htReportList[i].PlateName
					} else {
						PermissionName, err := getPermissionNameById(plate.ParentId)
						if err != nil {
							logger.Error("获取ETA研报列表失败：%v", err)
							htReportList[i].PermissionName = ""
						} else {
							htReportList[i].PermissionName = PermissionName
						}
					}
				}
				var stop bool
				stop, err = report.InitHTReportList(htReportList)
				if err != nil {
					logger.Error("同步ETA研报列表失败：%v", err)
					break
				}
				if stop {
					logger.Info(contants.TaskFormat, "同步HT研报库结束")
					break
				}
			} else {
				logger.Info(contants.TaskFormat, "同步HT研报库结束")
				break
			}
		}
	}()
	wg.Wait()
	logger.Info("初始化研报库完成")
}

func getPermissionNameById(id int) (name string, err error) {
	plate, err := ht.GetPermissionNameById(id)
	if err != nil {
		return
	}
	if plate.ParentId != 0 {
		return getPermissionNameById(plate.ParentId)
	} else {
		return plate.PlateName, nil
	}
}
