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

// 产品入库相关代码

// ProductInventoryAdd 新增
// @Summary 新增
// @Tags 产品入库，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.ProductInventoryAddReq true "新增模型"
// @Success 200 {object} models.ErpInventoryProductOrder
// @Router /api/v1/inventory/product/add [post]
func ProductInventoryAdd(c *gin.Context) {
	req := &models.ProductInventoryAddReq{}
	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
	}

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

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

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

// ProductInventoryEdit 编辑
// @Summary 编辑
// @Tags 产品入库，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.ProductInventoryEditReq true "编辑模型"
// @Success 200 {object} models.ErpInventoryProductOrder
// @Router /api/v1/inventory/product/edit [post]
func ProductInventoryEdit(c *gin.Context) {
	req := &models.ProductInventoryEditReq{}
	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
	}

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

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

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

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

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

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

// ProductInventoryDelete 删除
// @Summary 删除
// @Tags 产品入库，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.ProductInventoryDeleteReq true "删除模型"
// @Success 200 {object} app.Response
// @Router /api/v1/inventory/product/delete [post]
func ProductInventoryDelete(c *gin.Context) {
	req := &models.ProductInventoryDeleteReq{}
	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
	}

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

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

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

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

// ProductInventoryList 产品入库列表
// @Summary 产品入库列表
// @Tags 产品入库，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.ProductInventoryListReq true "产品入库列表模型"
// @Success 200 {object} models.ProductInventoryListResp
// @Router /api/v1/inventory/product/list [post]
func ProductInventoryList(c *gin.Context) {
	req := &models.ProductInventoryListReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		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
}

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

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

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

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

	var productCommodities []models.ErpInventoryProductCommodity
	err = orm.Eloquent.Table("erp_inventory_product_commodity").Where("product_order_id=?", productOrder.ID).
		Find(&productCommodities).Error
	if err != nil {
		logger.Error("product commodities err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, "获取失败")
		return
	}

	productOrder.Commodities = productCommodities
	app.OK(c, productOrder, "查询成功")
	return
}

// ProductInventoryGetIMEI 系统生成串码
// @Summary 系统生成串码
// @Tags 产品入库，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.ProductInventoryGetIMEIReq true "系统生成串码模型"
// @Success 200 {object} models.ProductInventoryGetIMEIResp
// @Router /api/v1/inventory/product/getIMEI [post]
func ProductInventoryGetIMEI(c *gin.Context) {
	req := &models.ProductInventoryGetIMEIReq{}
	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
	}

	// 检查商品是否为串码商品，如果是，则判断是否为系统自动生成串码
	commodity, err := models.GetCommodity(req.CommodityId)
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, "获取失败")
		return
	}
	if commodity.ID == 0 {
		app.Error(c, http.StatusBadRequest, err, "获取失败：商品id有误，未查询到商品信息")
		return
	}
	if commodity.IMEIType == models.NoIMEICommodity { // 非串码商品
		app.Error(c, http.StatusBadRequest, errors.New("获取失败：该商品是非串码商品"), "获取失败：该商品是非串码商品")
		return
	}

	imei, err := models.GenerateSerialCode(commodity.ErpCategoryId, nil)
	if err != nil {
		logger.Error("GenerateIMEI err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, "获取失败")
		return
	}

	var resp models.ProductInventoryGetIMEIResp
	resp.IMEI = imei

	app.OK(c, resp, "获取成功")
	return
}
