package report

import (
	"encoding/json"
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/common/contants"
	"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/task/base"
	"sync"
	"time"
)

var (
	updateTaskName base.TaskType = "ReportUpdateSyncTask"
	updateCron                   = "0/10 * * * * *"
)

// Execute Task ETA取研报的数据
func (re *ReportUpdateTask) Execute(taskDetail *base.TaskDetail) error {
	logger.Info(contants.TaskFormat, "更新研报库开始")
	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		defer wg.Done()
		var etaReportList []eta.ETAReport
		etaReportList, err := eta.GetUpdateETAReports()
		if err != nil {
			logger.Error("获取ETA研报列表失败：%v", err)
		}
		if len(etaReportList) > 0 {
			var list []byte
			list, err = json.Marshal(etaReportList)
			if err == nil {
				taskDetail.Content = string(list)
			}
			err = report.SyncETAReportList(etaReportList)
			if err != nil {
				logger.Error("同步ETA研报列表失败：%v", err)
			}
		}
		logger.Info(contants.TaskFormat, "同步ETA研报库结束")
	}()
	go func() {
		defer wg.Done()
		var htReportList []ht.HTReport
		etaReportList, err := ht.GetUpdateHTReports()
		if err != nil {
			logger.Error("获取ETA研报列表失败：%v", err)
		}
		if len(etaReportList) > 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.SyncHTReportList(htReportList)
			if err != nil {
				logger.Error("同步ETA研报列表失败：%v", err)
			}
			if stop {
				logger.Info(contants.TaskFormat, "同步HT研报库结束")
			}
		} else {
			logger.Info(contants.TaskFormat, "同步ETA研报库结束")
		}
	}()
	wg.Wait()
	return nil
}

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
	}
}

type ReportUpdateTask struct {
}

func init() {
	reportTask := base.NewTask(updateTaskName, updateCron, new(ReportUpdateTask), base.DEV)
	base.RegisterTask(&reportTask)
}
