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

package implments

import (
	baseDal "LAPP_LF_MOM_BACKEND/dao/base"
	meDal "LAPP_LF_MOM_BACKEND/dao/me"
	dal "LAPP_LF_MOM_BACKEND/dao/om"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/grmi"
	meta "LAPP_LF_MOM_BACKEND/meta/om"
	baseModel "LAPP_LF_MOM_BACKEND/models/base"
	model "LAPP_LF_MOM_BACKEND/models/om"
	"LAPP_LF_MOM_BACKEND/utils"
	"LAPP_LF_MOM_BACKEND/web/models"
	"github.com/360EntSecGroup-Skylar/excelize"
	"strconv"
	"strings"
	"time"
)

/******************************************************************************
 *
 * @Description              : DemandHead的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-21 10:27:00
 *
 ******************************************************************************/
var DefaultConditionOfDemandHead = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.DemandHead_FileNr.UrlParameterName:     grmi.NewConditionItem(meta.DemandHead_FileNr, grmi.Equal, true),
		meta.DemandHead_FileName.UrlParameterName:   grmi.NewConditionItem(meta.DemandHead_FileName, grmi.Equal, false),
		meta.DemandHead_Source.UrlParameterName:     grmi.NewConditionItem(meta.DemandHead_Source, grmi.Equal, false),
		meta.DemandHead_Status.UrlParameterName:     grmi.NewConditionItem(meta.DemandHead_Status, grmi.Equal, false),
		meta.DemandHead_ErrorInfo.UrlParameterName:  grmi.NewConditionItem(meta.DemandHead_ErrorInfo, grmi.Equal, false),
		meta.DemandHead_LastModify.UrlParameterName: grmi.NewConditionItem(meta.DemandHead_LastModify, grmi.Approximate, false),
		meta.DemandHead_LastUser.UrlParameterName:   grmi.NewConditionItem(meta.DemandHead_LastUser, grmi.Equal, false),
		meta.DemandHead_CreateTime.UrlParameterName: grmi.NewConditionItem(meta.DemandHead_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : DemandHead的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-21 10:27:00
 *
 ******************************************************************************/
var DefaultConditionOfDemandHeadAndPaging = grmi.NewCondition(
	DefaultConditionOfDemandHead.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : DemandHeadServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : DemandHead的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-21 10:27:00
 *
 ******************************************************************************/
type DemandHeadServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewDemandHeadDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个DemandHeadDAOImplement实例
 *
 * @Return Value             : DemandHeadDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-21 10:27:00
 *
 ******************************************************************************/
func NewDemandHeadServiceImplement() *DemandHeadServiceImplement {
	return &DemandHeadServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadService.InsertOne
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) InsertOne(user *models.Usertab, entity *model.DemandHead) error {

	grmi.Log(user, "/services/om/implments/DemandHead.service.impl.go", "InsertOneDemandHead", "插入一个DemandHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewDemandHeadDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.FileNr)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadService.DeleteOne
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) DeleteOne(user *models.Usertab, fileNr int) error {

	grmi.Log(user, "/services/om/implments/DemandHead.service.impl.go", "DeleteOneDemandHead", "删除一个DemandHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	err := session.Begin()
	if err != nil {
		return err
	}
	defer session.Close()
	dao := dal.NewDemandHeadDAO(session, user.Pid, user.Userid)
	demandLstDao := dal.NewDemandLstDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(fileNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	if record.Status != model.DemandHeadLoadFailedStatus && record.Status != model.DemandHeadUnParsedStatus {
		return grmi.NewBusinessError("该状态不可以删除")
	}
	err = dao.DeleteOne(fileNr)
	if err != nil {
		session.Rollback()
		return err
	}
	err = demandLstDao.DeleteWhere([]grmi.Predicate{meta.DemandLst_FileNr.NewPredicate(grmi.Equal, fileNr)})
	if err != nil {
		session.Rollback()
		return err
	}
	session.Commit()
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadService.SelectOne
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) SelectOne(user *models.Usertab, fileNr int) (*model.DemandHead, error) {

	grmi.Log(user, "/services/om/implments/DemandHead.service.impl.go", "SelectOneDemandHead", "查询一个DemandHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewDemandHeadDAO(session, user.Pid, user.Userid)
	result, err := dao.SelectOne(fileNr)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadService.UpdateOne
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) UpdateOne(user *models.Usertab, entity *model.DemandHead) error {

	grmi.Log(user, "/services/om/implments/DemandHead.service.impl.go", "UpdateOneDemandHead", "修改一个DemandHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewDemandHeadDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.FileNr)
	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/om/DemandHeadService.Insert
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) Insert(user *models.Usertab, entities *[]model.DemandHead) error {

	grmi.Log(user, "/services/om/implments/DemandHead.service.impl.go", "InsertDemandHead", "插入多个DemandHead")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.FileNr)
		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/om/DemandHeadService.Delete
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) Delete(user *models.Usertab, entities *[]model.DemandHead) error {

	grmi.Log(user, "/services/om/implments/DemandHead.service.impl.go", "DeleteDemandHead", "删除多个DemandHead")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.FileNr)
		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/om/DemandHeadService.Select
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) Select(user *models.Usertab, urlParameters map[string]string) (interface{}, error) {

	grmi.Log(user, "/services/om/implments/DemandHead.service.impl.go", "SelectDemandHead", "查询DemandHead")

	condition := DefaultConditionOfDemandHeadAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewDemandHeadDAO(session, user.Pid, 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/om/DemandHeadService.Update
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) Update(user *models.Usertab, entities *[]model.DemandHead) error {

	grmi.Log(user, "/services/om/implments/DemandHead.service.impl.go", "UpdateDemandHead", "修改多个DemandHead")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.FileNr)
		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/om/DemandHeadService.UploadExcel
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) UploadExcel(user *models.Usertab, filepath string, filename string, source string) error {
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	demandHeadDao := dal.NewDemandHeadDAO(session, user.Pid, user.Userid)
	demandHeadLi, err := demandHeadDao.Select([]grmi.Predicate{meta.DemandHead_FileName.NewPredicate(grmi.Equal, filename), meta.DemandHead_Source.NewPredicate(grmi.Equal, source)}, []grmi.Field{})
	if err != nil {
		return err
	}
	if len(demandHeadLi) != 0 {
		return grmi.NewBusinessError("已存在同名文件")
	}
	demandHead := model.DemandHead{
		FileName: filename,
		Status:   model.DemandHeadLoadingStatus,
		Source:   source,
	}
	err = demandHeadDao.InsertOne(&demandHead)
	if err != nil {
		return err
	}
	if source == model.ParseSourceInterval {
		return impl.SaveIntervalDataFromExcel(user, filepath, demandHead)
	} else if source == model.ParseSourceMES {
		go impl.SaveMesDataFromExcel(user, filepath, demandHead)
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadService.UploadExcel
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) SaveMesDataFromExcel(user *models.Usertab, filepath string, demandHead model.DemandHead) {
	engine := db.Eloquent.Master()
	headSession := engine.NewSession()
	lstSession := engine.NewSession()
	err := lstSession.Begin()
	if err != nil {
		return
	}
	defer lstSession.Close()
	defer headSession.Close()
	demandHeadDao := dal.NewDemandHeadDAO(headSession, user.Pid, user.Userid)
	demandLstDao := dal.NewDemandLstDAO(lstSession, user.Pid, user.Userid)
	file, err := excelize.OpenFile(filepath)
	if err != nil {
		demandHead.Status = model.DemandHeadLoadFailedStatus
		demandHead.ErrorInfo = "读取文件失败:" + err.Error()
		_ = demandHeadDao.UpdateOne(&demandHead)
		return
	}
	rowsIterator, err := file.Rows("Sheet1")
	if err != nil {
		demandHead.Status = model.DemandHeadLoadFailedStatus
		demandHead.ErrorInfo = "不存在Sheet1"
		_ = demandHeadDao.UpdateOne(&demandHead)
		return
	}

	demandLi := make([]model.DemandLst, 0, 100)
	var firstSign bool
	var pos int
	for rowsIterator.Next() {
		if !firstSign {
			firstSign = true
			continue
		}
		pos += 1
		var demandLst model.DemandLst
		demandLst.Pos = pos
		demandLst.FileNr = demandHead.FileNr
		row := rowsIterator.Columns()
		for index, colCell := range row {
			switch index {
			case 0:
				demandNr, err := strconv.Atoi(colCell)
				if err != nil {
					_ = lstSession.Rollback()
					demandHead.Status = model.DemandHeadLoadFailedStatus
					demandHead.ErrorInfo = "DemandNr解析出错: " + err.Error()
					_ = demandHeadDao.UpdateOne(&demandHead)
					return
				}
				demandLst.DemandNr = demandNr
			case 1:
				demandLst.BarCode = colCell
			case 2:
				demandLst.BarCodeDesc = colCell
			case 3:
				demandLst.PartCode = colCell
			case 4:
				demandTime, err := time.ParseInLocation("1/2/2006 15:04:05", colCell, utils.TimezoneLocation)
				if err != nil {
					demandTime, err = time.ParseInLocation("2006-01-02 15:04:05", colCell, utils.TimezoneLocation)
					if err != nil {
						_ = lstSession.Rollback()
						demandHead.Status = model.DemandHeadLoadFailedStatus
						demandHead.ErrorInfo = "plan_dttm时间解析错误: " + err.Error()
						_ = demandHeadDao.UpdateOne(&demandHead)
						return
					}
				}
				demandLst.PlanDttm = grmi.DateTime(demandTime)
			case 5:
				class1, err := strconv.Atoi(colCell)
				if err != nil {
					_ = lstSession.Rollback()
					demandHead.Status = model.DemandHeadLoadFailedStatus
					demandHead.ErrorInfo = "class1 value type error: " + err.Error()
					_ = demandHeadDao.UpdateOne(&demandHead)
					return
				}
				demandLst.Class1 = class1
			case 6:
				demandLst.ConfigDesc = colCell
			case 7:
				demandLst.ConfigKey = colCell
			case 8:
				seq, err := strconv.Atoi(colCell)
				if err != nil {
					_ = lstSession.Rollback()
					demandHead.Status = model.DemandHeadLoadFailedStatus
					demandHead.ErrorInfo = "seq value type error: " + err.Error()
					_ = demandHeadDao.UpdateOne(&demandHead)
					return
				}
				demandLst.Seq = seq
			case 9:
				state, err := strconv.Atoi(colCell)
				if err != nil {
					_ = lstSession.Rollback()
					demandHead.Status = model.DemandHeadLoadFailedStatus
					demandHead.ErrorInfo = "state value type error: " + err.Error()
					_ = demandHeadDao.UpdateOne(&demandHead)
					return
				}
				demandLst.State = state
			case 10:
				demandLst.StateName = colCell
			case 11:
				var station int
				if colCell == "NULL" {
					station = 0
				} else {
					station, err = strconv.Atoi(colCell)
					if err != nil {
						_ = lstSession.Rollback()
						demandHead.Status = model.DemandHeadLoadFailedStatus
						demandHead.ErrorInfo = "station value type error: " + err.Error()
						_ = demandHeadDao.UpdateOne(&demandHead)
						return
					}
				}

				demandLst.Station = station
			case 12:
				demandLst.StationCode = colCell
			case 13:
				demandLst.StationDesc = colCell
			case 14:
				creatTime, err := time.ParseInLocation("1/2/2006 15:04:05", colCell, utils.TimezoneLocation)
				if err != nil {
					creatTime, err = time.ParseInLocation("2006-01-02 15:04:05", colCell, utils.TimezoneLocation)
					if err != nil {
						_ = lstSession.Rollback()
						demandHead.Status = model.DemandHeadLoadFailedStatus
						demandHead.ErrorInfo = "create_time解析错误: " + err.Error()
						_ = demandHeadDao.UpdateOne(&demandHead)
						return
					}
				}
				demandLst.DemandCreateTime = grmi.DateTime(creatTime)
			case 15:
				if colCell == "" {
					demandLst.IsRefreshToggle = false
				} else {
					demandLst.IsRefreshToggle = true
				}
			case 16:
				demandLst.Serial = colCell
			case 17:
				demandLst.CustomId = colCell
			case 18:
				if colCell != "NULL" {
					logTime, err := time.Parse("1/2/2006 15:04:05", colCell)
					if err != nil {
						logTime, err = time.Parse("2006-01-02 15:04:05", colCell)
						if err != nil {
							_ = lstSession.Rollback()
							demandHead.Status = model.DemandHeadLoadFailedStatus
							demandHead.ErrorInfo = "log_time解析错误: " + err.Error()
							_ = demandHeadDao.UpdateOne(&demandHead)
							return
						}
					}
					demandLst.LogTime = grmi.DateTime(logTime)
				}
			case 19:
				demandLst.CodeBar = colCell
			case 20:
				demandLst.Memo = colCell
			}
		}
		demandLi = append(demandLi, demandLst)
	}
	// 批量插入时 一次最多插入50条
	tempLi := make([]model.DemandLst, 0, 50)
	for index, demandLst := range demandLi {
		if index%50 == 0 {
			err = demandLstDao.Insert(&tempLi)
			if err != nil {
				demandHead.Status = model.DemandHeadLoadFailedStatus
				demandHead.ErrorInfo = "写入数据出错: " + err.Error()
				_ = demandHeadDao.UpdateOne(&demandHead)
				_ = lstSession.Rollback()
				return
			}
			tempLi = make([]model.DemandLst, 0, 50)
		}
		tempLi = append(tempLi, demandLst)
	}
	if len(tempLi) != 0 {
		err = demandLstDao.Insert(&tempLi)
		if err != nil {
			demandHead.Status = model.DemandHeadLoadFailedStatus
			demandHead.ErrorInfo = "写入数据出错: " + err.Error()
			_ = demandHeadDao.UpdateOne(&demandHead)
			_ = lstSession.Rollback()
			return
		}
	}
	err = lstSession.Commit()
	if err != nil {
		demandHead.Status = model.DemandHeadLoadFailedStatus
		demandHead.ErrorInfo = "事务提交失败"
		_ = demandHeadDao.UpdateOne(&demandHead)
		return
	}
	demandHead.Status = model.DemandHeadUnParsedStatus
	demandHead.ErrorInfo = ""
	_ = demandHeadDao.UpdateOne(&demandHead)

}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadService.SaveIntervalDataFromExcel
 *
 ******************************************************************************/
//func (impl *DemandHeadServiceImplement) SaveIntervalDataFromExcel(user *models.Usertab, filepath string, demandHead model.DemandHead) {
//	engine := db.Eloquent.Master()
//	headSession := engine.NewSession()
//	lstSession := engine.NewSession()
//	err := lstSession.Begin()
//	if err != nil {
//		return
//	}
//	defer lstSession.Close()
//	defer headSession.Close()
//
//	demandHeadDao := dal.NewDemandHeadDAO(headSession, user.Pid, user.Userid)
//	custOrderDao := dal.NewCustOrderDAO(lstSession, user.Pid, user.Userid)
//	file, err := excelize.OpenFile(filepath)
//	if err != nil {
//		demandHead.Status = model.DemandHeadLoadFailedStatus
//		demandHead.ErrorInfo = "读取文件失败"
//		_ = demandHeadDao.UpdateOne(&demandHead)
//		return
//	}
//	rowsIterator, err := file.Rows("Sheet1")
//	if err != nil {
//		demandHead.Status = model.DemandHeadLoadFailedStatus
//		demandHead.ErrorInfo = "不存在Sheet1"
//		_ = demandHeadDao.UpdateOne(&demandHead)
//		return
//	}
//	custOrderLi := make([]model.CustOrder, 0, 100)
//	artTypeMap := make(map[string]baseModel.ArticleType)
//	artTypeDao := baseDal.NewArticleTypeDAO(headSession, user.Pid, user.Userid)
//	var firstSign bool
//	var noId int
//	for rowsIterator.Next() {
//		if !firstSign {
//			firstSign = true
//			continue
//		}
//		var custOrder model.CustOrder
//		custOrder.TaskNr = demandHead.FileNr
//		custOrder.PlantNr = demandHead.PlantNr
//		row := rowsIterator.Columns()
//		for index, colCell := range row {
//			colCell = strings.TrimSpace(colCell)
//			switch index {
//			case 0:
//				if colCell == "" {
//					noId++
//				}
//				custOrder.CustOrderId = colCell
//				custOrder.OemOrderId = colCell
//			case 1:
//
//				custOrder.ArtId = colCell
//			case 2:
//
//				custOrder.ArtDesc = colCell
//			case 3:
//
//				planDueTime, err := time.ParseInLocation("2006-01-02 15:04:05", colCell, utils.TimezoneLocation)
//				if err != nil {
//					_ = lstSession.Rollback()
//					demandHead.Status = model.DemandHeadLoadFailedStatus
//					demandHead.ErrorInfo = "plan_ddt时间解析错误: " + err.Error() + "_" + colCell
//					_ = demandHeadDao.UpdateOne(&demandHead)
//					return
//				}
//				custOrder.DDT = grmi.DateTime(planDueTime)
//			case 4:
//
//				custOrder.ProjectId = colCell
//			case 5:
//
//				custOrder.ArtTypeDesc = colCell
//			case 6:
//				artTypeId := colCell
//				artType, exist := artTypeMap[artTypeId]
//				if !exist {
//					artTypePointer, err := artTypeDao.SelectOne(artTypeId)
//					if err != nil {
//						_ = lstSession.Rollback()
//						demandHead.Status = model.DemandHeadLoadFailedStatus
//						demandHead.ErrorInfo = "获取artType错误: " + err.Error()
//						_ = demandHeadDao.UpdateOne(&demandHead)
//						return
//					}
//					if artTypePointer == nil {
//						_ = lstSession.Rollback()
//						demandHead.Status = model.DemandHeadLoadFailedStatus
//						demandHead.ErrorInfo = "artType不存在"
//						_ = demandHeadDao.UpdateOne(&demandHead)
//						return
//					}
//					artType = *artTypePointer
//					artTypeMap[artType.ArtTypeId] = artType
//				}
//				if artType.Descr != custOrder.ArtTypeDesc {
//					_ = lstSession.Rollback()
//					demandHead.Status = model.DemandHeadLoadFailedStatus
//					demandHead.ErrorInfo = "artTypeId和artTypeDesc不符" + artType.Descr + "_" + custOrder.ArtTypeDesc
//					_ = demandHeadDao.UpdateOne(&demandHead)
//					return
//				}
//				custOrder.ArtTypeId = artTypeId
//			case 7:
//				if len(colCell) == 0 {
//					custOrder.SEQ = 0
//				} else {
//					seq, err := strconv.Atoi(colCell)
//					if err != nil {
//						_ = lstSession.Rollback()
//						demandHead.Status = model.DemandHeadLoadFailedStatus
//						demandHead.ErrorInfo = "seq数据类型错误: " + err.Error()
//						_ = demandHeadDao.UpdateOne(&demandHead)
//						return
//					} else {
//						custOrder.SEQ = seq
//					}
//				}
//			case 8:
//				custOrder.CustomerId = colCell
//			}
//		}
//		custOrderLi = append(custOrderLi, custOrder)
//	}
//	var maxOrderId int
//	var prefix string
//	snr := new(models.Snrtab)
//	if noId > 0 {
//		snr.Finr = user.Pid
//		CustOrderId, err := snr.GetNextSnrWithNum(lstSession, "CustOrder", noId)
//		if err != nil {
//			demandHead.Status = model.DemandHeadLoadFailedStatus
//			demandHead.ErrorInfo = "获取流水号失败: " + err.Error()
//			_ = demandHeadDao.UpdateOne(&demandHead)
//			_ = lstSession.Rollback()
//			return
//		}
//		fmt.Println("custOrderId:", CustOrderId)
//		li := strings.Split(CustOrderId, "-")
//		if len(li) != 2 {
//			demandHead.Status = model.DemandHeadLoadFailedStatus
//			demandHead.ErrorInfo = "获取流水号失败: 流水号格式错误"
//			_ = demandHeadDao.UpdateOne(&demandHead)
//			_ = lstSession.Rollback()
//			return
//		}
//		prefix = li[0] + "-"
//		maxOrderId, err = strconv.Atoi(li[1])
//		if err != nil {
//			demandHead.Status = model.DemandHeadLoadFailedStatus
//			demandHead.ErrorInfo = "获取流水号失败: 流水号格式错误"
//			_ = demandHeadDao.UpdateOne(&demandHead)
//			_ = lstSession.Rollback()
//			return
//		}
//	}
//	// 批量插入时 一次最多插入50条
//	tempLi := make([]model.CustOrder, 0, 50)
//	for index, custOrder := range custOrderLi {
//		if custOrder.CustOrderId == "" {
//			fmt.Println("maxOrderId:", maxOrderId)
//			fmt.Println("snr.Length:",snr.Length)
//			idStr := utils.ConvInt2FormatString(maxOrderId, snr.Length)
//			fmt.Println("idStr:", idStr)
//			orderId := prefix + idStr
//			maxOrderId++
//			custOrder.CustOrderId = orderId
//			custOrder.OemOrderId = orderId
//		}
//		if index%50 == 0 {
//			err = custOrderDao.Insert(&tempLi)
//			if err != nil {
//				demandHead.Status = model.DemandHeadLoadFailedStatus
//				demandHead.ErrorInfo = "写入数据出错: " + err.Error()
//				_ = demandHeadDao.UpdateOne(&demandHead)
//				_ = lstSession.Rollback()
//				return
//			}
//			tempLi = make([]model.CustOrder, 0, 50)
//		}
//		tempLi = append(tempLi, custOrder)
//	}
//
//	if len(tempLi) != 0 {
//		err = custOrderDao.Insert(&tempLi)
//		if err != nil {
//			demandHead.Status = model.DemandHeadLoadFailedStatus
//			demandHead.ErrorInfo = "写入数据出错: " + err.Error()
//			_ = demandHeadDao.UpdateOne(&demandHead)
//			_ = lstSession.Rollback()
//			return
//		}
//	}
//
//	err = lstSession.Commit()
//	if err != nil {
//		demandHead.Status = model.DemandHeadLoadFailedStatus
//		demandHead.ErrorInfo = "事务提交失败"
//		_ = demandHeadDao.UpdateOne(&demandHead)
//		return
//	}
//	demandHead.Status = model.DemandHeadUnParsedStatus
//	demandHead.ErrorInfo = ""
//	_ = demandHeadDao.UpdateOne(&demandHead)
//
//}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadService.SaveIntervalDataFromExcel
 *
 ******************************************************************************/
func (impl *DemandHeadServiceImplement) SaveIntervalDataFromExcel(user *models.Usertab, filepath string, demandHead model.DemandHead) (err error) {
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err = session.Begin(); err != nil {
		return err
	}
	demandHeadDao := dal.NewDemandHeadDAO(session, user.Pid, user.Userid)
	workOrderDao := dal.NewWorkOrderDAO(session, user.Pid, user.Userid)
	workOrderStatusDao := dal.NewWorkOrderStatusDAO(session, user.Pid, user.Userid)
	workOrderQtyDao := dal.NewWorkOrderQtyDAO(session, user.Pid, user.Userid)
	artDao := baseDal.NewArticleDAO(session, user.Pid, user.Userid)
	projectDao := meDal.NewProjectDAO(session, user.Pid, user.Userid)
	project, err := projectDao.SelectOne(baseModel.ProjectId)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("获取项目主数据失败,错误:" + err.Error())
	}
	file, err := excelize.OpenFile(filepath)
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("打开文件失败:" + err.Error())
	}
	rowsIterator, err := file.Rows("Sheet1")
	if err != nil {
		_ = session.Rollback()
		return grmi.NewBusinessError("未能打开Sheet1:" + err.Error())
	}
	workOrderLi := make([]model.WorkOrder, 0, 5)
	workOrderStatusLi := make([]model.WorkOrderStatus, 0, 5)
	workOrderQtyLi := make([]model.WorkOrderQty, 0, 5)
	for rowsIterator.Next() {
		var article *baseModel.Article
		var qty int
		row := rowsIterator.Columns()
		for index, colCell := range row {
			colCell = strings.TrimSpace(colCell)
			switch index {
			case 0:
				if colCell == "" {
					_ = session.Rollback()
					return grmi.NewBusinessError("零件号为空")
				}

				article, err = artDao.SelectOne(colCell)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("查询零件数据失败，错误:" + err.Error())
				}
				if article == nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("不存在对应的零件主数据, 零件号:" + colCell)
				}
			case 1:
				qty, err = strconv.Atoi(colCell)
				if err != nil {
					_ = session.Rollback()
					return grmi.NewBusinessError("解析零件数量失败，错误:" + err.Error())
				}
			}
		}
		snr := new(models.Snrtab)
		snr.Finr = user.Pid
		workOrderId, err := snr.GetNextSnrWithSession(session, project.WorkOrderSnr)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("获取工单流水号失败,错误:" + err.Error())
		}
		workOrder := model.WorkOrder{
			WorkOrderId:          workOrderId,
			ArtId:                article.ArtId,
			CustArtId: article.CustArtId,
			OrderType:            baseModel.ODER_TYPE_INTERVAL,
			OrderInfo:            article.Descr1,
			PlanResourceGroupId:  article.PlanResourceGroupId,
			PlanResourceId:       article.PlanResourceId,
			UsedResourceId:       article.UsedResourceId,
			PlanQty:              float64(qty),
			QtyUomId:             article.UomId,
			RatePerHourToggle:    article.RatePerHourToggle,
			TimePerItemToggle:    article.TimePerItemToggle,
			TimePerBatchToggle:   article.TimePerBatchToggle,
			BatchTimeFieldToggle: article.BatchTimeFieldToggle,
			OpTimePerItem:        article.OpTimePerItem,
			BatchTime:            article.BatchTime,
			QuantityPerHour:      article.QuantityPerHour,
			BatchingMethod:       article.BatchingMethod,
			PlanStartDate:        grmi.Date(time.Now()),
			ProjectId:            article.ProjectId,
		}
		workOrderStatus := model.WorkOrderStatus{
			WorkOrderId: workOrderId,
			Status:      baseModel.WO_STATUS_UNPLANNED,
		}
		workOrderQty := model.WorkOrderQty{
			WorkOrderId: workOrderId,
			PlanQty:     float64(qty),
		}
		workOrderLi = append(workOrderLi, workOrder)
		workOrderStatusLi = append(workOrderStatusLi, workOrderStatus)
		workOrderQtyLi = append(workOrderQtyLi, workOrderQty)
		if len(workOrderLi) == 5 {
			err = workOrderDao.Insert(&workOrderLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("生成workOrder写入数据库失败,错误:" + err.Error())
			}
			err = workOrderStatusDao.Insert(&workOrderStatusLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("生成workOrderStatus写入数据库失败,错误:" + err.Error())
			}
			err = workOrderQtyDao.Insert(&workOrderQtyLi)
			if err != nil {
				_ = session.Rollback()
				return grmi.NewBusinessError("生成workOrderQty写入数据库失败,错误:" + err.Error())
			}
			workOrderLi = make([]model.WorkOrder, 0, 5)
			workOrderStatusLi = make([]model.WorkOrderStatus, 0, 5)
			workOrderQtyLi = make([]model.WorkOrderQty, 0, 5)
		}
	}
	if len(workOrderLi) > 0 {
		err = workOrderDao.Insert(&workOrderLi)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("生成workOrder写入数据库失败,错误:" + err.Error())
		}
		err = workOrderStatusDao.Insert(&workOrderStatusLi)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("生成workOrderStatus写入数据库失败,错误:" + err.Error())
		}
		err = workOrderQtyDao.Insert(&workOrderQtyLi)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("生成workOrderQty写入数据库失败,错误:" + err.Error())
		}
	}
	demandHead.Status = model.DemandHeadParsedStatus
	demandHead.ErrorInfo = ""
	_ = demandHeadDao.UpdateOne(&demandHead)
	_ = session.Commit()
	return nil
}
