package main

import (
	"easydo-echo_win7/config"
	"easydo-echo_win7/handlers"
	"easydo-echo_win7/services"

	"log"

	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func main() {
	conf, err := config.Load("./config/config-dev.yaml")
	if err != nil {
		println("配置文件加载失败")
	}
	// 初始化服务
	go services.InitCaptcha()
	go services.InitMyRedis(
		conf.Redis.Addr,
		conf.Redis.Password,
		conf.Redis.DB,
	)
	go services.InitMysqlPool(
		conf.Database.User,
		conf.Database.Password,
		conf.Database.Host,
		conf.Database.Port,
		conf.Database.Name,
		conf.Database.Log,
	)
	go services.InitMinioServie(
		conf.Minio.Addr,
		conf.Minio.User,
		conf.Minio.Password,
		conf.Minio.UseSSL,
	)

	// 创建Echo实例
	e := echo.New()

	// 配置中间件
	if conf.Server.WebLog {
		// e.Use(middleware.LoggerWithConfig())
		e.Use(middleware.BodyDump(func(c echo.Context, reqBody, resBody []byte) {
			log.Printf("URI: \033[34m%s\033[0m, Agent: %s, remote_ip: %s\n Request Body: \033[31m%s\033[0m\n Response Body: \033[32m%s\033[0m",
				c.Request().URL.Path, c.Request().UserAgent(), c.Request().RemoteAddr, string(reqBody), string(resBody))
		}))
	}

	// e.Use(middleware.Recover())
	e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins: []string{"*"},
		AllowMethods: []string{echo.GET, echo.POST, echo.PUT, echo.DELETE, echo.OPTIONS},
		AllowHeaders: []string{echo.HeaderContentType, echo.HeaderAuthorization},
	}))

	// 配置Session中间件
	e.Use(session.Middleware(services.SessionStore()))

	// 定义路由
	setupRoutes(e)

	// 启动服务器
	port := conf.Server.Port
	log.Printf("服务器启动在 http://%s", port)

	if err := e.Start(port); err != nil {
		e.Logger.Fatal(err)
	}
}

func setupRoutes(e *echo.Echo) {
	handlers.Add_auth_to_routes(e)
	handlers.Add_menu_to_routes(e)
	handlers.Add_role_to_routes(e)
	handlers.Add_dept_to_routes(e)
	handlers.Add_user_to_routes(e)
	handlers.Add_role_menu_to_routes(e)

	handlers.Add_device_to_routes(e)
	handlers.Add_tenant_to_routes(e)
	handlers.Add_minio_to_routes(e)
	handlers.Add_customer_to_routes(e)
	handlers.Add_quality_inspect_program_to_routes(e)
	handlers.Add_product_material_to_routes(e)
	handlers.Add_product_bom_to_routes(e)

	handlers.Add_process_stage_to_routes(e)
	handlers.Add_process_route_to_routes(e)

	handlers.Add_sale_plan_to_routes(e)
	handlers.Add_sale_order_to_routes(e)
	handlers.Add_sale_performance_to_routes(e)

	handlers.Add_purchase_plan_to_routes(e)
	handlers.Add_purchase_order_to_routes(e)

	handlers.Add_warehouse_to_routes(e)
	handlers.Add_warehouse_material_to_routes(e)

	handlers.Add_product_plan_to_routes(e)
	handlers.Add_product_pre_plan_to_routes(e)
}
