package main

import (
	"cicv-data-closedloop/amd64/web_server/handler"
	"cicv-data-closedloop/amd64/web_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() {
	go handler.ExamEndTicker() // 考试结束
	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)     // 考试开始
	examPrefix.POST("/begin", handler.Begin)   // 考试开始2
	examPrefix.POST("/end", handler.End)       // 考试结束2
	examPrefix.POST("/page", handler.Page)     // 分页查询
	examPrefix.POST("/report", handler.Report) // pdf下载
	monitorPrefix := projectPrefix.Group("/monitor")
	monitorPrefix.POST("/insert", handler.SaveDeviceMonitor)
	// 端口
	err := router.Run(":" + infra.ApplicationYaml.Web.Port)
	if err != nil {
		c_log.GlobalLogger.Error("程序崩溃,监听端口 "+infra.ApplicationYaml.Web.Port+" 失败:", err)
		os.Exit(-1)
	}
}