package handlers

import (
	"net/http"

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

	"easydo-echo_win7/middleware"

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

func Add_warehouse_material_to_routes(e *echo.Echo) {
	group := e.Group("/warehouseMaterial")
	group.Use(middleware.AuthMiddleware)
	group.POST("/getPage", warehouseMaterialGetPage)
	group.POST("/getList", warehouseMaterialGetList)
	group.POST("/save", warehouseMaterialSave)
	group.POST("/update", warehouseMaterialUpdate)
	// group.POST("/remove", warehouseMaterialRemove)

}

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

		material := new(models.ProductMaterial)
		material.Code = model.MaterialCode
		err = services.JdbcClient.GetJdbcModel(material)
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
		}
		model.ProductMaterial = material

		warehouse := new(models.Warehouse)
		warehouse.ID = model.WarehouseId
		err = services.JdbcClient.GetJdbcModelById(warehouse)
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
		}
		model.Warehouse = warehouse

		list[i] = model
	}
	result.Records = list
	return c.JSON(http.StatusOK, result)

}

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

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

	sess, _ := session.Get("auth_session", c)
	user_id, ok := sess.Values["user_id"].(int64)
	if !ok {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("用户请先登录", ""))
	}
	warehouse_material := new(models.WarehouseMaterial)
	if err := c.Bind(warehouse_material); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}

	status := models.Status_Enable
	warehouse_material.Status = &status
	warehouse_material.CreateId = &user_id
	services.JdbcClient.JdbcInsert(warehouse_material, tx)

	warehouse_record := new(models.WarehouseRecord)
	warehouse_record.MaterialCode = warehouse_material.MaterialCode
	record_type := models.Warehouse_Record_Type_In
	warehouse_record.Type = &record_type
	warehouse_record.CreateId = &user_id
	warehouse_record.Number = warehouse_material.Number
	warehouse_record.TenantId = warehouse_material.TenantId
	warehouse_record.ToWarehouseId = warehouse_material.WarehouseId
	err := services.JdbcClient.JdbcInsert(warehouse_record, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
	}
	tx.Commit()
	return c.JSON(http.StatusOK, warehouse_material)
}

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

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

	record := new(models.WarehouseRecord)
	record.MaterialCode = warehouse_material.MaterialCode
	record_type := ""
	if *exist_warehouse_material.LockedNumber < *warehouse_material.LockedNumber {
		record_type = models.Warehouse_Record_Type_Lock
	} else if *exist_warehouse_material.Number < *warehouse_material.Number {
		record_type = models.Warehouse_Record_Type_In
	} else if *exist_warehouse_material.Number > *warehouse_material.Number {
		record_type = models.Warehouse_Record_Type_Out
	} else {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("记录类型出现异常", ""))
	}

	record.Type = &record_type
	record.CreateId = &user_id
	record.Number = warehouse_material.Number
	record.TenantId = warehouse_material.TenantId
	record.ToWarehouseId = warehouse_material.WarehouseId
	err = services.JdbcClient.JdbcInsert(record, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
	}
	tx.Commit()
	return c.JSON(http.StatusOK, warehouse_material)
}

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

	warehouse_material := new(models.WarehouseMaterial)
	if err := c.Bind(warehouse_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("用户请先登录", ""))
	}
	err := services.JdbcClient.JdbcRemoveById(warehouse_material, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	record := new(models.WarehouseRecord)
	record.MaterialCode = warehouse_material.MaterialCode
	record_type := models.Warehouse_Record_Type_Out
	record.Type = &record_type
	record.CreateId = &user_id
	record.Number = warehouse_material.Number
	record.TenantId = warehouse_material.TenantId
	record.ToWarehouseId = warehouse_material.WarehouseId
	err = services.JdbcClient.JdbcInsert(record, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
	}
	tx.Commit()
	return c.JSON(http.StatusOK, warehouse_material)
}
