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

package implments

import (
	"LAPP_LF_MOM_BACKEND/conf"
	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"
	"strings"
)

/******************************************************************************
 *
 * @Description              : ArtDemandHeadCache的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-15 15:14:40
 *
 ******************************************************************************/
var DefaultConditionOfArtDemandHeadCache = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.ArtDemandHeadCache_ArtId.UrlParameterName:              grmi.NewConditionItem(meta.ArtDemandHeadCache_ArtId, grmi.Equal, true),
		meta.ArtDemandHeadCache_DemandId.UrlParameterName:           grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandId, grmi.Equal, true),
		meta.ArtDemandHeadCache_DemandType.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandType, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandYear.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandYear, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandMonth.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandMonth, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandWeek.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandWeek, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandDate.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandDate, grmi.Approximate, false),
		meta.ArtDemandHeadCache_DemandHour.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandHour, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandTime.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandTime, grmi.Approximate, false),
		meta.ArtDemandHeadCache_DemandQty.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandQty, grmi.Equal, false),
		meta.ArtDemandHeadCache_QtyUomId.UrlParameterName:           grmi.NewConditionItem(meta.ArtDemandHeadCache_QtyUomId, grmi.Equal, false),
		meta.ArtDemandHeadCache_Status.UrlParameterName:             grmi.NewConditionItem(meta.ArtDemandHeadCache_Status, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandSendTime.UrlParameterName:     grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandSendTime, grmi.Approximate, false),
		meta.ArtDemandHeadCache_DemandRecieveTime.UrlParameterName:  grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandRecieveTime, grmi.Approximate, false),
		meta.ArtDemandHeadCache_DemandConfirmTime.UrlParameterName:  grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandConfirmTime, grmi.Approximate, false),
		meta.ArtDemandHeadCache_DemandCloseTime.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandCloseTime, grmi.Approximate, false),
		meta.ArtDemandHeadCache_DemandDeliveredQty.UrlParameterName: grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandDeliveredQty, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandCtrlPara1.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandCtrlPara1, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandCtrlPara2.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandCtrlPara2, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandCtrlPara3.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandCtrlPara3, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandCtrlPara4.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandCtrlPara4, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandCtrlTime1.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandCtrlTime1, grmi.Approximate, false),
		meta.ArtDemandHeadCache_DemandCtrlTime2.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandCtrlTime2, grmi.Approximate, false),
		meta.ArtDemandHeadCache_OrderStatus.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandHeadCache_OrderStatus, grmi.Equal, false),
		meta.ArtDemandHeadCache_UnproducedQty.UrlParameterName:      grmi.NewConditionItem(meta.ArtDemandHeadCache_UnproducedQty, grmi.Equal, false),
		meta.ArtDemandHeadCache_OrderType.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandHeadCache_OrderType, grmi.Equal, false),
		meta.ArtDemandHeadCache_WorkOrderId.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandHeadCache_WorkOrderId, grmi.Equal, false),
		meta.ArtDemandHeadCache_ProjectId.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandHeadCache_ProjectId, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandStatus.UrlParameterName:       grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandStatus, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandCtrlPara5.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandCtrlPara5, grmi.Equal, false),
		meta.ArtDemandHeadCache_DemandCtrlPara6.UrlParameterName:    grmi.NewConditionItem(meta.ArtDemandHeadCache_DemandCtrlPara6, grmi.Equal, false),
		meta.ArtDemandHeadCache_ChangeStatus.UrlParameterName:       grmi.NewConditionItem(meta.ArtDemandHeadCache_ChangeStatus, grmi.Equal, false),
		meta.ArtDemandHeadCache_PlanResourceId.UrlParameterName:     grmi.NewConditionItem(meta.ArtDemandHeadCache_PlanResourceId, grmi.Equal, false),
		meta.ArtDemandHeadCache_PlanStartDate.UrlParameterName:      grmi.NewConditionItem(meta.ArtDemandHeadCache_PlanStartDate, grmi.Approximate, false),
		meta.ArtDemandHeadCache_PlanEndDate.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandHeadCache_PlanEndDate, grmi.Approximate, false),
		meta.ArtDemandHeadCache_PlanStartTime.UrlParameterName:      grmi.NewConditionItem(meta.ArtDemandHeadCache_PlanStartTime, grmi.Approximate, false),
		meta.ArtDemandHeadCache_PlanEndTime.UrlParameterName:        grmi.NewConditionItem(meta.ArtDemandHeadCache_PlanEndTime, grmi.Approximate, false),
		meta.ArtDemandHeadCache_ActStartTime.UrlParameterName:       grmi.NewConditionItem(meta.ArtDemandHeadCache_ActStartTime, grmi.Approximate, false),
		meta.ArtDemandHeadCache_ActEndTime.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHeadCache_ActEndTime, grmi.Approximate, false),
		meta.ArtDemandHeadCache_CancelQty.UrlParameterName:          grmi.NewConditionItem(meta.ArtDemandHeadCache_CancelQty, grmi.Equal, false),
		meta.ArtDemandHeadCache_LastModify.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHeadCache_LastModify, grmi.Approximate, false),
		meta.ArtDemandHeadCache_LastUser.UrlParameterName:           grmi.NewConditionItem(meta.ArtDemandHeadCache_LastUser, grmi.Equal, false),
		meta.ArtDemandHeadCache_CreateTime.UrlParameterName:         grmi.NewConditionItem(meta.ArtDemandHeadCache_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : ArtDemandHeadCache的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-09 14:00:44
 *
 ******************************************************************************/
var DefaultConditionOfArtDemandHeadCacheAndPaging = grmi.NewCondition(
	DefaultConditionOfArtDemandHeadCache.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : ArtDemandHeadCacheServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : ArtDemandHeadCache的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-09 14:00:44
 *
 ******************************************************************************/
type ArtDemandHeadCacheServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewArtDemandHeadCacheDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个ArtDemandHeadCacheDAOImplement实例
 *
 * @Return Value             : ArtDemandHeadCacheDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-06-09 14:00:44
 *
 ******************************************************************************/
func NewArtDemandHeadCacheServiceImplement() *ArtDemandHeadCacheServiceImplement {
	return &ArtDemandHeadCacheServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandHeadCacheService.InsertOne
 *
 ******************************************************************************/
func (impl *ArtDemandHeadCacheServiceImplement) InsertOne(user *models.Usertab, entity *model.ArtDemandHeadCache) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandHeadCacheDAO(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.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

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

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandHeadCacheDAO(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 {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandHeadCacheService.SelectOne
 *
 ******************************************************************************/
func (impl *ArtDemandHeadCacheServiceImplement) SelectOne(user *models.Usertab, artId string, demandId string) (*model.ArtDemandHeadCache, error) {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandHeadCacheDAO(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/ArtDemandHeadCacheService.UpdateOne
 *
 ******************************************************************************/
func (impl *ArtDemandHeadCacheServiceImplement) UpdateOne(user *models.Usertab, entity *model.ArtDemandHeadCache) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandHeadCacheDAO(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/ArtDemandHeadCacheService.Insert
 *
 ******************************************************************************/
func (impl *ArtDemandHeadCacheServiceImplement) Insert(user *models.Usertab, entities *[]model.ArtDemandHeadCache) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandHeadCacheDAO(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 {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandHeadCacheService.Delete
 *
 ******************************************************************************/
func (impl *ArtDemandHeadCacheServiceImplement) Delete(user *models.Usertab, entities *[]model.ArtDemandHeadCache) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandHeadCacheDAO(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 {
		return err
	}
	return nil
}

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

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

	condition := DefaultConditionOfArtDemandHeadCacheAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewArtDemandHeadCacheDAO(session, user.Pid, user.Userid)
	condition.OrderByFields = append(condition.OrderByFields, meta.ArtDemandHeadCache_WorkOrderId)
	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/log/ArtDemandHeadCacheService.Update
 *
 ******************************************************************************/
func (impl *ArtDemandHeadCacheServiceImplement) Update(user *models.Usertab, entities *[]model.ArtDemandHeadCache) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewArtDemandHeadCacheDAO(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 {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandHeadCacheService.Update
 *
 ******************************************************************************/
func (impl *ArtDemandHeadCacheServiceImplement) TransferCacheDataToOrigin(plantNr int, postFileUrl string) {
	user := "datasync"
	log, _ := logger.NewLogger(user, "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",
	}
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	headDao := dal.NewArtDemandHeadCacheDAO(session, plantNr, user)
	lstDao := dal.NewArtDemandLstCacheDAO(session, plantNr, user)
	headLi, err := headDao.Select(nil, nil)
	if err != nil {
		log.Error("TransferCacheDataToOrigin get art demand head cache failed, error:" + err.Error())
		return
	}
	lstLi, err := lstDao.Select(nil, nil)
	if err != nil {
		log.Error("TransferCacheDataToOrigin get art demand lst cache failed, error:" + err.Error())
		return
	}
	filepath, err := impl.SaveToExcel(&headLi, &lstLi)
	if err != nil {
		log.Error("TransferCacheDataToOrigin 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("TransferCacheDataToOrigin post file to origin failed, error:" + err.Error())
		return
	}
	var postResp baseModel.Response
	err = json.Unmarshal(resp, &postResp)
	if err != nil {
		log.Error("TransferCacheDataToOrigin unmarshal post file response failed, error:"+err.Error(), "data:"+string(resp))
		return
	}
	log.Debug("TransferCacheDataToOrigin post file response:" + string(resp))
	if postResp.Code != http.StatusOK {
		log.Error("TransferCacheDataToOrigin post file response code is not OK, data:" + string(resp))
		return
	}
	return
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/log/ArtDemandHeadCacheService.Update
 *
 ******************************************************************************/
func (impl *ArtDemandHeadCacheServiceImplement) SaveToExcel(headLi *[]model.ArtDemandHeadCache, lstLi *[]model.ArtDemandLstCache) (filepath string, err error) {
	file := excelize.NewFile()
	file.DeleteSheet("Sheet1")
	file.NewSheet("ArtDemandHeadCache")
	file.NewSheet("ArtDemandLstCache")
	{
		streamWriter, err := file.NewStreamWriter("ArtDemandHeadCache")
		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("ArtDemandLstCache")
		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/ArtDemandHeadCacheService.ExportExcel
 *
 ******************************************************************************/
func (impl *ArtDemandHeadCacheServiceImplement) ExportExcel(user *models.Usertab, urlParameters map[string]string) (interface{}, error) {

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

	condition := DefaultConditionOfArtDemandHeadCacheAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewArtDemandHeadCacheDAO(session, user.Pid, user.Userid)
	condition.OrderByFields = append(condition.OrderByFields, meta.ArtDemandHeadCache_WorkOrderId)
	result, err := dao.Select(predicates, condition.OrderByFields)
	if err != nil {
		return nil, err
	}
	exportLi := make([]model.ArtDemandHeadCacheExport, 0, len(result))
	for _, artDemandHeadCache := range result {
		var data model.ArtDemandHeadCacheExport
		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 artDemandHeadCache.OrderStatus == statusInt {
				orderStatus = statusString
				break
			}
		}
		var demandStatus string
		if artDemandHeadCache.DemandStatus == model.DemandOrderStatusAccomplish {
			demandStatus = "完成"
		} else {
			demandStatus = "未完成"
		}
		data.PlantNr = artDemandHeadCache.PlantNr
		data.ArtId = artDemandHeadCache.ArtId
		data.DemandCtrlPara3 = artDemandHeadCache.DemandCtrlPara3
		data.DemandId = artDemandHeadCache.DemandId
		data.DemandType = artDemandHeadCache.DemandType
		data.DemandYear = artDemandHeadCache.DemandYear
		data.DemandMonth = artDemandHeadCache.DemandMonth
		data.DemandWeek = artDemandHeadCache.DemandWeek
		data.DemandDate = artDemandHeadCache.DemandDate
		data.DemandHour = artDemandHeadCache.DemandHour
		data.DemandTime = artDemandHeadCache.DemandTime
		data.DemandQty = artDemandHeadCache.DemandQty
		data.QtyUomId = artDemandHeadCache.QtyUomId
		data.UnproducedQty = artDemandHeadCache.UnproducedQty
		data.CancelQty = artDemandHeadCache.CancelQty
		data.OrderStatus = orderStatus
		data.OrderType = artDemandHeadCache.OrderType
		data.WorkOrderId = artDemandHeadCache.WorkOrderId
		data.ProjectId = artDemandHeadCache.ProjectId
		data.PlanResourceId = artDemandHeadCache.PlanResourceId
		data.DemandStatus = demandStatus
		data.LastModify = artDemandHeadCache.LastModify
		data.LastUser = artDemandHeadCache.LastUser
		data.CreateTime = artDemandHeadCache.CreateTime
		exportLi = append(exportLi, data)
	}
	temp := make([]interface{}, len(exportLi))
	for index, item := range exportLi {
		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

}
