package api

import (
	"box-cost/db/repo"
	"fmt"

	"github.com/gin-gonic/gin"
)

// RegRouters 注册路由
func RegRouters(svc *Service) {

	boxcost := svc.NewGinRouter("/" + svc.Conf.Name)
	boxcost.group.Use(Logger())

	//数据存储
	boxcost.POST("/save/policy", ServiceObsUploadPolicy)
	boxcost.GET("/printr", Printr)
	boxcost.GET("/removeSyncBill", RemovePlanSyncBill)
	boxcost.GET("/callback", callback)
	boxcost.POSTJWT("/diffUpdatePlanTest", DiffUpdatePlanTest)
	boxcost.POSTJWT("/diffUpdateProduceTest", DiffUpdateProduceTest)
	// boxcost.GET("/printDiff", PrintDiff)
	boxcost.GETJWT("/bill/history/list", BillHistoryList)
	boxcost.GETJWT("/plan/history/list", PlanHistoryList)
	boxcost.GETJWT("/bill/history/detail/:id", GetBillHistory)
	boxcost.GETJWT("/plan/history/detail/:id", GetPlanHistory)
	boxcost.POSTJWT("/download/plan/track", DownloadPlanTrack)

	PlanTrack(boxcost)

	// 材料管理
	Material(boxcost)

	// 工艺管理
	Craft(boxcost)

	// 供应商管理
	Supplier(boxcost)

	// 供应商价格管理
	SupplierPrice(boxcost)

	// 包装管理
	Pack(boxcost)

	// 生产计划管理
	ProductPlan(boxcost)

	//材料采购单据管理
	Bill(boxcost)

	//加工单据
	BillProduce(boxcost)

	//成品采购
	BillProduct(boxcost)

	//设置
	Setting(boxcost)

	// 签名管理
	Signature(boxcost)

	// 统计报表
	Report(boxcost)

	// 成品采购管理
	Product(boxcost)

	// 计划汇总
	Summary(boxcost)

	boxcost.GET("/apk/version", func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
		out, err := repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
			CollectName: "versions",
			Page:        1,
			Size:        10,
			Sort:        repo.Map{"releaseDate": -1},
		})
		c.JSON(200, out.List)
		return nil, err
	})
}

func Logger() gin.HandlerFunc {

	return func(c *gin.Context) {
		// 开始时间
		// start := time.Now()
		// 处理请求
		c.Next()
		// 结束时间
		// end := time.Now()
		//执行时间
		// latency := end.Sub(start)

		path := c.Request.URL.Path

		clientIP := c.ClientIP()
		// method := c.Request.Method
		// statusCode := c.Writer.Status()

		out := fmt.Sprintf("%15s=> %s", clientIP, path)
		fmt.Println(out)
	}
}