package models

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	orm "go-admin/common/global"
	"go-admin/logger"
	"go-admin/tools"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"math/rand"
	"time"
)

const (
	ErpInventoryProductOrderUnAudit  = 1 // 产品入库-待审核
	ErpInventoryProductOrderFinished = 2 // 产品入库-已完成
)

// ErpInventoryProductOrder 产品入库订单表
type ErpInventoryProductOrder struct {
	Model
	SerialNumber string                         `json:"serial_number" gorm:"index"` // 单据编号
	StoreId      uint32                         `json:"store_id" gorm:"index"`      // 门店id
	StoreName    string                         `json:"store_name"`                 // 门店名称
	HandlerId    uint32                         `json:"handler_id" gorm:"index"`    // 经手人id
	HandlerName  string                         `json:"handler_name"`               // 经手人名称
	MakerTime    *time.Time                     `json:"maker_time"`                 // 制单时间
	MakerId      uint32                         `json:"maker_id" gorm:"index"`      // 制单人id
	MakerName    string                         `json:"maker_name"`                 // 制单人名称
	AuditTime    *time.Time                     `json:"audit_time"`                 // 审核时间
	AuditorId    uint32                         `json:"auditor_id" gorm:"index"`    // 审核人id
	AuditorName  string                         `json:"auditor_name"`               // 审核人名称
	State        uint32                         `json:"state"`                      // 1-待审核 2-已完成
	TotalCount   uint32                         `json:"total_count"`                // 总数量
	TotalAmount  float64                        `json:"total_amount"`               // 总金额
	Commodities  []ErpInventoryProductCommodity `json:"commodities" gorm:"-"`       // 产品入库商品信息
}

// ErpInventoryProductCommodity 产品入库商品信息表
type ErpInventoryProductCommodity struct {
	Model
	ProductOrderId uint32  `json:"product_order_id" gorm:"index"` // 产品入库订单表id
	CommodityId    uint32  `json:"commodity_id" gorm:"index"`     // 商品id
	CommodityName  string  `json:"commodity_name"`                // 商品名称
	SupplierId     uint32  `json:"supplier_id" gorm:"index"`      // 供应商id
	SupplierName   string  `json:"supplier_name"`                 // 供应商名称
	IMEIType       uint32  `json:"imei_type"`                     // 1-无串码 2-串码
	IMEI           string  `json:"imei"`                          // 商品串码
	Count          uint32  `json:"count"`                         // 计划数量
	Price          float64 `json:"price"`                         // 采购单价
	EmployeePrice  float64 `json:"employee_price"`                // 员工成本价
	Amount         float64 `json:"amount"`                        // 金额
	Remark         string  `json:"remark"`                        // 备注
}

// ProductInventoryAddReq 新增产品入库入参
type ProductInventoryAddReq struct {
	StoreId     uint32                         `json:"store_id" binding:"required"`     // 门店id
	StoreName   string                         `json:"store_name" binding:"required"`   // 门店名称
	HandlerId   uint32                         `json:"handler_id" binding:"required"`   // 经手人id
	HandlerName string                         `json:"handler_name" binding:"required"` // 经手人名称
	Commodities []ErpInventoryProductCommodity `json:"commodities"  binding:"required"` // 产品入库商品信息
}

// ProductInventoryEditReq 编辑产品入库入参
type ProductInventoryEditReq struct {
	SerialNumber string `json:"serial_number" binding:"required"` // 单据编号
	ProductInventoryAddReq
}

// ProductInventoryAuditReq 审核入参
type ProductInventoryAuditReq struct {
	SerialNumber string `json:"serial_number" binding:"required"` // 单据编号
	State        int    `json:"state"  binding:"required"`        // 审核操作: 1-审核 2-取消审核
}

// ProductInventoryDeleteReq 删除入参
type ProductInventoryDeleteReq struct {
	SerialNumber string `json:"serial_number" binding:"required"` // 单据编号
}

// ProductInventoryListReq 查询产品入库列表入参
type ProductInventoryListReq struct {
	SerialNumber   string `json:"serial_number"`    // 单据编号
	StoreId        uint32 `json:"store_id"`         // 门店id
	HandlerId      uint32 `json:"handler_id"`       // 经手人id
	State          int    `json:"state"`            // 1-待审核 2-已完成
	AuditTimeStart string `json:"audit_time_start"` // 审核开始时间
	AuditTimeEnd   string `json:"audit_time_end"`   // 审核结束时间
	PageIndex      int    `json:"pageIndex"`        // 页码
	PageSize       int    `json:"pageSize"`         // 页面条数
}

// ProductInventoryListResp 查询产品入库列表出参
type ProductInventoryListResp struct {
	List      []ErpInventoryProductOrder `json:"list"`
	Total     int                        `json:"total"`     // 总条数
	PageIndex int                        `json:"pageIndex"` // 页码
	PageSize  int                        `json:"pageSize"`  // 页面条数
}

// ProductInventoryDetailReq  查询产品入库详情入参
type ProductInventoryDetailReq struct {
	SerialNumber string `json:"serial_number" binding:"required"` // 单据编号
}

// newProductInventorySn 生成产品入库订单号
func newProductInventorySn() string {
	nowTime := time.Now()
	rand.Seed(nowTime.UnixNano())
	max := 1
	for {
		if max > 5 {
			logger.Error("create NewProductInventorySn err")
			return ""
		}
		random := rand.Intn(9000) + 1000
		sn := fmt.Sprintf("%s%d", nowTime.Format("060102"), random)
		exist, err := QueryRecordExist(fmt.Sprintf("SELECT * FROM erp_inventory_product_order "+
			"WHERE serial_number='%s'", "cpr"+sn))
		if err != nil {
			logger.Error("exist sn err")
		}
		if !exist {
			return "cpr" + sn
		}

		max++
	}
}

// CheckProductInventoryParam 检查新增产品入库参数
func CheckProductInventoryParam(req *ProductInventoryAddReq, editFlag bool) error {
	if len(req.Commodities) == 0 {
		return errors.New("商品信息为空")
	}

	noIMEICommodityMap := make(map[uint32]bool, 0)
	IMEICommodityMap := make(map[string]bool, 0)
	for _, item := range req.Commodities {
		// 校验商品是否存在
		commodityInfo, err := GetCommodity(item.CommodityId)
		if err != nil {
			return err
		}
		if commodityInfo.Name == "" {
			return fmt.Errorf("商品[%s]不存在", item.CommodityName)
		}

		// 校验供应商是否存在
		supplierInfo, err := GetErpSupplier(item.SupplierId)
		if err != nil {
			return err
		}
		if supplierInfo.Name == "" {
			return fmt.Errorf("供应商[%s]不存在", item.SupplierName)
		}

		if editFlag {
			if item.ID == 0 {
				return fmt.Errorf("商品[%s]ID为空", item.CommodityName)
			}
		}

		// 校验采购单价
		if item.Price <= 0 {
			return fmt.Errorf("商品[%s]采购单价[%f]错误，需大于0", item.CommodityName, item.Price)
		}

		// 校验数量
		if item.Count <= 0 {
			return fmt.Errorf("商品[%s]数量[%d]错误，需大于0", item.CommodityName, item.Count)
		} else {
			if item.Count != 1 && item.IMEIType != NoIMEICommodity { // 串码商品数量不为1，则报错
				return fmt.Errorf("串码商品[%s]数量[%d]错误，需为1", item.CommodityName, item.Count)
			}
		}

		// 校验金额
		if item.Amount <= 0 {
			return fmt.Errorf("商品[%s]金额[%f]错误，需大于0", item.CommodityName, item.Amount)
		}

		// 校验员工成本价
		if item.EmployeePrice <= 0 {
			return fmt.Errorf("商品[%s]员工成本价[%f]错误，需大于0", item.CommodityName, item.EmployeePrice)
		}

		// 校验数量和金额是否对应
		if float64(item.Count)*item.Price != item.Amount {
			return fmt.Errorf("商品[%s]数据有误，数量和金额不符", item.CommodityName)
		}

		// 校验串码类型
		switch item.IMEIType {
		case 1, 2, 3:
			// 串码商品校验串码是否为空
			if item.IMEIType != NoIMEICommodity && item.IMEI == "" {
				return fmt.Errorf("[%s]是串码商品，其串码不能为空", item.CommodityName)
			}
		default:
			return fmt.Errorf("商品[%s]串码类型[%d]错误", item.CommodityName, item.IMEIType)
		}

		if item.IMEIType == NoIMEICommodity {
			_, ok := noIMEICommodityMap[item.CommodityId]
			if !ok {
				noIMEICommodityMap[item.CommodityId] = true
			} else {
				return fmt.Errorf("商品[%s]重复，相同的非串码商品只能有1条数据", item.CommodityName)
			}
		} else {
			_, ok := IMEICommodityMap[item.IMEI]
			if !ok {
				// 如果该商品是串码商品，判断其串码是否会重复
				if item.IMEI != "" {
					exist, err := QueryRecordExist(fmt.Sprintf("SELECT * FROM erp_stock_commodity WHERE FIND_IN_SET('%s', imei) > 0", item.IMEI))
					if err != nil {
						logger.Error("exist sn err")
					}
					if exist {
						return fmt.Errorf("串码有重复项请修改[%s]", item.IMEI)
					}
				}
				IMEICommodityMap[item.IMEI] = true
			} else {
				return fmt.Errorf("串码[%s]有重复项", item.IMEI)
			}
		}
	}

	return nil
}

// AddProductInventory 新增产品入库
func AddProductInventory(req *ProductInventoryAddReq, sysUser *SysUser) (*ErpInventoryProductOrder, error) {
	// 检查新增产品入库信息
	if err := CheckProductInventoryParam(req, false); err != nil {
		return nil, err
	}

	var err error
	nowTime := time.Now()

	// 计算产品入库的总数量和总金额
	var nTotalCount uint32
	var nTotalAmount float64
	for i, _ := range req.Commodities {
		nTotalCount += req.Commodities[i].Count   // 数量
		nTotalAmount += req.Commodities[i].Amount // 金额
	}

	// 组合产品入库订单数据
	inventoryProductOrder := &ErpInventoryProductOrder{
		SerialNumber: newProductInventorySn(),
		StoreId:      req.StoreId,
		StoreName:    req.StoreName,
		HandlerId:    req.HandlerId,
		HandlerName:  req.HandlerName,
		MakerTime:    &nowTime,
		MakerId:      uint32(sysUser.UserId),
		MakerName:    sysUser.NickName,
		State:        ErpInventoryProductOrderUnAudit,
		TotalCount:   nTotalCount,
		TotalAmount:  nTotalAmount,
	}

	// 创建产品入库订单
	begin := orm.Eloquent.Begin()
	err = begin.Create(inventoryProductOrder).Error
	if err != nil {
		begin.Rollback()
		logger.Error("create product order err:", logger.Field("err", err))
		return nil, err
	}

	// 创建产品入库商品信息，添加产品入库订单id
	for i, _ := range req.Commodities {
		req.Commodities[i].ProductOrderId = inventoryProductOrder.ID
		err = begin.Create(&req.Commodities[i]).Error
		if err != nil {
			begin.Rollback()
			logger.Error("create product commodity err:", logger.Field("err", err))
			return nil, err
		}
	}

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

	return inventoryProductOrder, nil
}

// EditProductInventory  编辑产品入库
func EditProductInventory(req *ProductInventoryEditReq) (*ErpInventoryProductOrder, error) {
	// 查询订单信息
	var inventoryProductOrder ErpInventoryProductOrder
	err := orm.Eloquent.Table("erp_inventory_product_order").Where("serial_number = ?", req.SerialNumber).
		Find(&inventoryProductOrder).Error
	if err != nil {
		logger.Error("product order err:", logger.Field("err", err))
		return nil, err
	}

	// 未找到订单
	if inventoryProductOrder.ID == 0 {
		return nil, fmt.Errorf("未找到该订单，请检查单据编号[%s]", req.SerialNumber)
	}

	if inventoryProductOrder.State != ErpInventoryProductOrderUnAudit { // 只有待审核的订单才能编辑
		return nil, errors.New("订单不是待审核状态")
	}

	// 检查新增产品入库信息
	if err = CheckProductInventoryParam(&req.ProductInventoryAddReq, true); err != nil {
		return nil, err
	}

	// 计算产品入库的总数量和总金额
	var nTotalCount uint32
	var nTotalAmount float64
	for i, _ := range req.Commodities {
		nTotalCount += req.Commodities[i].Count   // 数量
		nTotalAmount += req.Commodities[i].Amount // 金额
	}

	begin := orm.Eloquent.Begin()
	// 1-更新产品订单信息
	inventoryProductOrder.StoreId = req.StoreId
	inventoryProductOrder.StoreName = req.StoreName
	inventoryProductOrder.HandlerId = req.HandlerId
	inventoryProductOrder.HandlerName = req.HandlerName
	inventoryProductOrder.TotalCount = nTotalCount
	inventoryProductOrder.TotalAmount = nTotalAmount

	err = begin.Model(&ErpInventoryProductOrder{}).Where("id = ?", inventoryProductOrder.ID).
		Omit("created_at").Save(inventoryProductOrder).Error
	if err != nil {
		begin.Rollback()
		logger.Error("update erp_order err:", logger.Field("err", err))
		return nil, err
	}

	// 2-更新产品订单商品表
	err = updateProductCommodityData(begin, inventoryProductOrder.ID, req)
	if err != nil {
		begin.Rollback()
		logger.Error("update erp_purchase_commodity err:", logger.Field("err", err))
		return nil, err
	}

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

	return &inventoryProductOrder, nil
}

// updateProductCommodityData 更新采购订单商品信息
func updateProductCommodityData(gdb *gorm.DB, orderId uint32, req *ProductInventoryEditReq) error {
	// 查询现有的零售订单信息
	var commodities []ErpInventoryProductCommodity
	err := orm.Eloquent.Table("erp_inventory_product_commodity").Where("product_order_id = ?", orderId).Find(&commodities).Error
	if err != nil {
		logger.Error("query erp_inventory_product_commodity err:", logger.Field("err", err))
		return err
	}

	var newCommodities []ErpInventoryProductCommodity
	var deletedCommodities []ErpInventoryProductCommodity
	var matchingCommodities []ErpInventoryProductCommodity
	// 找到新增的商品
	for i, reqCommodity := range req.Commodities {
		// 订单商品表信息添加零售订单id
		req.Commodities[i].ProductOrderId = orderId

		var found bool
		for _, dbCommodity := range commodities {
			if reqCommodity.CommodityId == dbCommodity.CommodityId && reqCommodity.ID == dbCommodity.ID {
				found = true
				break
			}
		}
		if !found {
			reqCommodity.ID = 0
			newCommodities = append(newCommodities, reqCommodity)
		}
	}

	// 找到删除的商品
	for _, dbCommodity := range commodities {
		var found bool
		for _, reqCommodity := range req.Commodities {
			if reqCommodity.CommodityId == dbCommodity.CommodityId && reqCommodity.ID == dbCommodity.ID {
				found = true
				// 找到匹配的商品，加入匹配列表
				matchingCommodities = append(matchingCommodities, reqCommodity)
				break
			}
		}
		if !found {
			deletedCommodities = append(deletedCommodities, dbCommodity)
		}
	}

	// 2-更新商品订单信息-更新
	for _, commodity := range matchingCommodities {
		if err := gdb.Model(&ErpInventoryProductCommodity{}).Where("id = ?", commodity.ID).Updates(commodity).Error; err != nil {
			logger.Error("更新商品订单信息-更新 error")
			return errors.New("操作失败:" + err.Error())
		}
	}

	// 2-更新商品订单信息-新增
	if len(newCommodities) != 0 {
		err = gdb.Create(&newCommodities).Error
		if err != nil {
			logger.Error("更新商品订单信息-新增 error")
			return errors.New("操作失败:" + err.Error())
		}
	}

	//2-更新商品订单信息-删除
	if len(deletedCommodities) != 0 {
		err = gdb.Delete(&deletedCommodities).Error
		if err != nil {
			logger.Error("更新商品订单信息-删除 error")
			return errors.New("操作失败:" + err.Error())
		}
	}

	return nil
}

// AuditProductInventory 审核产品入库 state：1-审核，2-取消审核
func AuditProductInventory(req *ProductInventoryAuditReq, c *gin.Context) error {
	// 查询订单信息
	var inventoryProductOrder 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))
		return err
	}

	sysUser, err := GetSysUserByCtx(c)
	if err != nil {
		return err
	}

	// 校验是否有入参门店权限
	err = AuthUserStore(c, inventoryProductOrder.StoreId)
	if err != nil {
		return err
	}

	begin := orm.Eloquent.Begin()

	// 判断入参state：1-审核，2-取消审核
	orderState := 0
	switch req.State {
	case 1: // 1-审核：待审核状态可以审核
		if inventoryProductOrder.State == ErpInventoryProductOrderFinished { // 订单已审核
			return errors.New("订单已完成，无需再次审核")
		}
		orderState = ErpInventoryProductOrderFinished
		// 入库-更新库存信息
		err = productAuditAndUpdateStock(begin, inventoryProductOrder)
		if err != nil {
			begin.Rollback()
			logger.Error("ProductAuditAndUpdateStock err:", logger.Field("err", err))
			return err
		}
	case 2: // 2-取消审核
		orderState = ErpInventoryProductOrderUnAudit
		if inventoryProductOrder.State == ErpInventoryProductOrderUnAudit { // 订单未审核
			return errors.New("订单是未审核状态，无需取消审核")
		}
		if IsMonthEndClosed(*inventoryProductOrder.AuditTime) {
			return errors.New("财务已月结")
		}
		// 退库-更新库存信息
		err = cancelProductAuditAndUpdateStock(begin, inventoryProductOrder)
		if err != nil {
			begin.Rollback()
			return err
		}
	default:
		logger.Error("order err, req.State is:", logger.Field("req.State", req.State))
		return errors.New("参数有误")
	}

	// 更新产品入库订单表
	err = begin.Table("erp_inventory_product_order").Where("id = ?", inventoryProductOrder.ID).
		Updates(map[string]interface{}{
			"state":        orderState,
			"auditor_id":   sysUser.UserId,
			"audit_time":   time.Now(),
			"auditor_name": sysUser.NickName,
		}).Error
	if err != nil {
		begin.Rollback()
		logger.Error("update erp_inventory_product_order err:", logger.Field("err", err))
		return err
	}

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

	return nil
}

// cancelProductAuditAndUpdateStock 产品入库反审核后更新库存信息
func cancelProductAuditAndUpdateStock(gdb *gorm.DB, productOrder ErpInventoryProductOrder) error {
	// 查询采购入库商品信息
	var commodities []ErpInventoryProductCommodity
	err := orm.Eloquent.Table("erp_inventory_product_commodity").Where("product_order_id = ?",
		productOrder.ID).Find(&commodities).Error
	if err != nil {
		logger.Error("query erp_inventory_product_commodity err:", logger.Field("err", err))
		return err
	}

	if len(commodities) == 0 {
		return errors.New("未查询到商品信息")
	}

	// 更新库存数量
	for i, _ := range commodities {
		if commodities[i].IMEIType == 2 || commodities[i].IMEIType == 3 { // 串码商品
			if commodities[i].IMEI == "" {
				return errors.New("串码为空")
			}

			// 判断该串码商品是否已经销售
			var stockCommodityInfo ErpStockCommodity
			err = orm.Eloquent.Table("erp_stock_commodity").Where("imei = ?",
				commodities[i].IMEI).Find(&stockCommodityInfo).Error
			if err != nil {
				logger.Error("Inventory RejectStock query commodities err:", logger.Field("err", err))
				return err
			}
			if stockCommodityInfo.State == SoldOut {
				return fmt.Errorf("商品[%s]已经销售，不能退货", stockCommodityInfo.ErpCommodityName)
			}
			//else if stockCommodityInfo.State == OnSale {
			//	return fmt.Errorf("商品[%s]在销售锁定中，不能退货", stockCommodityInfo.ErpCommodityName)
			//}

			// 更新库存数量
			err = gdb.Table("erp_stock").Where("store_id = ? and erp_commodity_id = ?",
				productOrder.StoreId, commodities[i].CommodityId).
				Updates(map[string]interface{}{"count": gorm.Expr("count - ?", 1)}).Error // 库存数量-1
			if err != nil {
				logger.Error("RetailTypeRejected commodities err:", logger.Field("err", err))
				return err
			}
		} else {
			// 查询入库商品实际库存详情处剩余有效数，不包含已出库的数量
			nCount, err := GetCommodityStockByPurchaseId(productOrder.SerialNumber,
				commodities[i].CommodityId)
			if err != nil {
				logger.Error("InventoryErpPurchaseUpdateRejectStock GetCommodityStockByPurchaseId err:",
					logger.Field("err", err))
				return err
			}
			// 如果库存数量不够则报错
			if nCount < commodities[i].Count {
				return fmt.Errorf("商品[%s]采购退货数量超出实际库存数量，请先零售退货",
					commodities[i].CommodityName)
			}

			// 更新库存数量
			err = gdb.Table("erp_stock").Where("store_id = ? and erp_commodity_id = ?",
				productOrder.StoreId, commodities[i].CommodityId).
				Updates(map[string]interface{}{"count": gorm.Expr("count - ?", commodities[i].Count)}).Error // 库存数量-count
			if err != nil {
				logger.Error("RetailTypeRejected commodities err:", logger.Field("err", err))
				return err
			}
		}
	}

	// 删除库存商品表对应的记录
	err = gdb.Where("original_sn = ? and state = ?", productOrder.SerialNumber, InStock).Delete(&ErpStockCommodity{}).Error
	if err != nil {
		logger.Error("delete erp_stock_commodity err:", logger.Field("err", err))
		return err
	}

	return nil
}

// productAuditAndUpdateStock 产品入库审核后更新库存信息
func productAuditAndUpdateStock(gdb *gorm.DB, productOrder ErpInventoryProductOrder) error {
	// 查询采购入库商品信息
	var commodities []ErpInventoryProductCommodity
	err := orm.Eloquent.Table("erp_inventory_product_commodity").Where("product_order_id = ?",
		productOrder.ID).Find(&commodities).Error
	if err != nil {
		logger.Error("query erp_inventory_product_commodity err:", logger.Field("err", err))
		return err
	}

	// 遍历采购入库商品信息
	var stockList []ErpStockCommodity
	for _, v := range commodities {
		commodityInfo, err := GetCommodity(v.CommodityId)
		if err != nil {
			logger.Errorf("GetCommodity err:", err)
			return err
		}
		exist, err := QueryRecordExist(fmt.Sprintf("SELECT * FROM erp_stock WHERE store_id=%d AND erp_commodity_id=%d",
			productOrder.StoreId, v.CommodityId))
		if err != nil {
			logger.Errorf("exist err:", err)
			return err
		}
		if exist {
			err = gdb.Exec(fmt.Sprintf(
				"UPDATE erp_stock SET count=count+%d WHERE  store_id=%d AND erp_commodity_id=%d",
				v.Count, productOrder.StoreId, v.CommodityId)).Error
			if err != nil {
				logger.Errorf("update stock err:", err)
				return err
			}
		} else {
			stock := &ErpStock{
				StoreId:               productOrder.StoreId,
				StoreName:             productOrder.StoreName,
				ErpCommodityId:        v.CommodityId,
				ErpCommodityName:      v.CommodityName,
				ErpCategoryId:         commodityInfo.ErpCategoryId,
				ErpCategoryName:       commodityInfo.ErpCategoryName,
				CommoditySerialNumber: commodityInfo.SerialNumber,
				IMEIType:              v.IMEIType,
				RetailPrice:           commodityInfo.RetailPrice,
				MinRetailPrice:        commodityInfo.MinRetailPrice,
				Count:                 v.Count,
				DispatchCount:         0,
			}
			// 使用带冲突处理的插入操作
			err = gdb.Clauses(clause.OnConflict{
				Columns:   []clause.Column{{Name: "store_id"}, {Name: "erp_commodity_id"}},                      // 唯一约束字段
				DoUpdates: clause.Assignments(map[string]interface{}{"count": gorm.Expr("count + ?", v.Count)}), // 冲突时累加 count
			}).Create(stock).Error

			if err != nil {
				logger.Errorf("create or update stock err:", err)
				return err
			}
		}

		for i := 0; i < int(v.Count); i++ {
			nowTime := time.Now()
			stockCommodity := ErpStockCommodity{
				StoreId:               productOrder.StoreId,
				StoreName:             productOrder.StoreName,
				ErpCommodityId:        v.CommodityId,
				ErpCommodityName:      v.CommodityName,
				CommoditySerialNumber: commodityInfo.SerialNumber,
				ErpCategoryId:         commodityInfo.ErpCategoryId,
				ErpCategoryName:       commodityInfo.ErpCategoryName,
				ErpSupplierId:         v.SupplierId,
				ErpSupplierName:       v.SupplierName,
				StaffCostPrice:        tools.RoundToTwoDecimalPlaces(v.EmployeePrice - v.Price),
				WholesalePrice:        tools.RoundToTwoDecimalPlaces(v.Price),
				State:                 InStock,
				StorageType:           ProductInventory, // 产品入库
				FirstStockTime:        nowTime,
				StockTime:             nowTime,
				Count:                 1,
				ErpBarcode:            commodityInfo.ErpBarcode, // 240106新增商品条码
				IMEIType:              v.IMEIType,
				IMEI:                  v.IMEI,
				Remark:                "",
				MemberDiscount:        commodityInfo.MemberDiscount,
				MinRetailPrice:        commodityInfo.MinRetailPrice,
				RetailPrice:           commodityInfo.RetailPrice,
				OriginalSn:            productOrder.SerialNumber,
				//StockSn:               v.SerialNumber,
			}
			stockList = append(stockList, stockCommodity)
		}
	}

	err = gdb.Debug().Create(&stockList).Error
	if err != nil {
		logger.Errorf("create stock commodity err:", err)
		return err
	}

	return nil
}

// List 查询采购订单列表
func (m *ProductInventoryListReq) List(c *gin.Context) (*ProductInventoryListResp, error) {
	resp := &ProductInventoryListResp{
		PageIndex: m.PageIndex,
		PageSize:  m.PageSize,
	}
	page := m.PageIndex - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	qs := orm.Eloquent.Table("erp_inventory_product_order")

	// 非管理员才判断所属门店
	if !(tools.GetRoleName(c) == "admin" || tools.GetRoleName(c) == "系统管理员") {
		sysUser, err := GetSysUserByCtx(c)
		if err != nil {
			return nil, err
		}

		// 返回sysUser未过期的门店id列表
		storeList := GetValidStoreIDs(sysUser.StoreData)
		if m.StoreId != 0 {
			if !Contains(storeList, m.StoreId) {
				return nil, errors.New("您没有该门店权限")
			}
		} else {
			if len(storeList) > 0 {
				if len(storeList) == 1 {
					qs = qs.Where("store_id = ?", storeList[0])
				} else {
					qs = qs.Where("store_id IN (?)", storeList)
				}
			} else {
				return nil, errors.New("用户未绑定门店")
			}
		}
	}

	if m.SerialNumber != "" {
		qs = qs.Where("serial_number=?", m.SerialNumber)
	} else {
		if m.StoreId != 0 {
			qs = qs.Where("store_id=?", m.StoreId)
		}
		if m.HandlerId != 0 {
			qs = qs.Where("handler_id=?", m.HandlerId)
		}
		if m.State != 0 {
			qs = qs.Where("state=?", m.State)
		}
		if m.AuditTimeStart != "" {
			parse, err := time.Parse(QueryTimeFormat, m.AuditTimeStart)
			if err != nil {
				logger.Errorf("ProductInventoryList err:", err)
				return nil, err
			}
			qs = qs.Where("audit_time > ?", parse)
		}
		if m.AuditTimeEnd != "" {
			parse, err := time.Parse(QueryTimeFormat, m.AuditTimeEnd)
			if err != nil {
				logger.Errorf("ProductInventoryList err:", err)
				return nil, err
			}
			qs = qs.Where("audit_time < ?", parse)
		}
	}

	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return resp, err
	}
	resp.Total = int(count)
	var orders []ErpInventoryProductOrder
	err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&orders).Error
	if err != nil && err != RecordNotFound {
		logger.Error("product list err:", logger.Field("err", err))
		return resp, err
	}

	// 校验时间，如果为01-01-01 08:05，则赋值为空
	for i, v := range orders {
		if v.MakerTime != nil && v.MakerTime.IsZero() {
			orders[i].MakerTime = nil
		}

		if v.AuditTime != nil && v.AuditTime.IsZero() {
			orders[i].AuditTime = nil
		}
	}

	resp.List = orders
	return resp, nil
}

// ProductInventoryGetIMEIReq 系统生成串码入参
type ProductInventoryGetIMEIReq struct {
	CommodityId uint32 `json:"commodity_id"  binding:"required"` // 商品id
}

// ProductInventoryGetIMEIResp 系统生成串码出参
type ProductInventoryGetIMEIResp struct {
	IMEI string `json:"imei"` // 商品串码
}
