package main

import (
	"cicv-data-closedloop/amd64/score_server/handler"
	"cicv-data-closedloop/amd64/score_server/infra"
	"cicv-data-closedloop/common/config/c_db"
	"cicv-data-closedloop/common/config/c_log"
	"cicv-data-closedloop/common/gin/middleware"
	_ "embed"
	"github.com/gin-gonic/gin"
	_ "gopkg.in/yaml.v3"
	"os"
)

func init() {
	infra.InitApplication()
	c_log.InitLog(
		infra.ApplicationYaml.Log.Dir,
		infra.ApplicationYaml.Log.Prefix,
	)
	c_db.InitSqlxMysql(
		infra.ApplicationYaml.Mysql.Username,
		infra.ApplicationYaml.Mysql.Password,
		infra.ApplicationYaml.Mysql.Ip,
		infra.ApplicationYaml.Mysql.Port,
		infra.ApplicationYaml.Mysql.Dbname,
		infra.ApplicationYaml.Mysql.Charset,
	)
	c_db.InitSqlFilesMap(infra.ApplicationYaml.Mysql.SqlfileDir)
}

func main() {
	c_log.GlobalLogger.Info("配置文件为:", infra.ApplicationYaml)
	// 创建 gin 实例
	router := gin.Default()
	// 使用中间件
	router.Use(middleware.Cors())                                                                                // 解决cors
	router.Use(middleware.LogRequest())                                                                          // 请求日志打印
	router.Use(middleware.ValidateHeaders(infra.ApplicationYaml.Web.WhiteList, infra.ApplicationYaml.Web.Token)) // 全局请求头校验
	// 通过路由组设置全局前缀
	projectPrefix := router.Group(infra.ApplicationYaml.Web.RoutePrefix)
	{
		examPrefix := projectPrefix.Group("/exam")
		{
			examPrefix.POST("/tick", handler.Tick)       // 考试开始
			go handler.ExamEndTicker()                   // 考试结束
			examPrefix.POST("/display", handler.Display) // 云控展示线上评分
			examPrefix.POST("/page", handler.Page)       // 分页查询
			examPrefix.POST("/report", handler.Report)   // pdf下载
			examPrefix.POST("/offline", handler.Offline) // 录入线下成绩
		}
	}
	{
		monitorPrefix := router.Group("/web_server/monitor") // todo web_server会改成score_server,后续修改
		{
			monitorPrefix.POST("/insert", handler.SaveDeviceMonitor)
		}
	}
	{
		monitorPrefix := router.Group("/web_server/collect_limit") // todo web_server会改成score_server,后续修改
		{
			monitorPrefix.POST("/can_collect", handler.TriggerCollect)
		}
	}
	// 端口
	err := router.Run(":" + infra.ApplicationYaml.Web.Port)
	if err != nil {
		c_log.GlobalLogger.Error("程序崩溃,监听端口 "+infra.ApplicationYaml.Web.Port+" 失败:", err)
		os.Exit(-1)
	}
}