package handlers

import (
	"net/http"

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

	"easydo-echo_win7/middleware"

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

func Add_purchase_order_to_routes(e *echo.Echo) {
	group := e.Group("/purchaseOrder")
	group.Use(middleware.AuthMiddleware)
	group.POST("/getPage", purchaseOrderGetPage)
	group.POST("/getList", purchaseOrderGetList)
	group.POST("/save", purchaseOrderSave)
	group.POST("/update", purchaseOrderUpdate)
	group.POST("/remove", purchaseOrderRemove)

}

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

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

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

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

		detailParam := new(models.PurchaseOrderDetail)
		detailParam.OrderId = model.ID
		result, err := services.JdbcClient.GetJdbcListByObject(detailParam)
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
		}
		detail_list := utils.ConvertInterface[[]models.PurchaseOrderDetail](result)

		for j := range detail_list {
			detail := detail_list[j]

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

			detail.ProductMaterial = material

			detail_list[j] = detail
		}
		model.ChildrenList = &detail_list

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

}

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

func purchaseOrderSave(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("用户请先登录", ""))
	}
	order := new(models.PurchaseOrder)
	if err := c.Bind(order); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	err_msg := purchaseOrder_generateCode(order, tx)
	if err_msg != "" {
		tx.Rollback()
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse(err_msg, ""))
	}
	status := models.Purchase_Order_Status_Pending
	order.Status = &status
	order.CreateId = &user_id
	services.JdbcClient.JdbcInsert(order, tx)

	detail_list := *order.ChildrenList
	for _, detail := range detail_list {
		detail.OrderId = order.ID
		err := services.JdbcClient.JdbcInsert(&detail, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			tx.Rollback()
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
	}

	purchase_plan := new(models.PurchasePlan)
	purchase_plan.ID = order.PurchasePlanId
	plan_status := models.Purchase_Plan_Status_Processing
	purchase_plan.Status = &plan_status
	err := services.JdbcClient.JdbcUpdateById(purchase_plan, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	if order.FileList == nil {
		tx.Commit()
		return c.JSON(http.StatusOK, order)
	}
	fileList := *order.FileList
	for _, file := range fileList {
		file.RefId = order.ID
		refType := models.File_Ref_Type_Purchase_Order
		file.RefType = &refType

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

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

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

	order := new(models.PurchaseOrder)
	if err := c.Bind(order); 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("用户请先登录", ""))
	}
	order.UpdateId = &user_id
	if order.ExpressNo != nil && *order.ExpressNo != "" {
		status := models.Purchase_Order_Status_Shipped
		order.Status = &status
	}
	err := services.JdbcClient.JdbcUpdateById(order, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	detail := new(models.PurchaseOrderDetail)
	detail.OrderId = order.ID
	err = services.JdbcClient.JdbcRemove(detail, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	detail_list := *order.ChildrenList
	for _, detail := range detail_list {
		detail.OrderId = order.ID
		err := services.JdbcClient.JdbcInsert(&detail, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			tx.Rollback()
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
	}

	if order.Status != nil && *order.Status == models.Purchase_Order_Status_Complete {
		err = services.JdbcClient.GetJdbcModel(order, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			tx.Rollback()
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
		purchase_plan := new(models.PurchasePlan)
		purchase_plan.ID = order.PurchasePlanId
		plan_status := models.Purchase_Plan_Status_Complete
		purchase_plan.Status = &plan_status
		err = services.JdbcClient.JdbcUpdateById(purchase_plan, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			tx.Rollback()
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
	}

	if order.FileList == nil {
		tx.Commit()
		return c.JSON(http.StatusOK, order)
	}

	fileList := *order.FileList
	for _, file := range fileList {
		file.RefId = order.ID
		refType := models.File_Ref_Type_Purchase_Order
		file.RefType = &refType

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

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

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

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

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

	minio_file := new(models.MinioFile)
	minio_file.RefId = order.ID
	refType := models.File_Ref_Type_Purchase_Order
	minio_file.RefType = &refType
	err = services.JdbcClient.JdbcRemove(minio_file, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	detail := new(models.PurchaseOrderDetail)
	detail.OrderId = order.ID
	err = services.JdbcClient.JdbcRemove(detail, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

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

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