package handlers

import (
	"net/http"

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

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

func Add_product_material_to_routes(e *echo.Echo) {
	group := e.Group("/processMaterial")
	group.Use(middleware.AuthMiddleware)
	group.POST("/getPage", productMaterialGetPage)
	group.POST("/getList", productMaterialGetList)
	group.POST("/save", productMaterialSave)
	group.POST("/update", productMaterialUpdate)
	group.POST("/remove", productMaterialRemove)

}

func productMaterialGetPage(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.ProductMaterial{})
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	list := utils.ConvertInterface[[]models.ProductMaterial](result.Records)
	if len(list) == 0 {
		list = []models.ProductMaterial{}
	}

	result.Records = list
	return c.JSON(http.StatusOK, result)

}

func productMaterialGetList(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.ProductMaterial{})
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	list := utils.ConvertInterface[[]models.ProductMaterial](result)
	if len(list) == 0 {
		return c.JSON(http.StatusOK, []string{})
	}
	return c.JSON(http.StatusOK, list)
}

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

	material := new(models.ProductMaterial)
	if err := c.Bind(material); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	sess, _ := session.Get("auth_session", c)
	err_msg := productMaterial_generateCode(material, tx)
	if err_msg != "" {
		tx.Rollback()
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse(err_msg, ""))
	}

	user_id, ok := sess.Values["user_id"].(int64)
	if !ok {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("用户请先登录", ""))
	}

	status := models.Status_Enable
	material.Status = &status
	material.CreateId = &user_id
	err := services.JdbcClient.JdbcInsert(material, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	tx.Commit()
	return c.JSON(http.StatusOK, material)
}

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

	material := new(models.ProductMaterial)
	if err := c.Bind(material); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	sess, _ := session.Get("auth_session", c)
	user_id, ok := sess.Values["user_id"].(int64)
	if !ok {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("用户请先登录", ""))
	}
	material.UpdateId = &user_id
	err := services.JdbcClient.JdbcUpdateById(material, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	bom := new(models.ProductBom)
	bom.MaterialName = material.Name
	paramMap := map[string]interface{}{
		"materialCode": material.Code,
	}
	err = services.JdbcClient.JdbcUpdate(bom, paramMap, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	tx.Commit()
	return c.JSON(http.StatusOK, material)
}

func productMaterialRemove(c echo.Context) error {
	material := new(models.ProductMaterial)
	if err := c.Bind(material); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	err := services.JdbcClient.GetJdbcModelById(material)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	bom := new(models.ProductBom)
	bom.MaterialCode = material.Code
	count, err := services.JdbcClient.GetJdbcCount(bom)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	if count > 0 {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("该物料在bom管理中存在，无法删除", ""))
	}

	err = services.JdbcClient.JdbcRemoveById(material)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	return c.JSON(http.StatusOK, material)
}

func productMaterial_generateCode(model *models.ProductMaterial, 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.ProductMaterial)
		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_Product_Material, *model.TenantId, tx)
			if err != nil {
				return "自动生成编码失败"
			}
			modelParam := new(models.ProductMaterial)
			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 ""
}
