package handlers

import (
	"net/http"

	"easydo-echo_win7/models"
	"easydo-echo_win7/services"
	"easydo-echo_win7/utils"

	"github.com/jmoiron/sqlx"
	// "github.com/labstack/echo-contrib/session"
	"easydo-echo_win7/middleware"

	"github.com/labstack/echo/v4"
)

func Add_warehouse_to_routes(e *echo.Echo) {
	group := e.Group("/warehouse")
	group.Use(middleware.AuthMiddleware)
	group.POST("/getPage", warehouseGetPage)
	group.POST("/getList", warehouseGetList)
	group.POST("/save", warehouseSave)
	group.POST("/update", warehouseUpdate)
	group.POST("/remove", warehouseRemove)
}

func warehouseGetPage(c echo.Context) error {
	var paramMap map[string]interface{}
	if err := c.Bind(&paramMap); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	result, err := services.JdbcClient.GetJdbcPage(paramMap, models.Warehouse{})
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	list := utils.ConvertInterface[[]models.Warehouse](result.Records)
	if len(list) == 0 {
		list = []models.Warehouse{}
	}
	result.Records = list
	return c.JSON(http.StatusOK, result)

}

func warehouseGetList(c echo.Context) error {
	var paramMap map[string]interface{}
	if err := c.Bind(&paramMap); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	result, err := services.JdbcClient.GetJdbcList(paramMap, models.Warehouse{})
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	list := utils.ConvertInterface[[]models.Warehouse](result)
	if len(list) == 0 {
		return c.JSON(http.StatusOK, []models.Warehouse{})
	}
	return c.JSON(http.StatusOK, list)
}

func warehouseSave(c echo.Context) error {
	tx, _ := services.MYSQL_DB.Beginx()

	warehouse := new(models.Warehouse)
	if err := c.Bind(warehouse); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	err_msg := warehouse_generateCode(warehouse, tx)
	if err_msg != "" {
		tx.Rollback()
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse(err_msg, ""))
	}
	err := services.JdbcClient.JdbcInsert(warehouse, tx)
	if err != nil {
		tx.Rollback()
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	tx.Commit()
	return c.JSON(http.StatusOK, warehouse)
}

func warehouseUpdate(c echo.Context) error {
	warehouse := new(models.Warehouse)
	if err := c.Bind(warehouse); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	err := services.JdbcClient.JdbcUpdateById(warehouse)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	return c.JSON(http.StatusOK, warehouse)
}

func warehouseRemove(c echo.Context) error {
	tx, _ := services.MYSQL_DB.Beginx()

	warehouse := new(models.Warehouse)
	if err := c.Bind(warehouse); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}

	err := services.JdbcClient.JdbcRemoveById(warehouse, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	tx.Commit()
	return c.JSON(http.StatusOK, warehouse)
}

func warehouse_generateCode(model *models.Warehouse, tx *sqlx.Tx) string {
	sync := new(models.Synchronized)
	sync.Sync.Lock()
	defer sync.Sync.Unlock()

	if model.Code != nil && len(*model.Code) > 0 {
		modelParam := new(models.Warehouse)
		modelParam.Code = model.Code
		modelParam.TenantId = model.TenantId
		count, err := services.JdbcClient.GetJdbcCount(modelParam, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			return "SQL执行失败"
		}
		if count > 0 {
			return "编号已存在，请重新填写"
		}
	} else {
		for {
			code, err := services.GetFlowNo(models.Flow_No_Type_Warehouse, *model.TenantId, tx)
			if err != nil {
				return "自动生成编码失败"
			}
			modelParam := new(models.Warehouse)
			modelParam.Code = &code
			modelParam.TenantId = model.TenantId
			count, err := services.JdbcClient.GetJdbcCount(modelParam, tx)
			if err != nil {
				utils.PrintSqlErr(err)
				return "SQL执行失败"
			}
			if count == 0 {
				model.Code = &code
				break
			}
		}

	}
	return ""
}
