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

package implments

import (
	"LAPP_LF_MOM_BACKEND/conf"
	baseDal "LAPP_LF_MOM_BACKEND/dao/base"
	dal "LAPP_LF_MOM_BACKEND/dao/log"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/grmi"
	"LAPP_LF_MOM_BACKEND/infra/logger"
	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"
	json "github.com/json-iterator/go"
	"net/http"
	"reflect"
	"strconv"
	"strings"
	"time"
)

/******************************************************************************
 *
 * @Description              : ArtDemandHead的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-15 15:14:40
 *
 ******************************************************************************/
var DefaultConditionOfArtDemandHead = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.ArtDemandHead_ArtId.UrlParameterName:              grmi.NewConditionItem(meta.ArtDemandHead_ArtId, grmi.Equal, true),
		meta.ArtDemandHead_DemandId.UrlParameterName:           grmi.NewConditionItem(meta.ArtDemandHead_DemandId, grmi.Equal, true),
		meta.ArtDemandHead_DemandType.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHead_DemandType, grmi.Equal, false),
		meta.ArtDemandHead_DemandYear.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHead_DemandYear, grmi.Equal, false),
		meta.ArtDemandHead_DemandMonth.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandHead_DemandMonth, grmi.Equal, false),
		meta.ArtDemandHead_DemandWeek.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHead_DemandWeek, grmi.Equal, false),
		meta.ArtDemandHead_DemandDate.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHead_DemandDate, grmi.Approximate, false),
		meta.ArtDemandHead_DemandHour.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHead_DemandHour, grmi.Equal, false),
		meta.ArtDemandHead_DemandTime.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHead_DemandTime, grmi.Approximate, false),
		meta.ArtDemandHead_DemandQty.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandHead_DemandQty, grmi.Equal, false),
		meta.ArtDemandHead_QtyUomId.UrlParameterName:           grmi.NewConditionItem(meta.ArtDemandHead_QtyUomId, grmi.Equal, false),
		meta.ArtDemandHead_Status.UrlParameterName:             grmi.NewConditionItem(meta.ArtDemandHead_Status, grmi.Equal, false),
		meta.ArtDemandHead_DemandSendTime.UrlParameterName:     grmi.NewConditionItem(meta.ArtDemandHead_DemandSendTime, grmi.Approximate, false),
		meta.ArtDemandHead_DemandRecieveTime.UrlParameterName:  grmi.NewConditionItem(meta.ArtDemandHead_DemandRecieveTime, grmi.Approximate, false),
		meta.ArtDemandHead_DemandConfirmTime.UrlParameterName:  grmi.NewConditionItem(meta.ArtDemandHead_DemandConfirmTime, grmi.Approximate, false),
		meta.ArtDemandHead_DemandCloseTime.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHead_DemandCloseTime, grmi.Approximate, false),
		meta.ArtDemandHead_DemandDeliveredQty.UrlParameterName: grmi.NewConditionItem(meta.ArtDemandHead_DemandDeliveredQty, grmi.Equal, false),
		meta.ArtDemandHead_DemandCtrlPara1.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHead_DemandCtrlPara1, grmi.Equal, false),
		meta.ArtDemandHead_DemandCtrlPara2.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHead_DemandCtrlPara2, grmi.Equal, false),
		meta.ArtDemandHead_DemandCtrlPara3.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHead_DemandCtrlPara3, grmi.Equal, false),
		meta.ArtDemandHead_DemandCtrlPara4.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHead_DemandCtrlPara4, grmi.Equal, false),
		meta.ArtDemandHead_DemandCtrlTime1.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHead_DemandCtrlTime1, grmi.Approximate, false),
		meta.ArtDemandHead_DemandCtrlTime2.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHead_DemandCtrlTime2, grmi.Approximate, false),
		meta.ArtDemandHead_OrderStatus.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandHead_OrderStatus, grmi.Equal, false),
		meta.ArtDemandHead_UnproducedQty.UrlParameterName:      grmi.NewConditionItem(meta.ArtDemandHead_UnproducedQty, grmi.Equal, false),
		meta.ArtDemandHead_OrderType.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandHead_OrderType, grmi.Equal, false),
		meta.ArtDemandHead_WorkOrderId.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandHead_WorkOrderId, grmi.Equal, false),
		meta.ArtDemandHead_ProjectId.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandHead_ProjectId, grmi.Equal, false),
		meta.ArtDemandHead_DemandStatus.UrlParameterName:       grmi.NewConditionItem(meta.ArtDemandHead_DemandStatus, grmi.Equal, false),
		meta.ArtDemandHead_DemandCtrlPara5.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHead_DemandCtrlPara5, grmi.Equal, false),
		meta.ArtDemandHead_DemandCtrlPara6.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHead_DemandCtrlPara6, grmi.Equal, false),
		meta.ArtDemandHead_ChangeStatus.UrlParameterName:       grmi.NewConditionItem(meta.ArtDemandHead_ChangeStatus, grmi.Equal, false),
		meta.ArtDemandHead_PlanResourceId.UrlParameterName:     grmi.NewConditionItem(meta.ArtDemandHead_PlanResourceId, grmi.Equal, false),
		meta.ArtDemandHead_PlanStartDate.UrlParameterName:      grmi.NewConditionItem(meta.ArtDemandHead_PlanStartDate, grmi.Approximate, false),
		meta.ArtDemandHead_PlanEndDate.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandHead_PlanEndDate, grmi.Approximate, false),
		meta.ArtDemandHead_PlanStartTime.UrlParameterName:      grmi.NewConditionItem(meta.ArtDemandHead_PlanStartTime, grmi.Approximate, false),
		meta.ArtDemandHead_PlanEndTime.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandHead_PlanEndTime, grmi.Approximate, false),
		meta.ArtDemandHead_ActStartTime.UrlParameterName:       grmi.NewConditionItem(meta.ArtDemandHead_ActStartTime, grmi.Approximate, false),
		meta.ArtDemandHead_ActEndTime.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHead_ActEndTime, grmi.Approximate, false),
		meta.ArtDemandHead_CancelQty.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandHead_CancelQty, grmi.Equal, false),
		meta.ArtDemandHead_LastModify.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHead_LastModify, grmi.Approximate, false),
		meta.ArtDemandHead_LastUser.UrlParameterName:           grmi.NewConditionItem(meta.ArtDemandHead_LastUser, grmi.Equal, false),
		meta.ArtDemandHead_CreateTime.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHead_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : ArtDemandHead的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-03-23 10:43:27
 *
 ******************************************************************************/
var DefaultConditionOfArtDemandHeadAndPaging = grmi.NewCondition(
	DefaultConditionOfArtDemandHead.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : ArtDemandHeadServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : ArtDemandHead的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-05-10 16:21:26
 *
 ******************************************************************************/
type ArtDemandHeadServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewArtDemandHeadDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个ArtDemandHeadDAOImplement实例
 *
 * @Return Value             : ArtDemandHeadDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-03-23 10:43:27
 *
 ******************************************************************************/
func NewArtDemandHeadServiceImplement() *ArtDemandHeadServiceImplement {
	return &ArtDemandHeadServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandHeadService.InsertOne
 *
 ******************************************************************************/
func (impl *ArtDemandHeadServiceImplement) InsertOne(user *models.Usertab, entity *model.ArtDemandHead) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandHeadDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.ArtId, entity.DemandId)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	snr := new(models.Snrtab)
	snr.Finr = user.Pid
	demandId, err := snr.GetNextSnr("Demand")
	if err != nil {
		return err
	}
	entity.DemandId = demandId
	articleDao := baseDal.NewArticleDAO(session, user.Pid, user.Userid)
	article, err := articleDao.SelectOne(entity.ArtId)
	if err != nil {
		return err
	}
	if article == nil {
		return grmi.NewBusinessError("不存在对应的物料, ArtId: " + entity.ArtId + ", demandId: " + entity.DemandId)
	}
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandHeadService.DeleteOne
 *
 ******************************************************************************/
func (impl *ArtDemandHeadServiceImplement) DeleteOne(user *models.Usertab, artId string, demandId string) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewArtDemandHeadDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(artId, demandId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(artId, demandId)
	if err != nil {
		session.Rollback()
		return err
	}
	artDemandLstDao := dal.NewArtDemandLstDAO(session, user.Pid, user.Userid)
	artDemandLi := []model.ArtDemandItem{{
		ArtId:    artId,
		DemandId: demandId,
	},
	}
	err = artDemandLstDao.DeleteByHead(&artDemandLi)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandHeadService.SelectOne
 *
 ******************************************************************************/
func (impl *ArtDemandHeadServiceImplement) SelectOne(user *models.Usertab, artId string, demandId string) (*model.ArtDemandHead, error) {

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandHeadService.UpdateOne
 *
 ******************************************************************************/
func (impl *ArtDemandHeadServiceImplement) UpdateOne(user *models.Usertab, entity *model.ArtDemandHead) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandHeadDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.ArtId, entity.DemandId)
	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/log/ArtDemandHeadService.Insert
 *
 ******************************************************************************/
func (impl *ArtDemandHeadServiceImplement) Insert(user *models.Usertab, entities *[]model.ArtDemandHead) error {

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

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

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

	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/ArtDemandHeadService.Delete
 *
 ******************************************************************************/
func (impl *ArtDemandHeadServiceImplement) Delete(user *models.Usertab, entities *[]model.ArtDemandHead) error {

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

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

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

	err = dao.Delete(entities)

	if err != nil {
		session.Rollback()
		return err
	}
	artDemandLstDao := dal.NewArtDemandLstDAO(session, user.Pid, user.Userid)
	artDemandLi := make([]model.ArtDemandItem, len(*entities))
	for index, entity := range *entities {
		artDemandLi[index] = model.ArtDemandItem{
			ArtId:    entity.ArtId,
			DemandId: entity.DemandId,
		}
	}
	err = artDemandLstDao.DeleteByHead(&artDemandLi)
	if err != nil {
		session.Rollback()
		return nil
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

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

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

	condition := DefaultConditionOfArtDemandHeadAndPaging
	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.ArtDemandHead_DemandId.UrlParameterName: search,
		}
		innerPredicates, err := condition.BuildPredicates(params)
		if err != nil {
			return nil, err
		}
		predicates = append(predicates, innerPredicates...)
	}
	dao := dal.NewArtDemandHeadDAO(session, user.Pid, user.Userid)

	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.ArtDemandHead_DemandDate.NewPredicate(grmi.Include)}
					predicates = append(predicates, predicate...)
				}
			} else {
				if urgency == model.UrgencyNot {
					predicate := []grmi.Predicate{meta.ArtDemandHead_DemandDate.NewPredicate(grmi.GreaterThen, dateString)}
					predicates = append(predicates, predicate...)
				} else if urgency == model.UrgencyNormal {
					predicate1 := []grmi.Predicate{meta.ArtDemandHead_DemandDate.NewPredicate(grmi.GreaterOrEqual, today)}
					predicate2 := []grmi.Predicate{meta.ArtDemandHead_DemandDate.NewPredicate(grmi.LessOrEqual, dateString)}
					predicates = append(predicates, predicate1...)
					predicates = append(predicates, predicate2...)
				} else {
					predicate := []grmi.Predicate{meta.ArtDemandHead_DemandDate.NewPredicate(grmi.LessThen, today)}
					predicates = append(predicates, predicate...)
				}
				predicate := []grmi.Predicate{meta.ArtDemandHead_Status.NewPredicate(grmi.NotEqual, model.AccomplishedStatus)}
				predicates = append(predicates, predicate...)
			}
		}

	}

	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.ArtDemandHead_WorkOrderId)
	if condition.Fill(urlParameters) {
		result, err := dao.SelectAndPaging(condition.Paging, predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		artDemandHeadLi := result.Records.([]model.ArtDemandHead)
		baseDao := baseDal.NewArticleDAO(session, user.Pid, user.Userid)
		responseLi := make([]model.ArtDemandHeadResponseItem, 0, len(artDemandHeadLi))

		for _, artDemandHead := range artDemandHeadLi {
			data := artDemandHead
			var responseItem model.ArtDemandHeadResponseItem
			responseItem.ArtDemandHead = &data
			if data.ProjectId == baseModel.A30PorjectId {
				responseItem.ArtDesc = data.DemandCtrlPara3
			} else {
				article, err := baseDao.SelectOne(artDemandHead.ArtId)
				if err != nil {
					return nil, err
				}
				if article != nil {
					responseItem.ArtDesc = article.Descr1
				}
			}
			if artDemandHead.Status == model.AccomplishedStatus {
				responseItem.UrgencyDegree = 0
				responseItem.SurplusDays = 0
			} else {
				demandDate := artDemandHead.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.ArtDemandHeadResponseItem, 0, len(result))
		for _, artDemandHead := range result {
			data := artDemandHead
			var responseItem model.ArtDemandHeadResponseItem
			responseItem.ArtDemandHead = &data
			if data.ProjectId == baseModel.A30PorjectId {
				responseItem.ArtDesc = data.DemandCtrlPara3
			} else {
				article, err := baseDao.SelectOne(artDemandHead.ArtId)
				if err != nil {
					return nil, err
				}
				if article != nil {
					responseItem.ArtDesc = article.Descr1
				}
			}

			if artDemandHead.Status == model.AccomplishedStatus {
				responseItem.UrgencyDegree = 0
				responseItem.SurplusDays = 0
			} else {
				demandDate := artDemandHead.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/ArtDemandHeadService.Update
 *
 ******************************************************************************/
func (impl *ArtDemandHeadServiceImplement) Update(user *models.Usertab, entities *[]model.ArtDemandHead) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.ArtId, entity.DemandId)
		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/ArtDemandHeadService.ExportExcel
 *
 ******************************************************************************/
func (impl *ArtDemandHeadServiceImplement) ExportExcel(user *models.Usertab, urlParameters map[string]string) (interface{}, error) {
	grmi.Log(user, "/services/log/implments/ArtDemandHeadService.service.impl.go", "ExportExcelArtDemandHead", "导出ArtDemandHead报表")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	condition := DefaultConditionOfArtDemandHeadAndPaging
	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.ArtDemandHead_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.ArtDemandHead_DemandDate.NewPredicate(grmi.Include)}
					predicates = append(predicates, predicate...)
				}
			} else {
				if urgency == model.UrgencyNot {
					predicate := []grmi.Predicate{meta.ArtDemandHead_DemandDate.NewPredicate(grmi.GreaterThen, dateString)}
					predicates = append(predicates, predicate...)
				} else if urgency == model.UrgencyNormal {
					predicate1 := []grmi.Predicate{meta.ArtDemandHead_DemandDate.NewPredicate(grmi.GreaterOrEqual, today)}
					predicate2 := []grmi.Predicate{meta.ArtDemandHead_DemandDate.NewPredicate(grmi.LessOrEqual, dateString)}
					predicates = append(predicates, predicate1...)
					predicates = append(predicates, predicate2...)
				} else {
					predicate := []grmi.Predicate{meta.ArtDemandHead_DemandDate.NewPredicate(grmi.LessThen, today)}
					predicates = append(predicates, predicate...)
				}
				predicate := []grmi.Predicate{meta.ArtDemandHead_Status.NewPredicate(grmi.NotEqual, model.AccomplishedStatus)}
				predicates = append(predicates, predicate...)
			}
		}

	}
	dao := dal.NewArtDemandHeadDAO(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.ArtDemandHead_WorkOrderId)
	result, err := dao.Select(predicates, condition.OrderByFields)
	if err != nil {
		return nil, err
	}
	responseLi := make([]model.ArtDemandHeadResponseItemTemp, 0, len(result))
	for _, artDemandHead := range result {
		data := artDemandHead
		var responseItem model.ArtDemandHeadResponseItemTemp
		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 = "未完成"
		}
		var changeStatus string
		if data.ChangeStatus == model.DemandChangeStatusTrue {
			changeStatus = "变更"
		} else {
			changeStatus = "未变更"
		}
		responseItem.PlantNr = data.PlantNr
		responseItem.ArtId = data.ArtId
		responseItem.DemandCtrlPara3 = data.DemandCtrlPara3
		responseItem.DemandId = data.DemandId
		responseItem.DemandType = data.DemandType
		responseItem.DemandYear = data.DemandYear
		responseItem.DemandMonth = data.DemandMonth
		responseItem.DemandWeek = data.DemandWeek
		responseItem.DemandDate = data.DemandDate
		responseItem.DemandHour = data.DemandHour
		responseItem.DemandTime = data.DemandTime
		responseItem.DemandQty = data.DemandQty
		responseItem.UnproducedQty = data.UnproducedQty
		responseItem.CancelQty = data.CancelQty
		responseItem.QtyUomId = data.QtyUomId
		responseItem.DemandSendTime = data.DemandSendTime
		responseItem.DemandRecieveTime = data.DemandRecieveTime
		responseItem.DemandConfirmTime = data.DemandConfirmTime
		responseItem.DemandCloseTime = data.DemandCloseTime
		responseItem.DemandDeliveredQty = data.DemandDeliveredQty
		responseItem.ChangeStatus = changeStatus
		responseItem.DemandCtrlPara4 = data.DemandCtrlPara4
		responseItem.OrderStatus = orderStatus
		responseItem.OrderType = data.OrderType
		responseItem.WorkOrderId = data.WorkOrderId
		responseItem.ProjectId = data.ProjectId
		responseItem.DemandStatus = demandStatus
		responseItem.PlanResourceId = data.PlanResourceId
		responseItem.LastModify = data.LastModify
		responseItem.LastUser = data.LastUser
		responseItem.CreateTime = data.CreateTime
		if artDemandHead.Status == model.AccomplishedStatus {
			responseItem.UrgencyDegree = "不紧急"
			responseItem.SurplusDays = 0
		} else {
			demandDate := artDemandHead.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",
		"项目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/ArtDemandHeadService.ChangeArtDemandLstStatus
 *
 ******************************************************************************/
func (impl *ArtDemandHeadServiceImplement) ChangeArtDemandHeadStatus(user *models.Usertab, records []model.ArtDemandHeadStatusChange, operateType string) error {
	grmi.Log(user, "/services/log/implments/LOG_ArtDemandHead.service.impl.go", "ChangeArtDemandHeadStatus", "ArtDemandHead状态修改")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewArtDemandHeadDAO(session, user.Pid, user.Userid)
	artDemandHeadLi := make([]model.ArtDemandHead, 0, len(records))
	// 校验每个ArtDemandHead的状态 再修改status
	for _, record := range records {

		artDemandHead, err := dao.SelectOne(record.ArtId, record.DemandId)
		if err != nil {
			return err
		}
		if artDemandHead == nil {
			return grmi.NewBusinessError(fmt.Sprintf("该条数据不存在, artId: %s, demandId: %s", record.ArtId, record.DemandId))
		}
		switch operateType {
		case "receive":
			if artDemandHead.Status != model.WaitReceivingStatus {
				return grmi.NewBusinessError(fmt.Sprintf("计划明细状态与您的操作不相符,artID: %s demandId: %s", record.ArtId, record.DemandId))
			}
			artDemandHead.Status = model.ReceivedStatus
			artDemandHead.DemandRecieveTime = grmi.DateTime(time.Now())
		case "confirm":
			if artDemandHead.Status != model.ReceivedStatus {
				return grmi.NewBusinessError(fmt.Sprintf("计划明细状态与您的操作不相符,artID: %s demandId: %s", record.ArtId, record.DemandId))
			}
			artDemandHead.Status = model.ConfirmedStatus
			artDemandHead.DemandConfirmTime = grmi.DateTime(time.Now())
		case "accomplish":
			if artDemandHead.Status != model.ConfirmedStatus {
				return grmi.NewBusinessError(fmt.Sprintf("计划明细状态与您的操作不相符,artID: %s demandId: %s", record.ArtId, record.DemandId))
			}
			artDemandHead.Status = model.AccomplishedStatus
			artDemandHead.DemandCloseTime = grmi.DateTime(time.Now())
		}
		artDemandHeadLi = append(artDemandHeadLi, *artDemandHead)
	}
	err = dao.UpdateWithoutModifyTime(&artDemandHeadLi)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

func (impl *ArtDemandHeadServiceImplement) TransferDataToOrigin(getTimeUrl, postFileUrl string, plantNr int) {
	log, _ := logger.NewLogger("datasync", "Log")
	headers := map[string]string{
		"Host":                      conf.DbConfig.PortalHost,
		"User-Agent":                "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
		"Upgrade-Insecure-Requests": "1",
		"Accept-Language":           "en-US,en;q=0.9",
	}
	timeBody, err := utils.GetRequest(getTimeUrl, headers)
	if err != nil {
		log.Error("DataToOrigin get time from origin failed, error:" + err.Error())
		return
	}
	var response baseModel.Response
	err = json.Unmarshal(timeBody, &response)
	if err != nil {
		log.Error("DataToOrigin unmarshal time body failed, error:"+err.Error(), "body: "+string(timeBody))
		return
	}
	log.Debug("DataToOrigin get time response:" + string(timeBody))
	var lastTime string
	if response.Code == http.StatusBadRequest && response.Msg == "数据不存在!" {
		lastTime = "2000-01-01 00:00:00"
	} else {
		if response.Code != http.StatusOK {
			log.Info("DataToOrigin get time data failed, response:" + string(timeBody))
			return
		}
		lastTime = response.Data
	}
	_, err = time.Parse("2006-01-02 15:04:05", lastTime)
	if err != nil {
		log.Error("DataToOrigin parse time failed, error:"+err.Error(), "time string:"+lastTime)
		return
	}
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	headDao := dal.NewArtDemandHeadDAO(session, plantNr, "datasync")
	lstDao := dal.NewArtDemandLstDAO(session, plantNr, "datasync")
	headLi, err := headDao.SelectByLastModifyTime(lastTime)
	if err != nil {
		log.Error("DataToOrigin get art demand head failed, error:" + err.Error())
		return
	}
	if len(headLi) == 0 {
		log.Debug("DataToOrigin get art demand head is zero")
		return
	}
	lstLi := make([]model.ArtDemandLst, 0)
	for _, head := range headLi {
		tempLstLi, err := lstDao.SelectWithoutAuthority([]grmi.Predicate{meta.ArtDemandLst_DemandId.NewPredicate(grmi.Equal, head.DemandId)}, []grmi.Field{meta.ArtDemandLst_LastModify})
		if err != nil {
			log.Error("DataToOrigin get art demand lst failed, error:"+err.Error(), "demandID:"+head.DemandId)
			return
		}
		lstLi = append(lstLi, tempLstLi...)
	}
	filepath, err := impl.SaveToExcel(&headLi, &lstLi)
	if err != nil {
		log.Error("DataToOrigin save data to excel failed, error:" + err.Error())
		return
	}
	nameLi := strings.Split(filepath, "\\")
	resp, err := utils.PostFormDataWithSingleFile(postFileUrl, filepath, nameLi[len(nameLi)-1], headers)
	if err != nil {
		log.Error("DataToOrigin post file to origin failed, error:" + err.Error())
		return
	}
	var postResp baseModel.Response
	err = json.Unmarshal(resp, &postResp)
	if err != nil {
		log.Error("DataToOrigin unmarshal post file response failed, error:"+err.Error(), "data:"+string(resp))
		return
	}
	log.Debug("DataToOrigin post file response:" + string(resp))
	if postResp.Code != http.StatusOK {
		log.Error("DataToOrigin post file response code is not OK, data:" + string(resp))
		return
	}
	return
}

func (impl *ArtDemandHeadServiceImplement) SaveToExcel(headLi *[]model.ArtDemandHead, lstLi *[]model.ArtDemandLst) (filepath string, err error) {
	file := excelize.NewFile()
	file.DeleteSheet("Sheet1")
	file.NewSheet("ArtDemandHead")
	file.NewSheet("ArtDemandLst")
	{
		streamWriter, err := file.NewStreamWriter("ArtDemandHead")
		if err != nil {
			return "", err
		}
		for index, item := range *headLi {
			if index == 0 {
				typeOfS := reflect.TypeOf(item)
				row := make([]interface{}, typeOfS.NumField())
				for i := 0; i < typeOfS.NumField(); i++ {
					row[i] = typeOfS.Field(i).Name
				}
				cell, _ := excelize.CoordinatesToCellName(1, 1)
				if err := streamWriter.SetRow(cell, row); err != nil {
					return "", err
				}
			}
			reflectValue := reflect.ValueOf(item)
			row := make([]interface{}, reflectValue.NumField())
			for i := 0; i < reflectValue.NumField(); i++ {
				var date grmi.Date
				var datetime grmi.DateTime
				if reflect.TypeOf(date) == reflectValue.Field(i).Type() {
					filed := reflectValue.Field(i).Interface().(grmi.Date)
					row[i] = filed.ToString()
				} else if reflect.TypeOf(datetime) == reflectValue.Field(i).Type() {
					filed := reflectValue.Field(i).Interface().(grmi.DateTime)
					row[i] = filed.ToString()
				} else {
					row[i] = reflectValue.Field(i)
				}
			}
			cell, _ := excelize.CoordinatesToCellName(1, index+2)
			if err := streamWriter.SetRow(cell, row); err != nil {
				return "", err
			}
		}
		if err := streamWriter.Flush(); err != nil {
			return "", err
		}
	}
	{
		streamWriter, err := file.NewStreamWriter("ArtDemandLst")
		if err != nil {
			return "", err
		}
		for index, item := range *lstLi {
			if index == 0 {
				typeOfS := reflect.TypeOf(item)
				row := make([]interface{}, typeOfS.NumField())
				for i := 0; i < typeOfS.NumField(); i++ {
					row[i] = typeOfS.Field(i).Name
				}
				cell, _ := excelize.CoordinatesToCellName(1, 1)
				if err := streamWriter.SetRow(cell, row); err != nil {
					return "", err
				}
			}
			reflectValue := reflect.ValueOf(item)
			row := make([]interface{}, reflectValue.NumField())
			for i := 0; i < reflectValue.NumField(); i++ {
				var date grmi.Date
				var datetime grmi.DateTime
				if reflect.TypeOf(date) == reflectValue.Field(i).Type() {
					filed := reflectValue.Field(i).Interface().(grmi.Date)
					row[i] = filed.ToString()
				} else if reflect.TypeOf(datetime) == reflectValue.Field(i).Type() {
					filed := reflectValue.Field(i).Interface().(grmi.DateTime)
					row[i] = filed.ToString()
				} else {
					row[i] = reflectValue.Field(i)
				}
			}
			cell, _ := excelize.CoordinatesToCellName(1, index+2)
			if err := streamWriter.SetRow(cell, row); err != nil {
				return "", err
			}
		}
		if err := streamWriter.Flush(); err != nil {
			return "", err
		}
	}
	filename := utils.MakeOrderSn("datasync") + ".xlsx"
	dirname, err := utils.GetCurrentPath("web/public/datasync")
	if err != nil {
		return "", err
	}
	filepath = dirname + "/" + filename
	err = file.SaveAs(filepath)
	if err != nil {
		return "", err
	}
	//pathLi := strings.Split(filepath, "web\\")
	//if len(pathLi) != 2 {
	//	return "", errors.New("导出失败,请重试")
	//}
	//return pathLi[1], nil
	return filepath, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandLstService.SelectLastModify
 *
 ******************************************************************************/
func (impl *ArtDemandHeadServiceImplement) SelectLastModify(plantNr int) (string, error) {

	//grmi.Log(user, "/services/om/implments/WorkOrder.service.impl.go", "SelectLastModify", "查询最后一个WorkOrder订单")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandHeadDAO(session, plantNr, "syncPost")
	data, err := dao.SelectLastModify()
	if err != nil {
		return "", err
	}
	return data.LastModify.ToString(), nil
}
