package inventorymanage

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/logger"
	"go-admin/tools"
	"go-admin/tools/app"
	"net/http"
)

// 库存调拨相关代码

// InventoryAllotAdd 新增
// @Summary 新增
// @Tags 库存调拨，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryAllotAddReq true "新增模型"
// @Success 200 {object} models.ErpInventoryAllotOrder
// @Router /api/v1/inventory/allot/add [post]
func InventoryAllotAdd(c *gin.Context) {
	req := &models.InventoryAllotAddReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误:"+err.Error())
		return
	}

	err := tools.Validate(req) //必填参数校验
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	sysUser, err := models.GetSysUserByCtx(c)
	if err != nil {
		logger.Error("sys user err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	// 校验入参门店是否包含在用户所有门店中，是否过期
	if !(tools.GetRoleName(c) == "admin" || tools.GetRoleName(c) == "系统管理员") {
		if !models.CheckUserStore(req.DeliverStoreId, sysUser) {
			app.Error(c, http.StatusInternalServerError, errors.New("操作失败：您没有该门店权限"),
				"操作失败：您没有该门店权限")
			return
		}
	}

	inventoryProductOrder, err := models.AddInventoryAllot(req, sysUser)
	if err != nil {
		logger.Error("InventoryAllotAdd err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "新增失败:"+err.Error())
		return
	}

	app.OK(c, inventoryProductOrder, "新增成功")
	return
}

// InventoryAllotEdit 编辑
// @Summary 编辑
// @Tags 库存调拨，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryAllotEditReq true "编辑模型"
// @Success 200 {object} models.ErpInventoryAllotOrder
// @Router /api/v1/inventory/allot/edit [post]
func InventoryAllotEdit(c *gin.Context) {
	req := &models.InventoryAllotEditReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误:"+err.Error())
		return
	}

	err := tools.Validate(req) //必填参数校验
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	// 校验是否有入参门店权限
	err = models.AuthUserStore(c, req.DeliverStoreId)
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	inventoryProductOrder, err := models.EditAllotInventory(req)
	if err != nil {
		logger.Error("InventoryAllotEdit err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "编辑失败:"+err.Error())
		return
	}

	app.OK(c, inventoryProductOrder, "编辑成功")
	return
}

// InventoryAllotAudit 审核
// @Summary 审核
// @Tags 库存调拨，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryAllotAuditReq true "审核模型"
// @Success 200 {object} app.Response
// @Router /api/v1/inventory/allot/audit [post]
func InventoryAllotAudit(c *gin.Context) {
	req := &models.InventoryAllotAuditReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		//logger.Error(err)
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误:"+err.Error())
		return
	}

	err := models.AuditAllotInventory(req, c)
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "审核失败："+err.Error())
		return
	}

	app.OK(c, nil, "操作成功")
	return
}

// InventoryAllotDelete 删除
// @Summary 删除
// @Tags 库存调拨，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryAllotDeleteReq true "删除模型"
// @Success 200 {object} app.Response
// @Router /api/v1/inventory/allot/delete [post]
func InventoryAllotDelete(c *gin.Context) {
	req := &models.InventoryAllotDeleteReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		//logger.Error(err)
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误:"+err.Error())
		return
	}

	err := tools.Validate(req) //必填参数校验
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	var inventoryAllotOrder models.ErpInventoryAllotOrder
	err = orm.Eloquent.Table("erp_inventory_allot_order").Where("serial_number = ?", req.SerialNumber).
		Find(&inventoryAllotOrder).Error
	if err != nil {
		logger.Error("order err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "删除失败:"+err.Error())
		return
	}

	// 校验是否有入参门店权限
	err = models.AuthUserStore(c, inventoryAllotOrder.DeliverStoreId)
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	if inventoryAllotOrder.SerialNumber == "" {
		logger.Error("order is null")
		app.Error(c, http.StatusInternalServerError, err, "删除失败:订单不存在")
		return
	}

	// 仅待审核订单可删除
	if inventoryAllotOrder.State != models.ErpInventoryAllotOrderUnAudit {
		logger.Error("order err, inventoryAllotOrder.State is:", logger.Field("inventoryAllotOrder.State",
			inventoryAllotOrder.State))
		app.Error(c, http.StatusInternalServerError, err, "删除失败:仅待审核订单可删除")
		return
	}

	begin := orm.Eloquent.Begin()
	// 1-删除采购订单表
	err = begin.Delete(inventoryAllotOrder).Error
	if err != nil {
		begin.Rollback()
		logger.Error("order delete1 err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "删除失败:"+err.Error())
		return
	}

	// 2-删除采购订单商品表
	var commodities []models.ErpInventoryAllotCommodity
	err = orm.Eloquent.Table("erp_inventory_allot_commodity").Where("allot_order_id = ?",
		inventoryAllotOrder.ID).Find(&commodities).Error
	if err != nil {
		logger.Error("query erp_inventory_allot_commodity err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "删除失败:"+err.Error())
		return
	}

	if len(commodities) != 0 {
		err = begin.Delete(&commodities).Error
		if err != nil {
			begin.Rollback()
			logger.Error("更新商品订单信息-删除 error")
			app.Error(c, http.StatusInternalServerError, err, "删除失败:"+err.Error())
			return
		}
	}

	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Error("commit err:", logger.Field("err", err))
		return
	}

	app.OK(c, nil, "删除成功")
	return
}

// InventoryAllotList 库存调拨列表
// @Summary 库存调拨列表
// @Tags 库存调拨，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryAllotListReq true "库存调拨列表模型"
// @Success 200 {object} models.InventoryAllotListResp
// @Router /api/v1/inventory/allot/list [post]
func InventoryAllotList(c *gin.Context) {
	req := &models.InventoryAllotListReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		//logger.Error(err)
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误:"+err.Error())
		return
	}

	resp, err := req.List(c)
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "获取失败:"+err.Error())
		return
	}

	app.OK(c, resp, "查询成功")
	return
}

// InventoryAllotDetail 库存调拨详情
// @Summary 库存调拨详情
// @Tags 库存调拨，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryAllotDetailReq true "库存调拨详情模型"
// @Success 200 {object} models.ErpInventoryAllotOrder
// @Router /api/v1/inventory/allot/detail [post]
func InventoryAllotDetail(c *gin.Context) {
	req := &models.InventoryAllotDetailReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误:"+err.Error())
		return
	}

	var allotOrder models.ErpInventoryAllotOrder
	err := orm.Eloquent.Table("erp_inventory_allot_order").Where("serial_number=?", req.SerialNumber).Find(&allotOrder).Error
	if err != nil {
		logger.Error("allot order err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, "获取失败")
		return
	}
	if allotOrder.ID == 0 {
		logger.Error("allot commodities err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, fmt.Sprintf("未查询到订单[%s]", req.SerialNumber))
		return
	}

	sysUser, err := models.GetSysUserByCtx(c)
	if err != nil {
		logger.Error("sys user err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	// 校验入参门店是否包含在用户所有门店中，是否过期
	if !(tools.GetRoleName(c) == "admin" || tools.GetRoleName(c) == "系统管理员") {
		if !models.CheckUserStore(allotOrder.DeliverStoreId, sysUser) &&
			!models.CheckUserStore(allotOrder.ReceiveStoreId, sysUser) {
			app.Error(c, http.StatusInternalServerError, errors.New("操作失败：您没有该门店权限"),
				"操作失败：您没有该门店权限")
			return
		}
	}

	// 校验时间，如果为01-01-01 08:05，则赋值为空
	if allotOrder.MakerTime != nil && allotOrder.MakerTime.IsZero() {
		allotOrder.MakerTime = nil
	}
	if allotOrder.AuditTime != nil && allotOrder.AuditTime.IsZero() {
		allotOrder.AuditTime = nil
	}

	var allotCommodities []models.ErpInventoryAllotCommodity
	err = orm.Eloquent.Table("erp_inventory_allot_commodity").Where("allot_order_id=?", allotOrder.ID).
		Find(&allotCommodities).Error
	if err != nil {
		logger.Error("allot commodities err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, "获取失败")
		return
	}

	mergeCommodities := models.MergeCommodities(allotCommodities)
	allotOrder.Commodities = mergeCommodities

	// 查询商品的库存数量
	allotOrder.Commodities, _ = models.UpdateStockCounts(mergeCommodities, allotOrder.DeliverStoreId)

	app.OK(c, allotOrder, "查询成功")
	return
}

// InventoryAllotDeliver 调拨发货
// @Summary 调拨发货
// @Tags 库存调拨，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryAllotDeliverReq true "调拨发货模型"
// @Success 200 {object} app.Response
// @Router /api/v1/inventory/allot/deliver [post]
func InventoryAllotDeliver(c *gin.Context) {
	req := &models.InventoryAllotDeliverReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		//logger.Error(err)
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误:"+err.Error())
		return
	}

	err := models.DeliverAllotInventory(req, c)
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "操作失败:"+err.Error())
		return
	}

	app.OK(c, nil, "操作成功")
	return
}

// InventoryAllotReceive 调拨收货
// @Summary 调拨收货
// @Tags 库存调拨，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryAllotReceiveReq true "调拨收货模型"
// @Success 200 {object} app.Response
// @Router /api/v1/inventory/allot/receive [post]
func InventoryAllotReceive(c *gin.Context) {
	req := &models.InventoryAllotReceiveReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		//logger.Error(err)
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误:"+err.Error())
		return
	}

	err := models.ReceiveAllotInventory(req, c)
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "操作失败:"+err.Error())
		return
	}

	app.OK(c, nil, "操作成功")
	return
}
