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

package implments

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

/******************************************************************************
 *
 * @Description              : ArtDemandLst的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-11 16:10:25
 *
 ******************************************************************************/
var DefaultConditionOfArtDemandLst = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.ArtDemandLst_DemandId.UrlParameterName:           grmi.NewConditionItem(meta.ArtDemandLst_DemandId, grmi.Equal, true),
		meta.ArtDemandLst_Pos.UrlParameterName:                grmi.NewConditionItem(meta.ArtDemandLst_Pos, grmi.Equal, true),
		meta.ArtDemandLst_ArtId.UrlParameterName:              grmi.NewConditionItem(meta.ArtDemandLst_ArtId, grmi.Equal, false),
		meta.ArtDemandLst_DemandTime.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandLst_DemandTime, grmi.Approximate, false),
		meta.ArtDemandLst_DemandYear.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandLst_DemandYear, grmi.Equal, false),
		meta.ArtDemandLst_DemandMonth.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandLst_DemandMonth, grmi.Equal, false),
		meta.ArtDemandLst_DemandWeek.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandLst_DemandWeek, grmi.Equal, false),
		meta.ArtDemandLst_DemandDate.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandLst_DemandDate, grmi.Approximate, false),
		meta.ArtDemandLst_DemandHour.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandLst_DemandHour, grmi.Equal, false),
		meta.ArtDemandLst_DemandQty.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandLst_DemandQty, grmi.Equal, false),
		meta.ArtDemandLst_QtyUomId.UrlParameterName:           grmi.NewConditionItem(meta.ArtDemandLst_QtyUomId, grmi.Equal, false),
		meta.ArtDemandLst_DemandObjId.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandLst_DemandObjId, grmi.Equal, false),
		meta.ArtDemandLst_DemandType.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandLst_DemandType, grmi.Equal, false),
		meta.ArtDemandLst_Status.UrlParameterName:             grmi.NewConditionItem(meta.ArtDemandLst_Status, grmi.Equal, false),
		meta.ArtDemandLst_DemandSendTime.UrlParameterName:     grmi.NewConditionItem(meta.ArtDemandLst_DemandSendTime, grmi.Approximate, false),
		meta.ArtDemandLst_DemandRecieveTime.UrlParameterName:  grmi.NewConditionItem(meta.ArtDemandLst_DemandRecieveTime, grmi.Approximate, false),
		meta.ArtDemandLst_DemandConfirmTime.UrlParameterName:  grmi.NewConditionItem(meta.ArtDemandLst_DemandConfirmTime, grmi.Approximate, false),
		meta.ArtDemandLst_DemandCloseTime.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandLst_DemandCloseTime, grmi.Approximate, false),
		meta.ArtDemandLst_DemandDeliveredQty.UrlParameterName: grmi.NewConditionItem(meta.ArtDemandLst_DemandDeliveredQty, grmi.Equal, false),
		meta.ArtDemandLst_DemandCtrlPara1.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandLst_DemandCtrlPara1, grmi.Equal, false),
		meta.ArtDemandLst_DemandCtrlPara2.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandLst_DemandCtrlPara2, grmi.Equal, false),
		meta.ArtDemandLst_DemandCtrlPara3.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandLst_DemandCtrlPara3, grmi.Equal, false),
		meta.ArtDemandLst_DemandCtrlPara4.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandLst_DemandCtrlPara4, grmi.Equal, false),
		meta.ArtDemandLst_DemandCtrlTime1.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandLst_DemandCtrlTime1, grmi.Approximate, false),
		meta.ArtDemandLst_DemandCtrlTime2.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandLst_DemandCtrlTime2, grmi.Approximate, false),
		meta.ArtDemandLst_OrderStatus.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandLst_OrderStatus, grmi.Equal, false),
		meta.ArtDemandLst_UnproducedQty.UrlParameterName:      grmi.NewConditionItem(meta.ArtDemandLst_UnproducedQty, grmi.Equal, false),
		meta.ArtDemandLst_OrderType.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandLst_OrderType, grmi.Equal, false),
		meta.ArtDemandLst_ProjectId.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandLst_ProjectId, grmi.Equal, false),
		meta.ArtDemandLst_DemandStatus.UrlParameterName:       grmi.NewConditionItem(meta.ArtDemandLst_DemandStatus, grmi.Equal, false),
		meta.ArtDemandLst_PlanResourceId.UrlParameterName:     grmi.NewConditionItem(meta.ArtDemandLst_PlanResourceId, grmi.Equal, false),
		meta.ArtDemandLst_PlanStartDate.UrlParameterName:      grmi.NewConditionItem(meta.ArtDemandLst_PlanStartDate, grmi.Approximate, false),
		meta.ArtDemandLst_PlanEndDate.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandLst_PlanEndDate, grmi.Approximate, false),
		meta.ArtDemandLst_PlanStartTime.UrlParameterName:      grmi.NewConditionItem(meta.ArtDemandLst_PlanStartTime, grmi.Approximate, false),
		meta.ArtDemandLst_PlanEndTime.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandLst_PlanEndTime, grmi.Approximate, false),
		meta.ArtDemandLst_ActStartTime.UrlParameterName:       grmi.NewConditionItem(meta.ArtDemandLst_ActStartTime, grmi.Approximate, false),
		meta.ArtDemandLst_ActEndTime.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandLst_ActEndTime, grmi.Approximate, false),
		meta.ArtDemandLst_LastModify.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandLst_LastModify, grmi.Approximate, false),
		meta.ArtDemandLst_LastUser.UrlParameterName:           grmi.NewConditionItem(meta.ArtDemandLst_LastUser, grmi.Equal, false),
		meta.ArtDemandLst_CreateTime.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandLst_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : ArtDemandLst的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 11:27:55
 *
 ******************************************************************************/
var DefaultConditionOfArtDemandLstAndPaging = grmi.NewCondition(
	DefaultConditionOfArtDemandLst.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : ArtDemandLstServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : ArtDemandLst的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 11:27:55
 *
 ******************************************************************************/
type ArtDemandLstServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewArtDemandLstDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个ArtDemandLstDAOImplement实例
 *
 * @Return Value             : ArtDemandLstDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-22 11:27:55
 *
 ******************************************************************************/
func NewArtDemandLstServiceImplement() *ArtDemandLstServiceImplement {
	return &ArtDemandLstServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.InsertOne
 *
 ******************************************************************************/
func (impl *ArtDemandLstServiceImplement) InsertOne(user *models.Usertab, entity *model.ArtDemandLst) error {

	grmi.Log(user, "/services/log/implments/ArtDemandLst.service.impl.go", "InsertOneArtDemandLst", "插入一个ArtDemandLst")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	headDao := dal.NewArtDemandHeadDAO(session, user.Pid, user.Userid)
	headItem, err := headDao.SelectOne(entity.ArtId, entity.DemandId)
	if err != nil {
		return err
	}
	if headItem == nil {
		return grmi.NewBusinessError("对应的artDemandHead不存在，请检查")
	}
	dao := dal.NewArtDemandLstDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.DemandId, entity.Pos)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	baseDao := baseDal.NewArticleDAO(session, user.Pid, user.Userid)
	article, err := baseDao.SelectOne(entity.ArtId)
	if err != nil {
		return err
	}
	if article == nil {
		return grmi.NewBusinessError("不存在对应的物料，请检查")
	}
	demandTime := entity.DemandTime.Restore()
	entity.DemandYear = demandTime.Year()
	entity.DemandMonth = int(demandTime.Month())
	entity.DemandWeek = int(demandTime.Weekday())
	entity.DemandSendTime = grmi.DateTime(time.Now())
	entity.DemandHour = demandTime.Hour()
	entity.DemandDate = grmi.Date(demandTime)
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.DeleteOne
 *
 ******************************************************************************/
func (impl *ArtDemandLstServiceImplement) DeleteOne(user *models.Usertab, demandId string, pos int) error {

	grmi.Log(user, "/services/log/implments/ArtDemandLst.service.impl.go", "DeleteOneArtDemandLst", "删除一个ArtDemandLst")

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.SelectOne
 *
 ******************************************************************************/
func (impl *ArtDemandLstServiceImplement) SelectOne(user *models.Usertab, demandId string, pos int) (*model.ArtDemandLst, error) {

	grmi.Log(user, "/services/log/implments/ArtDemandLst.service.impl.go", "SelectOneArtDemandLst", "查询一个ArtDemandLst")

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.UpdateOne
 *
 ******************************************************************************/
func (impl *ArtDemandLstServiceImplement) UpdateOne(user *models.Usertab, entity *model.ArtDemandLst) error {

	grmi.Log(user, "/services/log/implments/ArtDemandLst.service.impl.go", "UpdateOneArtDemandLst", "修改一个ArtDemandLst")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandLstDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.DemandId, entity.Pos)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	//record.DemandId = entity.DemandId
	record.DemandCtrlPara1 = entity.DemandCtrlPara1
	record.DemandCtrlPara2 = entity.DemandCtrlPara2
	record.DemandCtrlPara3 = entity.DemandCtrlPara3
	record.DemandCtrlPara4 = entity.DemandCtrlPara4
	record.DemandCtrlTime1 = entity.DemandCtrlTime1
	record.DemandCtrlTime2 = entity.DemandCtrlTime2
	record.DemandObjId = entity.DemandObjId
	record.DemandDeliveredQty = entity.DemandDeliveredQty
	record.DemandQty = entity.DemandQty
	record.QtyUomId = entity.QtyUomId
	record.DemandType = entity.DemandType
	err = dao.UpdateOne(record)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.Insert
 *
 ******************************************************************************/
func (impl *ArtDemandLstServiceImplement) Insert(user *models.Usertab, entities *[]model.ArtDemandLst) error {

	grmi.Log(user, "/services/log/implments/ArtDemandLst.service.impl.go", "InsertArtDemandLst", "插入多个ArtDemandLst")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.DemandId, entity.Pos)
		if err != nil {
			return err
		}
		if record != nil {
			return grmi.NewBusinessError("已经存在相同主键的记录!")
		}
		demandTime := entity.DemandTime.Restore()
		entity.DemandYear = demandTime.Year()
		entity.DemandMonth = int(demandTime.Month())
		entity.DemandWeek = int(demandTime.Weekday())
		entity.DemandSendTime = grmi.DateTime(time.Now())
		entity.DemandHour = demandTime.Hour()
		entity.DemandDate = grmi.Date(demandTime)
	}

	err = dao.Insert(entities)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.Delete
 *
 ******************************************************************************/
func (impl *ArtDemandLstServiceImplement) Delete(user *models.Usertab, entities *[]model.ArtDemandLst) error {

	grmi.Log(user, "/services/log/implments/ArtDemandLst.service.impl.go", "DeleteArtDemandLst", "删除多个ArtDemandLst")

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

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

	err = dao.Delete(entities)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

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

	grmi.Log(user, "/services/log/implments/ArtDemandLst.service.impl.go", "SelectArtDemandLst", "查询ArtDemandLst")

	condition := DefaultConditionOfArtDemandLstAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	grmi.DeleteUrlParametersEmpty(&urlParameters)
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	search, exist := urlParameters["search"]
	if exist {
		params := map[string]string{
			meta.ArtDemandLst_DemandId.UrlParameterName: search,
		}
		innerPredicates, err := condition.BuildPredicates(params)
		if err != nil {
			return nil, err
		}
		predicates = append(predicates, innerPredicates...)
	}
	urgencyString, exist := urlParameters["urgency"]
	if exist {
		urgency, err := strconv.Atoi(urgencyString)
		if err == nil {
			now := time.Now()
			date := now.AddDate(0, 0, 2)
			dateString := date.Format(grmi.DateOutFormat)
			today := now.Format(grmi.DateOutFormat)
			status, exist := urlParameters["status"]
			if exist && status == strconv.Itoa(model.AccomplishedStatus) {
				if urgency != model.UrgencyNot {
					predicate := []grmi.Predicate{meta.ArtDemandLst_DemandDate.NewPredicate(grmi.Include)}
					predicates = append(predicates, predicate...)
				}
			} else {
				if urgency == model.UrgencyNot {
					predicate := []grmi.Predicate{meta.ArtDemandLst_DemandDate.NewPredicate(grmi.GreaterThen, dateString)}
					predicates = append(predicates, predicate...)
				} else if urgency == model.UrgencyNormal {
					predicate1 := []grmi.Predicate{meta.ArtDemandLst_DemandDate.NewPredicate(grmi.GreaterOrEqual, today)}
					predicate2 := []grmi.Predicate{meta.ArtDemandLst_DemandDate.NewPredicate(grmi.LessOrEqual, dateString)}
					predicates = append(predicates, predicate1...)
					predicates = append(predicates, predicate2...)
				} else {
					predicate := []grmi.Predicate{meta.ArtDemandLst_DemandDate.NewPredicate(grmi.LessThen, today)}
					predicates = append(predicates, predicate...)
				}
				predicate := []grmi.Predicate{meta.ArtDemandLst_Status.NewPredicate(grmi.NotEqual, model.AccomplishedStatus)}
				predicates = append(predicates, predicate...)
			}
		}

	}
	dao := dal.NewArtDemandLstDAO(session, user.Pid, user.Userid)
	year, month, day := time.Now().Date()
	var today time.Time
	var monthStr string
	var dayStr string
	if int(month) >= 10 {
		monthStr = strconv.Itoa(int(month))
	} else {
		monthStr = fmt.Sprintf("0%d", int(month))
	}
	if day >= 10 {
		dayStr = strconv.Itoa(day)
	} else {
		dayStr = fmt.Sprintf("0%d", day)
	}
	today, err = time.ParseInLocation(grmi.DateOutFormat, fmt.Sprintf("%d-%s-%s", year, monthStr, dayStr), utils.TimezoneLocation)
	if err != nil {
		return nil, err
	}
	condition.OrderByFields = append(condition.OrderByFields, meta.ArtDemandLst_DemandCtrlPara1, meta.ArtDemandLst_DemandCtrlPara2)
	if condition.Fill(urlParameters) {
		result, err := dao.SelectAndPaging(condition.Paging, predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		artDemandLstLi := result.Records.([]model.ArtDemandLst)
		baseDao := baseDal.NewArticleDAO(session, user.Pid, user.Userid)
		responseLi := make([]model.ArtDemandLstResponseItem, 0, len(artDemandLstLi))

		for _, artDemandLst := range artDemandLstLi {
			data := artDemandLst
			var responseItem model.ArtDemandLstResponseItem
			responseItem.ArtDemandLst = &data
			if data.ProjectId == baseModel.A30PorjectId {
				responseItem.ArtDesc = data.DemandCtrlPara3
			} else {
				article, err := baseDao.SelectOne(artDemandLst.ArtId)
				if err != nil {
					return nil, err
				}
				if article != nil {
					responseItem.ArtDesc = article.Descr1
				}
			}
			if artDemandLst.Status == model.AccomplishedStatus {
				responseItem.UrgencyDegree = 0
				responseItem.SurplusDays = 0
			} else {
				demandDate := artDemandLst.DemandDate.Restore()
				days := (demandDate.Unix() - today.Unix()) / 86400
				responseItem.SurplusDays = days
				if days > 2 {
					responseItem.UrgencyDegree = model.UrgencyNot
				} else if days >= 0 && days <= 2 {
					responseItem.UrgencyDegree = model.UrgencyNormal
				} else {
					responseItem.UrgencyDegree = model.UrgencySerious
				}
			}

			responseLi = append(responseLi, responseItem)
		}
		result.Records = responseLi
		return result, nil
	} else {
		result, err := dao.Select(predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		baseDao := baseDal.NewArticleDAO(session, user.Pid, user.Userid)
		responseLi := make([]model.ArtDemandLstResponseItem, 0, len(result))
		for _, artDemandLst := range result {
			data := artDemandLst
			var responseItem model.ArtDemandLstResponseItem
			responseItem.ArtDemandLst = &data
			if data.ProjectId == baseModel.A30PorjectId {
				responseItem.ArtDesc = data.DemandCtrlPara3
			} else {
				article, err := baseDao.SelectOne(artDemandLst.ArtId)
				if err != nil {
					return nil, err
				}
				if article != nil {
					responseItem.ArtDesc = article.Descr1
				}
			}
			if artDemandLst.Status == model.AccomplishedStatus {
				responseItem.UrgencyDegree = 0
				responseItem.SurplusDays = 0
			} else {
				demandDate := artDemandLst.DemandDate.Restore()

				days := (demandDate.Unix() - today.Unix()) / 86400
				responseItem.SurplusDays = days
				if days > 2 {
					responseItem.UrgencyDegree = model.UrgencyNot
				} else if days >= 0 && days <= 2 {
					responseItem.UrgencyDegree = model.UrgencyNormal
				} else {
					responseItem.UrgencyDegree = model.UrgencySerious
				}
			}
			responseLi = append(responseLi, responseItem)
		}
		return responseLi, nil
	}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.Update
 *
 ******************************************************************************/
func (impl *ArtDemandLstServiceImplement) Update(user *models.Usertab, entities *[]model.ArtDemandLst) error {

	grmi.Log(user, "/services/log/implments/ArtDemandLst.service.impl.go", "UpdateArtDemandLst", "修改多个ArtDemandLst")

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

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

	err = dao.Update(entities)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.ExportExcel
 *
 ******************************************************************************/
func (impl *ArtDemandLstServiceImplement) ExportExcel(user *models.Usertab, urlParameters map[string]string) (interface{}, error) {
	grmi.Log(user, "/services/log/implments/LOG_ArtDemandLst.service.impl.go", "ExportExcelArtDemandLst", "导出ArtDemandLst报表")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	condition := DefaultConditionOfArtDemandLstAndPaging
	grmi.DeleteUrlParametersEmpty(&urlParameters)
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	search, exist := urlParameters["search"]
	if exist {
		params := map[string]string{
			meta.ArtDemandLst_DemandId.UrlParameterName: search,
		}
		innerPredicates, err := condition.BuildPredicates(params)
		if err != nil {
			return nil, err
		}
		predicates = append(predicates, innerPredicates...)
	}
	urgencyString, exist := urlParameters["urgency"]
	if exist {
		urgency, err := strconv.Atoi(urgencyString)
		if err == nil {
			now := time.Now()
			date := now.AddDate(0, 0, 2)
			dateString := date.Format(grmi.DateOutFormat)
			today := now.Format(grmi.DateOutFormat)
			status, exist := urlParameters["status"]
			if exist && status == strconv.Itoa(model.AccomplishedStatus) {
				if urgency != model.UrgencyNot {
					predicate := []grmi.Predicate{meta.ArtDemandLst_DemandDate.NewPredicate(grmi.Include)}
					predicates = append(predicates, predicate...)
				}
			} else {
				if urgency == model.UrgencyNot {
					predicate := []grmi.Predicate{meta.ArtDemandLst_DemandDate.NewPredicate(grmi.GreaterThen, dateString)}
					predicates = append(predicates, predicate...)
				} else if urgency == model.UrgencyNormal {
					predicate1 := []grmi.Predicate{meta.ArtDemandLst_DemandDate.NewPredicate(grmi.GreaterOrEqual, today)}
					predicate2 := []grmi.Predicate{meta.ArtDemandLst_DemandDate.NewPredicate(grmi.LessOrEqual, dateString)}
					predicates = append(predicates, predicate1...)
					predicates = append(predicates, predicate2...)
				} else {
					predicate := []grmi.Predicate{meta.ArtDemandLst_DemandDate.NewPredicate(grmi.LessThen, today)}
					predicates = append(predicates, predicate...)
				}
				predicate := []grmi.Predicate{meta.ArtDemandLst_Status.NewPredicate(grmi.NotEqual, model.AccomplishedStatus)}
				predicates = append(predicates, predicate...)
			}
		}

	}
	dao := dal.NewArtDemandLstDAO(session, user.Pid, user.Userid)
	year, month, day := time.Now().Date()
	var today time.Time
	var monthStr string
	var dayStr string
	if int(month) >= 10 {
		monthStr = strconv.Itoa(int(month))
	} else {
		monthStr = fmt.Sprintf("0%d", int(month))
	}
	if day >= 10 {
		dayStr = strconv.Itoa(day)
	} else {
		dayStr = fmt.Sprintf("0%d", day)
	}
	today, err = time.ParseInLocation(grmi.DateOutFormat, fmt.Sprintf("%d-%s-%s", year, monthStr, dayStr), utils.TimezoneLocation)
	if err != nil {
		return nil, err
	}
	condition.OrderByFields = append(condition.OrderByFields, meta.ArtDemandLst_DemandCtrlPara1, meta.ArtDemandLst_DemandCtrlPara2)
	result, err := dao.Select(predicates, condition.OrderByFields)
	if err != nil {
		return nil, err
	}
	responseLi := make([]model.ArtDemandLstResponseItemTemp, 0, len(result))
	for _, artDemandLst := range result {
		data := artDemandLst
		var responseItem model.ArtDemandLstResponseItemTemp
		if data.Status == model.ReceivedStatus {
			responseItem.Status = "接收"
		} else if data.Status == model.WaitReceivingStatus {
			responseItem.Status = "未接收"
		} else if data.Status == model.ConfirmedStatus {
			responseItem.Status = "确认交期"
		} else if data.Status == model.AccomplishedStatus {
			responseItem.Status = "完成答复"
		}
		orderStatusLi := map[int]string{
			baseModel.WO_STATUS_UNPLANNED:  "未计划",
			baseModel.WO_STATUS_PLANNED:    "已计划",
			baseModel.WO_STATUS_LOCKED:     "已锁定",
			baseModel.WO_STATUS_RELEASED:   "已下达",
			baseModel.WO_STATUS_INTERRUPT:  "中断中",
			baseModel.WO_STATUS_RUNNING:    "生产中",
			baseModel.WO_STATUS_FINISHED:   "已完成",
			baseModel.WO_STATUS_DISPATCHED: "已发运",
			baseModel.WO_STATUS_FROZEN:     "冻结",
			baseModel.WO_STATUS_CANCELED:   "取消",
		}
		var orderStatus string
		for statusInt, statusString := range orderStatusLi {
			if data.OrderStatus == statusInt {
				orderStatus = statusString
				break
			}
		}
		var demandStatus string
		if data.DemandStatus == model.DemandOrderStatusAccomplish {
			demandStatus = "完成"
		} else {
			demandStatus = "未完成"
		}
		responseItem.PlantNr = data.PlantNr
		responseItem.ArtId = data.ArtId
		responseItem.DemandCtrlPara3 = data.DemandCtrlPara3
		responseItem.DemandId = data.DemandId
		responseItem.DemandTime = data.DemandTime
		responseItem.DemandYear = data.DemandYear
		responseItem.DemandMonth = data.DemandMonth
		responseItem.DemandWeek = data.DemandWeek
		responseItem.DemandDate = data.DemandDate
		responseItem.DemandHour = data.DemandHour
		responseItem.DemandQty = data.DemandQty
		responseItem.UnproducedQty = data.UnproducedQty
		responseItem.QtyUomId = data.QtyUomId
		responseItem.DemandObjId = data.DemandObjId
		responseItem.DemandType = data.DemandType
		responseItem.DemandSendTime = data.DemandSendTime
		responseItem.DemandRecieveTime = data.DemandRecieveTime
		responseItem.DemandConfirmTime = data.DemandConfirmTime
		responseItem.DemandCloseTime = data.DemandCloseTime
		responseItem.DemandDeliveredQty = data.DemandDeliveredQty
		responseItem.DemandCtrlPara1 = data.DemandCtrlPara1
		responseItem.DemandCtrlPara2 = data.DemandCtrlPara2
		responseItem.Pos = data.Pos
		responseItem.OrderStatus = orderStatus
		responseItem.OrderType = data.OrderType
		responseItem.ProjectId = data.ProjectId
		responseItem.DemandStatus = demandStatus
		responseItem.PlanResourceId = data.PlanResourceId
		responseItem.LastModify = data.LastModify
		responseItem.LastUser = data.LastUser
		responseItem.CreateTime = data.CreateTime
		if artDemandLst.Status == model.AccomplishedStatus {
			responseItem.UrgencyDegree = "不紧急"
			responseItem.SurplusDays = 0
		} else {
			demandDate := artDemandLst.DemandDate.Restore()

			days := (demandDate.Unix() - today.Unix()) / 86400
			responseItem.SurplusDays = days
			if days > 2 {
				responseItem.UrgencyDegree = "不紧急"
			} else if days >= 0 && days <= 2 {
				responseItem.UrgencyDegree = "紧急"
			} else {
				responseItem.UrgencyDegree = "延误"
			}
		}
		responseLi = append(responseLi, responseItem)
	}
	temp := make([]interface{}, len(responseLi))
	for index, item := range responseLi {
		temp[index] = item
	}
	titleList := []string{
		"工厂ID",
		"物料ID",
		"物料描述",
		"需求ID",
		"需求时间",
		"需求年份",
		"需求月份",
		"需求周",
		"需求日期",
		"需求时",
		"需求数量",
		"未生产数量",
		"数量单位",
		"需求对象ID",
		"需求类型",
		"状态",
		"需求发送时间",
		"需求接收时间",
		"需求确认时间",
		"需求关闭时间",
		"需求发运数量",
		"serial",
		"seq",
		"auto_id",
		"订单生产状态",
		"订单类型",
		"项目ID",
		"需求状态",
		"产线",
		"紧急程度",
		"剩余交付天数",
		"最后修改时间",
		"最后操作人",
		"创建时间",

	}

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.ChangeArtDemandLstStatus
 *
 ******************************************************************************/
func (impl *ArtDemandLstServiceImplement) ChangeArtDemandLstStatus(user *models.Usertab, records []model.ArtDemandLstStatusChange, operateType string) error {
	grmi.Log(user, "/services/log/implments/LOG_ArtDemandLst.service.impl.go", "ChangeArtDemandLstStatus", "ArtDemandLst状态修改为接收")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewArtDemandLstDAO(session, user.Pid, user.Userid)
	artDemandLstList := make([]model.ArtDemandLst, len(records))
	// 校验每个ArtDemandLst的状态 再修改status
	for index, record := range records {
		artDemandLst, err := dao.SelectOne(record.DemandId, record.Pos)
		if err != nil {
			return err
		}
		if artDemandLst == nil {
			return grmi.NewBusinessError(fmt.Sprintf("该条数据不存在, demandId: %s, Pos: %d", record.DemandId, record.Pos))
		}
		switch operateType {
		case "receive":
			if artDemandLst.Status != model.WaitReceivingStatus {
				return grmi.NewBusinessError(fmt.Sprintf("计划明细状态与您的操作不相符, demandId: %s, Pos: %d", record.DemandId, record.Pos))
			}
			artDemandLst.Status = model.ReceivedStatus
			artDemandLst.DemandRecieveTime = grmi.DateTime(time.Now())
		case "confirm":
			if artDemandLst.Status != model.ReceivedStatus {
				return grmi.NewBusinessError(fmt.Sprintf("计划明细状态与您的操作不相符, demandId: %s, Pos: %d", record.DemandId, record.Pos))
			}
			artDemandLst.Status = model.ConfirmedStatus
			artDemandLst.DemandConfirmTime = grmi.DateTime(time.Now())
		case "accomplish":
			if artDemandLst.Status != model.ConfirmedStatus {
				return grmi.NewBusinessError(fmt.Sprintf("计划明细状态与您的操作不相符, demandId: %s, Pos: %d", record.DemandId, record.Pos))
			}
			artDemandLst.Status = model.AccomplishedStatus
			artDemandLst.DemandCloseTime = grmi.DateTime(time.Now())
		}
		artDemandLstList[index] = *artDemandLst
	}
	err = dao.UpdateWithoutModifyTime(&artDemandLstList)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.SyncHronousData
 *
 ******************************************************************************/
func (impl *ArtDemandLstServiceImplement) SyncHronousData(plantNr int, filePath string) (err error) {

	//grmi.Log(user, "/services/om/implments/ArtDemandLstService.service.impl.go", "SyncHronousData", "同步Portal的WorkOrder订单")
	f, err := excelize.OpenFile(filePath)
	if err != nil {
		return
	}
	// 获取 ArtDemandHead 上所有单元格
	rows, err := f.GetRows("ArtDemandHead")
	if err != nil {
		return err
	}
	heads := make([]model.SyncArtDemandHead, 0)
	for k, row := range rows {
		if k == 0 {
			continue
		}
		head := model.SyncArtDemandHead{}
		head.PlantNr = utils.ValueToInt(row[0], 0)
		head.ArtId = utils.ValueToString(row[1], "")
		head.DemandId = utils.ValueToString(row[2], "")
		head.DemandType = utils.ValueToString(row[3], "")
		head.DemandYear = utils.ValueToInt(row[4], 0)
		head.DemandMonth = utils.ValueToInt(row[5], 0)
		head.DemandWeek = utils.ValueToInt(row[6], 0)
		DemandDateStr := utils.ValueToString(row[7], "")
		DemandDate, err := utils.TimeParseyyyyMMdd(DemandDateStr)
		if err != nil {
			return err
		}
		head.DemandDate = grmi.Date(DemandDate)
		head.DemandHour = utils.ValueToInt(row[8], 0)
		DemandTimeStr := utils.ValueToString(row[9], "")
		DemandTime, err := utils.TimeParse(DemandTimeStr)
		if err != nil {
			return err
		}
		head.DemandTime = grmi.DateTime(DemandTime)
		head.DemandQty = utils.ValueToFloat(row[10], 0.0)
		head.QtyUomId = utils.ValueToString(row[11], "")
		head.Status = utils.ValueToInt(row[12], 0)
		DemandSendTimeStr := utils.ValueToString(row[13], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.DemandSendTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[14], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.DemandRecieveTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[15], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.DemandConfirmTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[16], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.DemandCloseTime = grmi.DateTime(DemandSendTime)
		}
		head.DemandDeliveredQty = utils.ValueToFloat(row[17], 0.0)
		head.DemandCtrlPara1 = utils.ValueToInt(row[18], 0)
		head.DemandCtrlPara2 = utils.ValueToInt(row[19], 0)
		head.DemandCtrlPara3 = utils.ValueToString(row[20], "")
		head.DemandCtrlPara4 = utils.ValueToString(row[21], "")
		DemandSendTimeStr = utils.ValueToString(row[22], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.DemandCtrlTime1 = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[23], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.DemandCtrlTime2 = grmi.DateTime(DemandSendTime)
		}
		head.OrderStatus = utils.ValueToInt(row[24], 0)
		head.UnproducedQty = utils.ValueToFloat(row[25], 0.0)
		head.OrderType = utils.ValueToString(row[26], "")
		head.WorkOrderId = utils.ValueToString(row[27], "")
		head.ProjectId = utils.ValueToString(row[28], "")
		head.DemandStatus = utils.ValueToInt(row[29], 0)
		head.DemandCtrlPara5 = utils.ValueToInt(row[30], 0)
		head.DemandCtrlPara6 = utils.ValueToInt(row[31], 0)
		head.ChangeStatus = utils.ValueToInt(row[32], 0)

		head.PlanResourceId = utils.ValueToString(row[33], "")
		DemandSendTimeStr = utils.ValueToString(row[34], "")
		if DemandSendTimeStr != "0001-01-01" {
			DemandSendTime, err := utils.TimeParseyyyyMMdd(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.PlanStartDate = grmi.Date(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[35], "")
		if DemandSendTimeStr != "0001-01-01" {
			DemandSendTime, err := utils.TimeParseyyyyMMdd(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.PlanEndDate = grmi.Date(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[36], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.PlanStartTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[37], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.PlanEndTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[38], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.ActStartTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[39], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.ActEndTime = grmi.DateTime(DemandSendTime)
		}
		head.CancelQty = utils.ValueToFloat(row[40], 0.0)
		LastModifyStr := utils.ValueToString(row[41], "")
		LastModify, err := utils.TimeParse(LastModifyStr)
		if err != nil {
			return err
		}
		head.LastModify = grmi.DateTime(LastModify)
		head.LastUser = utils.ValueToString(row[42], "")
		DemandSendTimeStr = utils.ValueToString(row[43], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			head.CreateTime = grmi.DateTime(DemandSendTime)
		}
		heads = append(heads, head)
	}
	// 获取 ArtDemandLst 上所有单元格
	rows, err = f.GetRows("ArtDemandLst")
	if err != nil {
		return err
	}
	lst := make([]model.SyncArtDemandLst, 0)
	for k, row := range rows {
		if k == 0 {
			continue
		}
		one := model.SyncArtDemandLst{}
		one.PlantNr = utils.ValueToInt(row[0], 0)
		one.DemandId = utils.ValueToString(row[1], "")
		one.Pos = utils.ValueToInt(row[2], 0)
		one.ArtId = utils.ValueToString(row[3], "")
		DemandTimeStr := utils.ValueToString(row[4], "")
		if DemandTimeStr != "0001-01-01 00:00:00" {
			DemandTime, _ := utils.TimeParse(DemandTimeStr)
			one.DemandTime = grmi.DateTime(DemandTime)
		}
		one.DemandYear = utils.ValueToInt(row[5], 0)
		one.DemandMonth = utils.ValueToInt(row[6], 0)
		one.DemandWeek = utils.ValueToInt(row[7], 0)
		DemandDateStr := utils.ValueToString(row[8], "")
		DemandDate, _ := utils.TimeParseyyyyMMdd(DemandDateStr)
		one.DemandDate = grmi.Date(DemandDate)
		one.DemandHour = utils.ValueToInt(row[9], 0)
		one.DemandQty = utils.ValueToFloat(row[10], 0.0)
		one.QtyUomId = utils.ValueToString(row[11], "")
		one.DemandObjId = utils.ValueToString(row[12], "")
		one.DemandType = utils.ValueToString(row[13], "")
		one.Status = utils.ValueToInt(row[14], 0)
		DemandSendTimeStr := utils.ValueToString(row[15], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, _ := utils.TimeParse(DemandSendTimeStr)
			one.DemandSendTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[16], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, _ := utils.TimeParse(DemandSendTimeStr)
			one.DemandRecieveTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[17], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, _ := utils.TimeParse(DemandSendTimeStr)
			one.DemandConfirmTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[18], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, _ := utils.TimeParse(DemandSendTimeStr)
			one.DemandCloseTime = grmi.DateTime(DemandSendTime)
		}
		one.DemandDeliveredQty = utils.ValueToFloat(row[19], 0.0)
		one.DemandCtrlPara1 = utils.ValueToInt(row[20], 0)
		one.DemandCtrlPara2 = utils.ValueToInt(row[21], 0)
		one.DemandCtrlPara3 = utils.ValueToString(row[22], "")
		one.DemandCtrlPara4 = utils.ValueToString(row[23], "")
		DemandSendTimeStr = utils.ValueToString(row[24], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, _ := utils.TimeParse(DemandSendTimeStr)
			one.DemandCtrlTime1 = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[25], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, _ := utils.TimeParse(DemandSendTimeStr)
			one.DemandCtrlTime2 = grmi.DateTime(DemandSendTime)
		}
		one.OrderStatus = utils.ValueToInt(row[26], 0)
		one.UnproducedQty = utils.ValueToFloat(row[27], 0.0)
		one.OrderType = utils.ValueToString(row[28], "")
		one.ProjectId = utils.ValueToString(row[29], "")
		one.DemandStatus = utils.ValueToInt(row[30], 0)
		one.PlanResourceId = utils.ValueToString(row[31], "")
		DemandSendTimeStr = utils.ValueToString(row[32], "")
		if DemandSendTimeStr != "0001-01-01" {
			DemandSendTime, err := utils.TimeParseyyyyMMdd(DemandSendTimeStr)
			if err != nil {
				return err
			}
			one.PlanStartDate = grmi.Date(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[33], "")
		if DemandSendTimeStr != "0001-01-01" {
			DemandSendTime, err := utils.TimeParseyyyyMMdd(DemandSendTimeStr)
			if err != nil {
				return err
			}
			one.PlanEndDate = grmi.Date(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[34], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			one.PlanStartTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[35], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			one.PlanEndTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[36], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			one.ActStartTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[37], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, err := utils.TimeParse(DemandSendTimeStr)
			if err != nil {
				return err
			}
			one.ActEndTime = grmi.DateTime(DemandSendTime)
		}
		DemandSendTimeStr = utils.ValueToString(row[38], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, _ := utils.TimeParse(DemandSendTimeStr)
			one.LastModify = grmi.DateTime(DemandSendTime)
		}
		one.LastUser = utils.ValueToString(row[39], "")
		DemandSendTimeStr = utils.ValueToString(row[40], "")
		if DemandSendTimeStr != "0001-01-01 00:00:00" {
			DemandSendTime, _ := utils.TimeParse(DemandSendTimeStr)
			one.CreateTime = grmi.DateTime(DemandSendTime)
		}
		lst = append(lst, one)
	}

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err = session.Begin()
	if err != nil {
		return
	}
	dao := dal.NewArtDemandHeadDAO(session, plantNr, "syncPost")
	logdao := dal.NewArtDemandLstDAO(session, plantNr, "syncPost")
	for _, v := range heads {
		ok, err := dao.SelectOne(v.ArtId, v.DemandId)
		if err != nil {
			session.Rollback()
			return err
		}
		if ok != nil {
			err = dao.SyncUpdateOne(&v)
			if err != nil {
				session.Rollback()
				return err
			}
		} else {
			err = dao.SyncInsertOne(&v)
			if err != nil {
				session.Rollback()
				return err
			}
		}
	}
	for _, vv := range lst {
		ok, err := logdao.SelectOne(vv.DemandId, vv.Pos)
		if err != nil {
			session.Rollback()
			return err
		}
		if ok != nil {
			err = logdao.SyncUpdateOne(&vv)
			if err != nil {
				session.Rollback()
				return err
			}
		} else {
			err = logdao.SyncInsertOne(&vv)
			if err != nil {
				session.Rollback()
				return err
			}
		}
	}
	session.Commit()
	return nil
}
