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"
)

// 库存变动相关代码

// InventoryChangeAdd 新增
// @Summary 新增
// @Tags 库存变动，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryChangeAddReq true "新增模型"
// @Success 200 {object} models.ErpInventoryChangeOrder
// @Router /api/v1/inventory/change/add [post]
func InventoryChangeAdd(c *gin.Context) {
	req := &models.InventoryChangeAddReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, http.StatusBadRequest, errors.New("param 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
	}

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

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

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

// InventoryChangeEdit 编辑
// @Summary 编辑
// @Tags 库存变动，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryChangeEditReq true "编辑模型"
// @Success 200 {object} models.ErpInventoryChangeOrder
// @Router /api/v1/inventory/change/edit [post]
func InventoryChangeEdit(c *gin.Context) {
	req := &models.InventoryChangeEditReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, http.StatusBadRequest, errors.New("param 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.StoreId)
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	if len(req.Commodities) == 0 {
		logger.Error("InventoryChangeEdit err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("请添加商品"), "请添加商品")
		return
	}

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

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

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

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

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

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

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

	var inventoryChangeOrder models.ErpInventoryChangeOrder
	err = orm.Eloquent.Table("erp_inventory_change_order").Where("serial_number = ?", req.SerialNumber).
		Find(&inventoryChangeOrder).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, inventoryChangeOrder.StoreId)
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

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

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

	begin := orm.Eloquent.Begin()
	// 1-删除采购订单表
	err = begin.Delete(inventoryChangeOrder).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.ErpInventoryChangeCommodity
	err = orm.Eloquent.Table("erp_inventory_change_commodity").Where("change_order_id = ?",
		inventoryChangeOrder.ID).Find(&commodities).Error
	if err != nil {
		logger.Error("query erp_inventory_change_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
}

// InventoryChangeList 库存变动列表
// @Summary 库存变动列表
// @Tags 库存变动，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.InventoryChangeListReq true "库存变动列表模型"
// @Success 200 {object} models.InventoryChangeListResp
// @Router /api/v1/inventory/change/list [post]
func InventoryChangeList(c *gin.Context) {
	req := &models.InventoryChangeListReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		//logger.Error(err)
		app.Error(c, http.StatusBadRequest, errors.New("param 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
}

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

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

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

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

	var changeCommodities []models.ErpInventoryChangeCommodity
	err = orm.Eloquent.Table("erp_inventory_change_commodity").Where("change_order_id=?", changeOrder.ID).
		Find(&changeCommodities).Error
	if err != nil {
		logger.Error("change commodities err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, "获取失败")
		return
	}

	changeOrder.Commodities = models.MergeChangeCommodities(changeCommodities)
	app.OK(c, changeOrder, "查询成功")
	return
}
