// Copyright (c) Shenyang Leading Edge Intelligent Technology Co., Ltd. All rights reserved.

package implments

import (
	dal "LAPP_LF_MOM_BACKEND/dao/wm"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/grmi"
	meta "LAPP_LF_MOM_BACKEND/meta/wm"
	model "LAPP_LF_MOM_BACKEND/models/wm"
	"LAPP_LF_MOM_BACKEND/utils"
	"LAPP_LF_MOM_BACKEND/web/models"
	"fmt"
	"time"
)

/******************************************************************************
 *
 * @Description              : InventoryCheckHead的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-29 10:57:04
 *
 ******************************************************************************/
var DefaultConditionOfInventoryCheckHead = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.InventoryCheckHead_InventoryCheckId.UrlParameterName: grmi.NewConditionItem(meta.InventoryCheckHead_InventoryCheckId, grmi.Equal, true),
		meta.InventoryCheckHead_Descr.UrlParameterName:            grmi.NewConditionItem(meta.InventoryCheckHead_Descr, grmi.Equal, false),
		meta.InventoryCheckHead_CheckDate.UrlParameterName:        grmi.NewConditionItem(meta.InventoryCheckHead_CheckDate, grmi.Approximate, false),
		meta.InventoryCheckHead_CheckTime.UrlParameterName:        grmi.NewConditionItem(meta.InventoryCheckHead_CheckTime, grmi.Approximate, false),
		meta.InventoryCheckHead_CheckType.UrlParameterName:        grmi.NewConditionItem(meta.InventoryCheckHead_CheckType, grmi.Equal, false),
		meta.InventoryCheckHead_CheckPerson.UrlParameterName:      grmi.NewConditionItem(meta.InventoryCheckHead_CheckPerson, grmi.Equal, false),
		meta.InventoryCheckHead_ICCtrlPara1.UrlParameterName:      grmi.NewConditionItem(meta.InventoryCheckHead_ICCtrlPara1, grmi.Equal, false),
		meta.InventoryCheckHead_ICCtrlPara2.UrlParameterName:      grmi.NewConditionItem(meta.InventoryCheckHead_ICCtrlPara2, grmi.Equal, false),
		meta.InventoryCheckHead_ICCtrlPara3.UrlParameterName:      grmi.NewConditionItem(meta.InventoryCheckHead_ICCtrlPara3, grmi.Equal, false),
		meta.InventoryCheckHead_ICCtrlPara4.UrlParameterName:      grmi.NewConditionItem(meta.InventoryCheckHead_ICCtrlPara4, grmi.Equal, false),
		meta.InventoryCheckHead_ICCtrlPara5.UrlParameterName:      grmi.NewConditionItem(meta.InventoryCheckHead_ICCtrlPara5, grmi.Equal, false),
		meta.InventoryCheckHead_ICCtrlPara6.UrlParameterName:      grmi.NewConditionItem(meta.InventoryCheckHead_ICCtrlPara6, grmi.Equal, false),
		meta.InventoryCheckHead_Status.UrlParameterName:           grmi.NewConditionItem(meta.InventoryCheckHead_Status, grmi.Equal, false),
		meta.InventoryCheckHead_WareHouseId.UrlParameterName:      grmi.NewConditionItem(meta.InventoryCheckHead_WareHouseId, grmi.Equal, false),
		meta.InventoryCheckHead_StorageAreaId.UrlParameterName:    grmi.NewConditionItem(meta.InventoryCheckHead_StorageAreaId, grmi.Equal, false),
		meta.InventoryCheckHead_StorageRackId.UrlParameterName:    grmi.NewConditionItem(meta.InventoryCheckHead_StorageRackId, grmi.Equal, false),
		meta.InventoryCheckHead_LastModify.UrlParameterName:       grmi.NewConditionItem(meta.InventoryCheckHead_LastModify, grmi.Approximate, false),
		meta.InventoryCheckHead_LastUser.UrlParameterName:         grmi.NewConditionItem(meta.InventoryCheckHead_LastUser, grmi.Equal, false),
		meta.InventoryCheckHead_CreateTime.UrlParameterName:       grmi.NewConditionItem(meta.InventoryCheckHead_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : InventoryCheckHead的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-29 10:57:04
 *
 ******************************************************************************/
var DefaultConditionOfInventoryCheckHeadAndPaging = grmi.NewCondition(
	DefaultConditionOfInventoryCheckHead.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : InventoryCheckHeadServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : InventoryCheckHead的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-29 10:57:04
 *
 ******************************************************************************/
type InventoryCheckHeadServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewInventoryCheckHeadDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个InventoryCheckHeadDAOImplement实例
 *
 * @Return Value             : InventoryCheckHeadDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-29 10:57:04
 *
 ******************************************************************************/
func NewInventoryCheckHeadServiceImplement() *InventoryCheckHeadServiceImplement {
	return &InventoryCheckHeadServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/wm/InventoryCheckHeadService.InsertOne
 *
 ******************************************************************************/
func (impl *InventoryCheckHeadServiceImplement) InsertOne(user *models.Usertab, entity *model.InventoryCheckHead) error {
	grmi.Log(user, "/services/wm/implments/InventoryCheckHead.service.impl.go", "InsertOneInventoryCheckHead", "插入一个InventoryCheckHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewInventoryCheckHeadDAO(session, user.Userid)
	binDao := dal.NewStorageBinDAO(session, user.Userid)
	daoWorkAreaUserLst := dal.NewWorkAreaUserLstDAO(session, user.Userid)
	daoWorkArea := dal.NewWorkAreaDAO(session, user.Userid)

	var workAreaCheck model.WorkAreaCheck
	detailLi := entity.InventoryCheckDetailLi
	if len(detailLi) == 0 {
		_ = session.Rollback()
		return grmi.NewBusinessError("未指定库位数据")
	}
	if entity.WareHouseId == "" || entity.StorageAreaId == "" || entity.StorageRackId == "" {
		_ = session.Rollback()
		return grmi.NewBusinessError("位置数据不完整")
	}
	for _, detail := range detailLi {
		workAreaCheck.StorageBinIdList = utils.AddListOnce(workAreaCheck.StorageBinIdList, detail.StorageBinId)
		workAreaCheck.WarehouseIdList = utils.AddListOnce(workAreaCheck.WarehouseIdList, detail.WarehouseId)
		workAreaCheck.StorageAreaIdList = utils.AddListOnce(workAreaCheck.StorageAreaIdList, entity.StorageAreaId)
		workAreaCheck.StorageRackIdList = utils.AddListOnce(workAreaCheck.StorageRackIdList, entity.StorageRackId)

		bin, err := binDao.SelectOne(detail.StorageBinId, detail.WarehouseId)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		if bin == nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("不存在选择的库位")
		}
		if bin.Status == model.BIN_STAUTS_CHECK {
			_ = session.Rollback()
			return grmi.NewBusinessError("该库位正在盘点中")
		}
		bin.Status = model.BIN_STAUTS_CHECK
		err = binDao.UpdateOne(bin)
		if err != nil {
			_ = session.Rollback()
			return err
		}
	}

	if model.WM_AUTH_CHECK == model.WM_AUTH_CHECK_ON{
		//权限
		selectWorkAreaUserLst, err := daoWorkAreaUserLst.Select([]grmi.Predicate{meta.WorkAreaUserLst_UserId.NewPredicate(grmi.Equal, user.Userid)}, nil)
		if err != nil {
			session.Rollback()
			return err
		}
		if len(selectWorkAreaUserLst) == 0{
			session.Rollback()
			return nil
		}

		var workAreaList []*model.WorkArea
		for _, info := range selectWorkAreaUserLst{
			selectWorkArea, err := daoWorkArea.SelectOne(info.WorkAreaId)
			if err != nil || selectWorkArea == nil{
				continue
			}
			workAreaList = append(workAreaList, selectWorkArea)
		}

		err = model.WM_Check(workAreaCheck, workAreaList)
		if err != nil {
			session.Rollback()
			fmt.Println(err)
			return err
		}
	}

	snr := new(models.Snrtab)
	snr.Finr = user.Pid
	checkId, err := snr.GetNextSnrWithSession(session, "Inventory")
	if err != nil {
		_ = session.Rollback()
		return err
	}
	for k, _ := range entity.InventoryCheckDetailLi{
		entity.InventoryCheckDetailLi[k].InventoryCheckId = checkId
		entity.InventoryCheckDetailLi[k].ICDPos = k + 1
		for k2, _ := range entity.InventoryCheckDetailLi[k].InventoryCheckLstLi{
			entity.InventoryCheckDetailLi[k].InventoryCheckLstLi[k2].InventoryCheckId = checkId
			entity.InventoryCheckDetailLi[k].InventoryCheckLstLi[k2].ICDPos = entity.InventoryCheckDetailLi[k].ICDPos
			entity.InventoryCheckDetailLi[k].InventoryCheckLstLi[k2].ICLPos = k2 + 1
		}
	}
	entity.CheckPerson = user.Userid
	entity.CheckDate = grmi.Date(time.Now())
	entity.CheckTime = grmi.DateTime(time.Now())
	entity.InventoryCheckId = checkId
	err = dao.InsertOne(entity)
	if err != nil {
		_ = session.Rollback()
		return err
	}

	dao2 := dal.NewInventoryCheckDetailDAO(session, user.Userid)
	err = dao2.Insert(&entity.InventoryCheckDetailLi)
	if err != nil {
		session.Rollback()
		fmt.Println(err)
		return err
	}

	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/wm/InventoryCheckHeadService.DeleteOne
 *
 ******************************************************************************/
func (impl *InventoryCheckHeadServiceImplement) DeleteOne(user *models.Usertab, inventoryCheckId string) error {

	grmi.Log(user, "/services/wm/implments/InventoryCheckHead.service.impl.go", "DeleteOneInventoryCheckHead", "删除一个InventoryCheckHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewInventoryCheckHeadDAO(session, user.Userid)
	detailDao := dal.NewInventoryCheckDetailDAO(session, user.Userid)
	binDao := dal.NewStorageBinDAO(session, user.Userid)
	daoWorkAreaUserLst := dal.NewWorkAreaUserLstDAO(session, user.Userid)
	daoWorkArea := dal.NewWorkAreaDAO(session, user.Userid)

	var workAreaCheck model.WorkAreaCheck
	record, err := dao.SelectOne(inventoryCheckId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if record == nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if record.Status == model.CHECK_STATUS_Accomplish {
		_ = session.Rollback()
		return grmi.NewBusinessError("该盘点单已完成，不可以删除")
	}
	detailLi, err := detailDao.Select([]grmi.Predicate{meta.InventoryCheckDetail_InventoryCheckId.NewPredicate(grmi.Equal, inventoryCheckId)}, nil)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	pos := 1
	for _, detail := range detailLi {
		workAreaCheck.StorageBinIdList = utils.AddListOnce(workAreaCheck.StorageBinIdList, detail.StorageBinId)
		workAreaCheck.WarehouseIdList = utils.AddListOnce(workAreaCheck.WarehouseIdList, detail.WarehouseId)

		bin, err := binDao.SelectOne(detail.StorageBinId, detail.WarehouseId)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		if bin == nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("盘点单中指定的库位不存在")
		}
		bin.Status = model.BIN_STATUS_ON
		err = binDao.UpdateOne(bin)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		detail.ICDPos = pos
		pos++
	}

	if model.WM_AUTH_CHECK == model.WM_AUTH_CHECK_ON{
		//权限
		selectWorkAreaUserLst, err := daoWorkAreaUserLst.Select([]grmi.Predicate{meta.WorkAreaUserLst_UserId.NewPredicate(grmi.Equal, user.Userid)}, nil)
		if err != nil {
			session.Rollback()
			return err
		}
		if len(selectWorkAreaUserLst) == 0{
			session.Rollback()
			return nil
		}

		var workAreaList []*model.WorkArea
		for _, info := range selectWorkAreaUserLst{
			selectWorkArea, err := daoWorkArea.SelectOne(info.WorkAreaId)
			if err != nil || selectWorkArea == nil{
				continue
			}
			workAreaList = append(workAreaList, selectWorkArea)
		}

		err = model.WM_Check(workAreaCheck, workAreaList)
		if err != nil {
			session.Rollback()
			fmt.Println(err)
			return err
		}
	}

	err = detailDao.DeleteWhere([]grmi.Predicate{meta.InventoryCheckDetail_InventoryCheckId.NewPredicate(grmi.Equal, inventoryCheckId)})
	if err != nil {
		_ = session.Rollback()
		return err
	}
	err = dao.DeleteOne(inventoryCheckId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/wm/InventoryCheckHeadService.SelectOne
 *
 ******************************************************************************/
func (impl *InventoryCheckHeadServiceImplement) SelectOne(user *models.Usertab, inventoryCheckId string) (*model.InventoryCheckHead, error) {

	grmi.Log(user, "/services/wm/implments/InventoryCheckHead.service.impl.go", "SelectOneInventoryCheckHead", "查询一个InventoryCheckHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewInventoryCheckHeadDAO(session, user.Userid)
	detailDao := dal.NewInventoryCheckDetailDAO(session, user.Userid)
	lstDao := dal.NewInventoryCheckLstDAO(session, user.Userid)
	result, err := dao.SelectOne(inventoryCheckId)
	if err != nil {
		return nil, err
	}
	if result == nil {
		return nil, grmi.NewBusinessError("不存在查询的盘点单")
	}
	detailLi, err := detailDao.Select([]grmi.Predicate{meta.InventoryCheckDetail_InventoryCheckId.NewPredicate(grmi.Equal, result.InventoryCheckId)}, nil)
	if err != nil {
		return nil, err
	}
	for index, detail := range detailLi {
		lstLi, err := lstDao.Select([]grmi.Predicate{meta.InventoryCheckLst_InventoryCheckId.NewPredicate(grmi.Equal, detail.InventoryCheckId, meta.InventoryCheckLst_ICDPos.NewPredicate(grmi.Equal, detail.ICDPos))}, nil)
		if err != nil {
			return nil, err
		}
		detail.InventoryCheckLstLi = lstLi
		detailLi[index] = detail
	}
	result.InventoryCheckDetailLi = detailLi
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/wm/InventoryCheckHeadService.UpdateOne
 *
 ******************************************************************************/
func (impl *InventoryCheckHeadServiceImplement) UpdateOne(user *models.Usertab, entity *model.InventoryCheckHead) error {

	grmi.Log(user, "/services/wm/implments/InventoryCheckHead.service.impl.go", "UpdateOneInventoryCheckHead", "修改一个InventoryCheckHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewInventoryCheckHeadDAO(session, user.Userid)
	record, err := dao.SelectOne(entity.InventoryCheckId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/wm/InventoryCheckHeadService.Insert
 *
 ******************************************************************************/
func (impl *InventoryCheckHeadServiceImplement) Insert(user *models.Usertab, entities *[]model.InventoryCheckHead) error {

	grmi.Log(user, "/services/wm/implments/InventoryCheckHead.service.impl.go", "InsertInventoryCheckHead", "插入多个InventoryCheckHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewInventoryCheckHeadDAO(session, user.Userid)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.InventoryCheckId)
		if err != nil {
			return err
		}
		if record != nil {
			return grmi.NewBusinessError("已经存在相同主键的记录!")
		}
	}

	err := dao.Insert(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/wm/InventoryCheckHeadService.Delete
 *
 ******************************************************************************/
func (impl *InventoryCheckHeadServiceImplement) Delete(user *models.Usertab, entities *[]model.InventoryCheckHead) error {

	grmi.Log(user, "/services/wm/implments/InventoryCheckHead.service.impl.go", "DeleteInventoryCheckHead", "删除多个InventoryCheckHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewInventoryCheckHeadDAO(session, user.Userid)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.InventoryCheckId)
		if err != nil {
			return err
		}
		if record == nil {
			return grmi.NewBusinessError("不存在指定记录!")
		}
	}

	err := dao.Delete(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/wm/InventoryCheckHeadService.Select
 *
 ******************************************************************************/
func (impl *InventoryCheckHeadServiceImplement) Select(user *models.Usertab, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/wm/implments/InventoryCheckHead.service.impl.go", "SelectInventoryCheckHead", "查询InventoryCheckHead")

	condition := DefaultConditionOfInventoryCheckHeadAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewInventoryCheckHeadDAO(session, user.Userid)
	if condition.Fill(urlParameters) {
		result, err := dao.SelectAndPaging(condition.Paging, predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		return result, nil
	} else {
		result, err := dao.Select(predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		return result, nil
	}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/wm/InventoryCheckHeadService.Update
 *
 ******************************************************************************/
func (impl *InventoryCheckHeadServiceImplement) Update(user *models.Usertab, entities *[]model.InventoryCheckHead) error {

	grmi.Log(user, "/services/wm/implments/InventoryCheckHead.service.impl.go", "UpdateInventoryCheckHead", "修改多个InventoryCheckHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewInventoryCheckHeadDAO(session, user.Userid)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.InventoryCheckId)
		if err != nil {
			return err
		}
		if record == nil {
			return grmi.NewBusinessError("不存在指定记录!")
		}
	}

	err := dao.Update(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/wm/InventoryCheckHeadService.AccomplishCheckHead
 *
 ******************************************************************************/
func (impl *InventoryCheckHeadServiceImplement) AccomplishCheckHead(user *models.Usertab, entity *model.InventoryCheckHead) error {
	grmi.Log(user, "/services/wm/implments/InventoryCheckHead.service.impl.go", "AccomplishCheckHead", "完成盘点单")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewInventoryCheckHeadDAO(session, user.Userid)
	detailDao := dal.NewInventoryCheckDetailDAO(session, user.Userid)
	binDao := dal.NewStorageBinDAO(session, user.Userid)
	lstDao := dal.NewInventoryCheckLstDAO(session, user.Userid)
	bookDao := dal.NewInventoryBookDAO(session, user.Userid)
	artDao := dal.NewArticleDAO(session, user.Userid)
	replenishDao := dal.NewReplenishOrderDAO(session, user.Userid)
	daoWorkAreaUserLst := dal.NewWorkAreaUserLstDAO(session, user.Userid)
	daoWorkArea := dal.NewWorkAreaDAO(session, user.Userid)

	var workAreaCheck model.WorkAreaCheck
	record, err := dao.SelectOne(entity.InventoryCheckId)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	if record == nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if record.Status == model.CHECK_STATUS_Accomplish {
		_ = session.Rollback()
		return grmi.NewBusinessError("该盘点单已完成盘点")
	}
	originDetailLi, err := detailDao.Select([]grmi.Predicate{meta.InventoryCheckDetail_InventoryCheckId.NewPredicate(grmi.Equal, record.InventoryCheckId)}, nil)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	originDetailMap := make(map[int]interface{}, len(originDetailLi))
	for _, detail := range originDetailLi {
		originDetailMap[detail.ICDPos] = nil
	}
	detailLi := entity.InventoryCheckDetailLi
	for _, detail := range detailLi {
		_, exist := originDetailMap[detail.ICDPos]
		if !exist {
			_ = session.Rollback()
			return grmi.NewBusinessError("数据中有盘点单中不存在的库位")
		}
		bin, err := binDao.SelectOne(detail.StorageBinId, detail.WarehouseId)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		if bin == nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("盘点单中指定的库位不存在")
		}
		bin.Status = model.BIN_STATUS_ON
		err = binDao.UpdateOne(bin)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		lstLi := detail.InventoryCheckLstLi
		pos := 1
		for index, lst := range lstLi {
			workAreaCheck.StorageBinIdList = utils.AddListOnce(workAreaCheck.StorageBinIdList, lst.StorageBinId)
			workAreaCheck.WarehouseIdList = utils.AddListOnce(workAreaCheck.WarehouseIdList, lst.WarehouseId)
			workAreaCheck.StorageAreaIdList = utils.AddListOnce(workAreaCheck.StorageAreaIdList, entity.StorageAreaId)
			workAreaCheck.StorageRackIdList = utils.AddListOnce(workAreaCheck.StorageRackIdList, entity.StorageRackId)
			if lst.WarehouseId != detail.WarehouseId || lst.StorageBinId != detail.StorageBinId {
				_ = session.Rollback()
				return grmi.NewBusinessError("盘点库位详情数据与盘点库位不一致")
			}
			book, err := bookDao.SelectOne(lst.StorageBinId, lst.WarehouseId, lst.ArtId)
			if err != nil {
				_ = session.Rollback()
				return err
			}
			if book == nil {
				book =&model.InventoryBook{
					StorageBinId: lst.StorageBinId,
					WarehouseId: lst.WarehouseId,
					ArtId: lst.ArtId,
					StorageAreaId: bin.StorageAreaId,
					StorageRackId: bin.StorageRackId,
					ArtName: lst.ArtName,
					ArtType: lst.ArtType,
					QtyUom: lst.QtyUom,
				}
				err = bookDao.InsertOne(book)
				if err != nil {
					_ = session.Rollback()
					return err
				}
			}
			lst.OriginQty = book.Qty
			lst.ICLPos = pos
			pos++
			if lst.ActQty == book.Qty {
				lst.CheckResult = model.CHECK_RESULT_EQUAL
			} else if lst.ActQty > book.Qty {
				lst.CheckResult = model.CHECK_RESULT_MORE
			} else {
				lst.CheckResult = model.CHECK_RESULT_LESS
			}
			if lst.ActQty != book.Qty {
				article, err := artDao.SelectOne(lst.ArtId)
				if err != nil {
					_ = session.Rollback()
					return err
				}
				if article == nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("不存在对应的物料")
				}
				article.Qty = article.Qty + (lst.ActQty - book.Qty)
				err = artDao.UpdateOne(article)
				if err != nil {
					_ = session.Rollback()
					return err
				}
				if article.Qty < article.ArticleReplenish.MinQty {
					orderLi, err := replenishDao.Select([]grmi.Predicate{meta.ReplenishOrder_ArtId.NewPredicate(grmi.Equal, lst.ArtId), meta.ReplenishOrder_Status.NewPredicate(grmi.Equal, model.REPLENISH_ORDER_STATUS_ON)}, nil)
					if err != nil {
						_ = session.Rollback()
						return err
					}
					if len(orderLi) == 0 {
						snr := new(models.Snrtab)
						snr.Finr = user.Pid
						orderId, err := snr.GetNextSnrWithSession(session, "ReplenishOrder")
						if err != nil {
							_ = session.Rollback()
							return err
						}
						replenishOrder := model.ReplenishOrder{
							ReplenishId:   orderId,
							ArtId:         lst.ArtId,
							Qty:           article.ArticleReplenish.ReplenishQty,
							Uom:           article.Uom,
							ReplenishTime: grmi.DateTime(time.Now()),
							ArtType:       article.ArtType,
							ArtName:       article.Descr1,
							Status:        model.REPLENISH_ORDER_STATUS_ON,
						}
						err = replenishDao.InsertOne(&replenishOrder)
						if err != nil {
							_ = session.Rollback()
							return err
						}
					}
				}
			}

			book.Qty = lst.ActQty
			book.LastCheckDate = grmi.DateTime(time.Now())
			book.LastCheckPerson = user.Userid
			err = bookDao.UpdateOne(book)
			if err != nil {
				_ = session.Rollback()
				return err
			}
			lst.InventoryCheckId = entity.InventoryCheckId
			lstLi[index] = lst
		}
		err = lstDao.Insert(&lstLi)
		if err != nil {
			_ = session.Rollback()
			return err
		}
	}

	if model.WM_AUTH_CHECK == model.WM_AUTH_CHECK_ON{
		//权限
		selectWorkAreaUserLst, err := daoWorkAreaUserLst.Select([]grmi.Predicate{meta.WorkAreaUserLst_UserId.NewPredicate(grmi.Equal, user.Userid)}, nil)
		if err != nil {
			session.Rollback()
			return err
		}
		if len(selectWorkAreaUserLst) == 0{
			session.Rollback()
			return nil
		}

		var workAreaList []*model.WorkArea
		for _, info := range selectWorkAreaUserLst{
			selectWorkArea, err := daoWorkArea.SelectOne(info.WorkAreaId)
			if err != nil || selectWorkArea == nil{
				continue
			}
			workAreaList = append(workAreaList, selectWorkArea)
		}

		err = model.WM_Check(workAreaCheck, workAreaList)
		if err != nil {
			session.Rollback()
			fmt.Println(err)
			return err
		}
	}

	entity.Status = model.CHECK_STATUS_Accomplish
	err = dao.UpdateOne(entity)
	if err != nil {
		_ = session.Rollback()
		return err
	}
	_ = session.Commit()
	return nil
}

func (impl *InventoryCheckHeadServiceImplement) ExportExcel(user *models.Usertab, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/wm/implments/InventoryCheckHead.service.impl.go", "ExportExcel", "导出excel表")

	condition := DefaultConditionOfInventoryCheckHeadAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewInventoryCheckHeadDAO(session, user.Userid)
	//condition.OrderByFields = append(condition.OrderByFields, meta.InventoryCheckHead_InventoryCheckId)
	result, err := dao.Select(predicates, condition.OrderByFields)
	if err != nil {
		return nil, err
	}
	temp := make([]interface{}, len(result))
	for index, item := range result {
		temp[index] = item
	}
	titleList := []string{}

	filepath, err := grmi.SaveExcelFile(temp, titleList, "盘点", "盘点")
	if err != nil {
		return nil, grmi.NewBusinessError(fmt.Sprintf("导出报表失败，请重试, errors: %s", err.Error()))
	}
	return filepath, nil
}
