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

package implments

import (
	baseDal "LAPP_ACURA_MOM_BACKEND/dao/base"
	dalMe "LAPP_ACURA_MOM_BACKEND/dao/me"
	dal "LAPP_ACURA_MOM_BACKEND/dao/pln"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	"LAPP_ACURA_MOM_BACKEND/infra/logger"
	meta "LAPP_ACURA_MOM_BACKEND/meta/pln"
	baseModel "LAPP_ACURA_MOM_BACKEND/models/base"
	modelMe "LAPP_ACURA_MOM_BACKEND/models/me"
	model "LAPP_ACURA_MOM_BACKEND/models/pln"
	"LAPP_ACURA_MOM_BACKEND/utils"
	"bufio"
	"fmt"
	"io"
	"os"
	"regexp"
	"strconv"
	"strings"
	"time"
)

/******************************************************************************
 *
 * @Description              : HondaDemand的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-20 09:58:33
 *
 ******************************************************************************/
var DefaultConditionOfHondaDemand = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.HondaDemand_DemandId.UrlParameterName:    grmi.NewConditionItem(meta.HondaDemand_DemandId, grmi.Equal, true),
		meta.HondaDemand_PlanCode.UrlParameterName:    grmi.NewConditionItem(meta.HondaDemand_PlanCode, grmi.Equal, false),
		meta.HondaDemand_DemandYear.UrlParameterName:  grmi.NewConditionItem(meta.HondaDemand_DemandYear, grmi.Equal, false),
		meta.HondaDemand_DemandWeek.UrlParameterName:  grmi.NewConditionItem(meta.HondaDemand_DemandWeek, grmi.Equal, false),
		meta.HondaDemand_DemandDate.UrlParameterName:  grmi.NewConditionItem(meta.HondaDemand_DemandDate, grmi.Approximate, false),
		meta.HondaDemand_DemandType.UrlParameterName:  grmi.NewConditionItem(meta.HondaDemand_DemandType, grmi.Equal, false),
		meta.HondaDemand_Parsed.UrlParameterName:      grmi.NewConditionItem(meta.HondaDemand_Parsed, grmi.Equal, false),
		meta.HondaDemand_OrderTime.UrlParameterName:   grmi.NewConditionItem(meta.HondaDemand_OrderTime, grmi.Approximate, false),
		meta.HondaDemand_TotalQty.UrlParameterName:    grmi.NewConditionItem(meta.HondaDemand_TotalQty, grmi.Equal, false),
		meta.HondaDemand_EdiFile.UrlParameterName:     grmi.NewConditionItem(meta.HondaDemand_EdiFile, grmi.Equal, false),
		meta.HondaDemand_EdiFileType.UrlParameterName: grmi.NewConditionItem(meta.HondaDemand_EdiFileType, grmi.Equal, false),
		meta.HondaDemand_CtrlPara1.UrlParameterName:   grmi.NewConditionItem(meta.HondaDemand_CtrlPara1, grmi.Equal, false),
		meta.HondaDemand_CtrlPara2.UrlParameterName:   grmi.NewConditionItem(meta.HondaDemand_CtrlPara2, grmi.Equal, false),
		meta.HondaDemand_CtrlStr1.UrlParameterName:    grmi.NewConditionItem(meta.HondaDemand_CtrlStr1, grmi.Equal, false),
		meta.HondaDemand_CtrlStr2.UrlParameterName:    grmi.NewConditionItem(meta.HondaDemand_CtrlStr2, grmi.Equal, false),
		meta.HondaDemand_CtrlTime1.UrlParameterName:   grmi.NewConditionItem(meta.HondaDemand_CtrlTime1, grmi.Approximate, false),
		meta.HondaDemand_CtrlTime2.UrlParameterName:   grmi.NewConditionItem(meta.HondaDemand_CtrlTime2, grmi.Approximate, false),
		meta.HondaDemand_LastModify.UrlParameterName:  grmi.NewConditionItem(meta.HondaDemand_LastModify, grmi.Approximate, false),
		meta.HondaDemand_LastUser.UrlParameterName:    grmi.NewConditionItem(meta.HondaDemand_LastUser, grmi.Equal, false),
		meta.HondaDemand_CreateTime.UrlParameterName:  grmi.NewConditionItem(meta.HondaDemand_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : HondaDemand的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-20 09:58:33
 *
 ******************************************************************************/
var DefaultConditionOfHondaDemandAndPaging = grmi.NewCondition(
	DefaultConditionOfHondaDemand.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : HondaDemandServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : HondaDemand的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-20 09:58:33
 *
 ******************************************************************************/
type HondaDemandServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewHondaDemandDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个HondaDemandDAOImplement实例
 *
 * @Return Value             : HondaDemandDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-10-20 09:58:33
 *
 ******************************************************************************/
func NewHondaDemandServiceImplement() *HondaDemandServiceImplement {
	hondaDemandServiceImplement := &HondaDemandServiceImplement{}
	//创建任务队列
	utils.EmailSendFoudnMap["demandAnalysis"] = hondaDemandServiceImplement
	utils.EmailSendStruct["demandAnalysis"] = utils.NewEmailSendStruct(5, "demandAnalysis", 10, "AnalysisFile")
	//查询解析中以及待解析数据加入任务
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	dao := dal.NewHondaDemandDAO(session, baseModel.PlantNr, "system")
	condition := DefaultConditionOfHondaDemandAndPaging
	urlParameters := make(map[string]string)
	urlParameters[meta.HondaDemand_Parsed.Name] = "1"
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		panic(err.Error())
	}
	list, err := dao.SelectAll(predicates, condition.OrderByFields)
	if err != nil {
		panic(err.Error())
	}
	for _, v := range list {
		utils.EmailSendStruct["demandAnalysis"].SeyChannels(utils.ChannelsInfo{
			Key:  v.DemandId,
			Info: v,
		})
	}
	return hondaDemandServiceImplement
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pln/HondaDemandService.Analysis
 *
 ******************************************************************************/
func (impl *HondaDemandServiceImplement) Analysis(user *global.User, demandId string) error {
	grmi.Log(user, "/services/pln/implments/HondaDemand.service.impl.go", "Analysis", "重新解析一个HondaDemand")
	condition := DefaultConditionOfHondaDemandErrorLstAndPaging

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewHondaDemandDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(demandId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	//判断是否存在未处理错误
	errDao := dal.NewHondaDemandErrorLstDAO(session, user.PlantNr, user.UserId)
	urlParameters := make(map[string]string)
	urlParameters[meta.HondaDemandErrorLst_ErrorStatus.Name] = "开"
	urlParameters[meta.HondaDemandErrorLst_DemandId.Name] = record.DemandId
	predicates, err := condition.BuildPredicates(urlParameters)
	errList, err := errDao.Select(predicates, condition.OrderByFields)
	if err != nil {
		return err
	}
	if len(errList) > 0 {
		return grmi.NewBusinessError("请修复错误后解析!")
	}
	if record.Parsed != 3 {
		return grmi.NewBusinessError("记录正在解析或已经解析成功!")
	}
	record.Parsed = 1
	err = dao.UpdateOne(record)
	if err != nil {
		return err
	}
	utils.EmailSendStruct["demandAnalysis"].SeyChannels(utils.ChannelsInfo{
		Key:  record.DemandId,
		Info: *record,
	})
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pln/HondaDemandService.InsertOne
 *
 ******************************************************************************/
func (impl *HondaDemandServiceImplement) InsertOne(user *global.User, entity *model.HondaDemand) error {
	log, _ := logger.NewLogger(user.UserId, "OM")
	grmi.Log(user, "/services/pln/implments/HondaDemand.service.impl.go", "InsertOneHondaDemand", "插入一个HondaDemand")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	//判断文件是否存在
	_, err := os.Stat("web/public/" + entity.DemandType + "/Demand/" + entity.EdiFile)
	if err != nil {
		return err
	}
	//添加主数据
	snrDao := baseDal.NewSnrDAO(session, user.PlantNr, user.UserId)

	entity.DemandId, err = snrDao.GetNextSnr("HondaID")
	if err != nil {
		log.Error("HondaID InsertOne get HondaDemand DemandId failed, error: " + err.Error())
		return err
	}
	entity.Parsed = 1
	dao := dal.NewHondaDemandDAO(session, user.PlantNr, user.UserId)
	infoDao := dal.NewHondaDemandItemLstDAO(session, user.PlantNr, user.UserId)
	errList, infoList := impl.fileUpload(entity)
	record, err := dao.SelectOneWhere(*entity)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("需求代码周期不能重复导入!")
	}
	if errList == nil {
		session.Begin()

		if len(infoList) > 20 {
			var _infoList []model.HondaDemandItemLst
			for k, v := range infoList {
				_infoList = append(_infoList, v)
				if (k > 0 && k%20 == 0) || k+1 == len(infoList) {
					err = infoDao.Insert(&_infoList)
					if err != nil {
						session.Rollback()
						return err
					}
					_infoList = []model.HondaDemandItemLst{}
				}
			}
		} else {
			err = infoDao.Insert(&infoList)
			if err != nil {
				session.Rollback()
				return err
			}
		}
		err = dao.InsertOne(entity)
		if err != nil {
			session.Rollback()
			return err
		}
	} else {
		errStr := ""
		for _, v := range errList {
			errStr += v.ErrorInfo + ";"
		}
		return fmt.Errorf(errStr)
	}
	utils.EmailSendStruct["demandAnalysis"].SeyChannels(utils.ChannelsInfo{
		Key:  entity.DemandId,
		Info: *entity,
	})
	session.Commit()
	return nil
}

//TimeLocationShangHai 默认时区，上海
var TimeLocationShangHai, _ = time.LoadLocation("Asia/Shanghai")

func (impl *HondaDemandServiceImplement) AnalysisFile(info utils.ChannelsInfo) (bool, utils.ChannelsInfo) {
	entity, ok := info.Info.(model.HondaDemand)
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer func() { //在panic前声明defer,能捕获异常
		if err := recover(); err != nil {
			session.Rollback()
			innerLog, _ := logger.NewLogger("system", "create_cust_order")
			innerLog.Debug("系统异常:", err)
		}
	}()
	defer session.Close()

	errDao := dal.NewHondaDemandErrorLstDAO(session, entity.PlantNr, "system")
	dao := dal.NewHondaDemandDAO(session, entity.PlantNr, "system")
	infoDao := dal.NewHondaDemandItemLstDAO(session, entity.PlantNr, "system")

	//配置
	familyDao := dalMe.NewProductFamilyDAO(session, entity.PlantNr, "system")
	//流水号
	snrDao := baseDal.NewSnrDAO(session, entity.PlantNr, "system")
	//客户订单
	custDao := dal.NewCustOrderDAO(session, entity.PlantNr, "system")
	custOrderQtyDao := dal.NewCustOrderQtyDAO(session, entity.PlantNr, "system")
	//订单状态
	custStatusDao := dal.NewCustOrderStatusDAO(session, entity.PlantNr, "system")
	if !ok || entity.DemandId == "" {
		panic("消息体类型错误跳过消息")
	}
	condition := DefaultConditionOfHondaDemandItemLstAndPaging
	errCondition := DefaultConditionOfHondaDemandErrorLstAndPaging
	//删除错误信息
	urlParameters := make(map[string]string)
	urlParameters[meta.HondaDemandErrorLst_DemandId.Name] = entity.DemandId
	predicates, err := errCondition.BuildPredicates(urlParameters)
	if err != nil {
		errData := model.HondaDemandErrorLst{
			DemandId:    entity.DemandId,
			Pos:         -1,
			ErrorType:   "",
			ErrorInfo:   "系统解析异常:" + err.Error() + ";",
			ErrorStatus: "开",
		}
		_ = errDao.InsertOne(&errData)
		return false, info
	}
	_ = errDao.DeleteWhere(predicates)

	//查出明细
	urlParameters = make(map[string]string)
	urlParameters[meta.HondaDemandErrorLst_DemandId.Name] = entity.DemandId
	predicates, err = condition.BuildPredicates(urlParameters)
	if err != nil {
		errData := model.HondaDemandErrorLst{
			DemandId:    entity.DemandId,
			Pos:         -1,
			ErrorType:   "",
			ErrorInfo:   "系统解析异常:" + err.Error() + ";",
			ErrorStatus: "开",
		}
		_ = errDao.InsertOne(&errData)
		return false, info
	}
	itemInfo, err := infoDao.Select(predicates, condition.OrderByFields)
	if err != nil {
		errData := model.HondaDemandErrorLst{
			DemandId:    entity.DemandId,
			Pos:         -1,
			ErrorType:   "",
			ErrorInfo:   "系统解析异常:" + err.Error() + ";",
			ErrorStatus: "开",
		}
		_ = errDao.InsertOne(&errData)
		return false, info
	}
	//根据配置号查询零件配置 以及配置信息
	var familyCode []string
	for _, v := range itemInfo {
		familyCode = append(familyCode, v.ProductFamilyId)
	}
	familyData, err := familyDao.SelectAndRelate(familyCode)
	if err != nil {
		errData := model.HondaDemandErrorLst{
			DemandId:    entity.DemandId,
			Pos:         -1,
			ErrorType:   "",
			ErrorInfo:   "系统解析异常:" + err.Error() + ";",
			ErrorStatus: "开",
		}
		_ = errDao.InsertOne(&errData)
		return false, info
	}
	familyMap := make(map[string]modelMe.ProductFamily)
	for _, v := range familyData {
		familyMap[v.ProductFamilyId] = v
	}
	//客户订单列表
	var custOrder []model.CustOrder
	var errList []model.HondaDemandErrorLst
	var custOrderStatus []model.CustOrderStatus
	var custOrderQtyLi []model.CustOrderQty
	//循环详情
	for _, v := range itemInfo {
		familyInfo, ok := familyMap[v.ProductFamilyId]
		if ok {
			if v.ColorValue != familyInfo.ColorValue {
				errList = append(errList, model.HondaDemandErrorLst{
					DemandId:    entity.DemandId,
					Pos:         v.Pos,
					ErrorType:   "",
					ErrorInfo:   "车型" + v.ProductFamilyId + "：颜色配置不一致;",
					ErrorStatus: "开",
				})
				continue
			}
			if v.ModelValue != familyInfo.ModelValue {
				errList = append(errList, model.HondaDemandErrorLst{
					DemandId:    entity.DemandId,
					Pos:         v.Pos,
					ErrorType:   "",
					ErrorInfo:   "车型" + v.ProductFamilyId + "：车型代码不一致;",
					ErrorStatus: "开",
				})
				continue
			}
			if v.ConfigValue != familyInfo.ConfigValue {
				errList = append(errList, model.HondaDemandErrorLst{
					DemandId:    entity.DemandId,
					Pos:         v.Pos,
					ErrorType:   "",
					ErrorInfo:   "车型" + v.ProductFamilyId + "：配置代码不一致;",
					ErrorStatus: "开",
				})
				continue
			}
			custOrderId, err := snrDao.GetNextSnr(familyInfo.Project.CustOrderSnr)
			if err != nil {
				errData := model.HondaDemandErrorLst{
					DemandId:    entity.DemandId,
					Pos:         -1,
					ErrorType:   "",
					ErrorInfo:   "系统解析异常,流水号生成失败:" + err.Error() + ";",
					ErrorStatus: "开",
				}
				_ = errDao.InsertOne(&errData)
				return false, info
			}
			custOrder = append(custOrder, model.CustOrder{
				CustOrderId:     custOrderId,
				ProductFamilyId: v.ProductFamilyId,
				//PartId:          val.ProductId,
				OrderType:       baseModel.ODER_TYPE_SEQ,
				OrderInfo:       familyInfo.Descr,
				ProjectId:       familyInfo.ProjectId,
				ConfigValue:     familyInfo.ConfigValue,
				ModelValue:      familyInfo.ModelValue,
				ColorValue:      familyInfo.ColorValue,
				PlanQty:         v.PlanQty,
				SourceId:        entity.DemandId,
				WorkLineId:      familyInfo.WorkLineId,
				QuantityPerHour: int(familyInfo.Jph),
			})
			custOrderStatus = append(custOrderStatus, model.CustOrderStatus{
				CustOrderId: custOrderId,
				Status:      baseModel.ORDER_STATUS_UNPLANED,
			})
			custOrderQty := model.CustOrderQty{
				CustOrderId: custOrderId,
				PlanQty:     v.PlanQty,
			}
			custOrderQtyLi = append(custOrderQtyLi, custOrderQty)
			//for _, val := range familyInfo.Relate {
			//
			//	custOrderId, err := snrDao.GetNextSnr(familyInfo.Project.CustOrderSnr)
			//	if err != nil {
			//		errData := model.HondaDemandErrorLst{
			//			DemandId:    entity.DemandId,
			//			Pos:         -1,
			//			ErrorType:   "",
			//			ErrorInfo:   "系统解析异常,流水号生成失败:" + err.Error() + ";",
			//			ErrorStatus: "开",
			//		}
			//		_ = errDao.InsertOne(&errData)
			//		return false, info
			//	}
			//	custOrder = append(custOrder, model.CustOrder{
			//		CustOrderId:     custOrderId,
			//		ProductFamilyId: v.ProductFamilyId,
			//		//PartId:          "111",
			//		PartId:      val.ProductId,
			//		OrderType:   baseModel.ODER_TYPE_SEQ,
			//		OrderInfo:   familyInfo.Descr,
			//		ProjectId:   familyInfo.ProjectId,
			//		ConfigValue: familyInfo.ConfigValue,
			//		ModelValue:  familyInfo.ModelValue,
			//		ColorValue:  familyInfo.ColorValue,
			//		PlanQty:     v.PlanQty,
			//		SourceId:    entity.DemandId,
			//	})
			//	custOrderStatus = append(custOrderStatus, model.CustOrderStatus{
			//		CustOrderId: custOrderId,
			//		Status:      baseModel.ORDER_STATUS_UNPLANED,
			//	})
			//}
		} else {
			errList = append(errList, model.HondaDemandErrorLst{
				DemandId:    entity.DemandId,
				Pos:         v.Pos,
				ErrorType:   "",
				ErrorInfo:   "车型配置未找到:" + v.ProductFamilyId,
				ErrorStatus: "开",
			})
		}
	}
	session.Begin()
	if len(errList) > 0 {
		entity.Parsed = 3
		err = dao.UpdateOne(&entity)
		if err != nil {
			panic("文件解析失败，更新状态异常:" + err.Error())
		}
		err = errDao.Insert(&errList)
		if err != nil {
			panic("文件解析失败，写入错误信息异常:" + err.Error())
		}
	} else {
		entity.Parsed = 2
		err = dao.UpdateOne(&entity)
		if err != nil {
			panic("文件解析成功，修改状态异常:" + err.Error())
		}

		if len(custOrder) > 20 {
			var _infoList []model.CustOrder
			for k, v := range custOrder {
				_infoList = append(_infoList, v)
				if (k > 0 && k%20 == 0) || k+1 == len(custOrder) {
					err = custDao.Insert(&_infoList)
					if err != nil {
						session.Rollback()
						panic("文件解析成功，写入客户订单异常:" + err.Error())
					}
					_infoList = []model.CustOrder{}
				}
			}
		} else {
			err = custDao.Insert(&custOrder)
			if err != nil {
				session.Rollback()
				panic("文件解析成功，写入客户订单异常:" + err.Error())
			}
		}

		if len(custOrder) > 20 {
			var _infoList []model.CustOrderStatus
			for k, v := range custOrderStatus {
				_infoList = append(_infoList, v)
				if (k > 0 && k%20 == 0) || k+1 == len(custOrderStatus) {
					err = custStatusDao.Insert(&_infoList)
					if err != nil {
						session.Rollback()
						panic("文件解析成功，写入客户订单异常:" + err.Error())
					}
					_infoList = []model.CustOrderStatus{}
				}
			}
		} else {
			err = custStatusDao.Insert(&custOrderStatus)
			if err != nil {
				session.Rollback()
				panic("文件解析成功，写入客户订单异常:" + err.Error())
			}
		}

		if len(custOrderQtyLi) > 20 {
			var _infoList []model.CustOrderQty
			for k, v := range custOrderQtyLi {
				_infoList = append(_infoList, v)
				if (k > 0 && k%20 == 0) || k+1 == len(custOrderQtyLi) {
					err = custOrderQtyDao.Insert(&_infoList)
					if err != nil {
						_ = session.Rollback()
						panic("文件解析成功，写入客户订单异常:" + err.Error())
					}
					_infoList = []model.CustOrderQty{}
				}
			}
		} else {
			err = custOrderQtyDao.Insert(&custOrderQtyLi)
			if err != nil {
				_ = session.Rollback()
				panic("文件解析成功，写入客户订单异常:" + err.Error())
			}
		}

	}
	_ = session.Commit()
	return false, info
}
func (impl *HondaDemandServiceImplement) fileUpload(entity *model.HondaDemand) ([]model.HondaDemandErrorLst, []model.HondaDemandItemLst) {
	var errList []model.HondaDemandErrorLst
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()

	_, err := os.Stat("web/public/" + entity.DemandType + "/Demand/" + entity.EdiFile)
	if err != nil {
		errList = append(errList, model.HondaDemandErrorLst{
			DemandId:    entity.DemandId,
			Pos:         -1,
			ErrorType:   "",
			ErrorInfo:   "文件不存在",
			ErrorStatus: "开",
		})
		return errList, nil
	}
	file, err := os.Open("web/public/" + entity.DemandType + "/Demand/" + entity.EdiFile)
	if err != nil {
		errList = append(errList, model.HondaDemandErrorLst{
			DemandId:    entity.DemandId,
			Pos:         -1,
			ErrorType:   "",
			ErrorInfo:   "文件不存在",
			ErrorStatus: "开",
		})
		return errList, nil
	}
	defer file.Close()
	reader := bufio.NewReader(file)
	readerRow := -1
	totalRow := 0
	dateStr := ""
	bodyRow := 0
	totalQty := 0
	var infoList []model.HondaDemandItemLst
	_planCode := ""
	_DemandYear := 0
	_analysis := time.Time{}
	for {
		totalRow++
		str, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		if err != nil {
			errList = append(errList, model.HondaDemandErrorLst{
				DemandId:    entity.DemandId,
				Pos:         -3,
				ErrorType:   "",
				ErrorInfo:   "文件读取失败",
				ErrorStatus: "开",
			})
			return errList, nil
		}
		str = strings.Trim(str, "\n")
		str = strings.Trim(str, "\r")
		if str == "1**XLP ENV=158LE, END;" || str == "+**XLP ENV=158LE, END;" {
			readerRow = 0
			continue
		}
		if readerRow > -1 {
			readerRow++
		}
		if readerRow == 2 {

			analysis, DemandYear, err := impl.headAnalysis(str)
			if err == nil {
				if DemandYear == 0 {
					if _DemandYear == 0 {
						errList = append(errList, model.HondaDemandErrorLst{
							DemandId:    entity.DemandId,
							Pos:         -3,
							ErrorType:   "",
							ErrorInfo:   "系统解析需求日期异常",
							ErrorStatus: "开",
						})
						_DemandYear = -1
					}

				}
				if _DemandYear == 0 {
					_DemandYear = DemandYear
					_analysis = analysis
					entity.DemandDate = grmi.Date(analysis)
					entity.DemandYear = DemandYear
				} else if _DemandYear != DemandYear || !_analysis.Equal(analysis) {
					errList = append(errList, model.HondaDemandErrorLst{
						DemandId:    entity.DemandId,
						Pos:         -9,
						ErrorType:   "",
						ErrorInfo:   "文件中需求周期不一致",
						ErrorStatus: "开",
					})
				}

			} else {
				if _DemandYear == 0 {
					errList = append(errList, model.HondaDemandErrorLst{
						DemandId:    entity.DemandId,
						Pos:         -4,
						ErrorType:   "",
						ErrorInfo:   err.Error(),
						ErrorStatus: "开",
					})
					_DemandYear = -1
				}
			}
		}
		if readerRow == 5 {
			demandWeek, planCode, err := impl.headWeek(str, entity.DemandYear)
			if err == nil {
				if _planCode == "" {
					_planCode = planCode
				} else if _planCode != planCode {
					//插入错误
					errList = append(errList, model.HondaDemandErrorLst{
						DemandId:    entity.DemandId,
						Pos:         -8,
						ErrorType:   "",
						ErrorInfo:   "文件内PlanCode不一致无法解析",
						ErrorStatus: "开",
					})
					return errList, nil
				}
				entity.DemandWeek = demandWeek
				entity.PlanCode = planCode
			} else {
				if _planCode == "" {
					errList = append(errList, model.HondaDemandErrorLst{
						DemandId:    entity.DemandId,
						Pos:         -5,
						ErrorType:   "",
						ErrorInfo:   err.Error(),
						ErrorStatus: "开",
					})
					_planCode = "-"
				}

			}
		}
		if readerRow > 9 {

			if strings.Trim(str, " ") == "" || strings.Trim(str, " ") == "1" {
				//空行过
				continue
			}
			bodyRow += 1
			info := &model.HondaDemandItemLst{}
			info.DemandId = entity.DemandId
			info.Pos = bodyRow

			_strArr2 := impl.bodyRoArr(str)

			//读取body
			str := impl.DeleteExtraSpace(str)
			_strArr := strings.Split(str, " ")
			if _strArr[1] == "GRAND" {
				if _strArr[2] == "TOTAL" {
					//文件结束 获取总数
					_totalQty := strings.Replace(_strArr[3], ",", "", -1)
					if i, err := strconv.Atoi(_totalQty); err == nil {
						entity.TotalQty = i
					}
				}
				break
			}
			//
			dateStr, errList = impl.bodyInfo(_strArr2, dateStr, info, errList, totalRow)
			totalQty += info.PlanQty
			infoList = append(infoList, *info)
		}
	}

	if entity.TotalQty != totalQty {
		errList = append(errList, model.HondaDemandErrorLst{
			DemandId:    entity.DemandId,
			Pos:         -6,
			ErrorType:   "",
			ErrorInfo:   "需求总数对比错误",
			ErrorStatus: "开",
		})
	}

	return nil, infoList
}

func (impl *HondaDemandServiceImplement) headAnalysis(str string) (time.Time, int, error) {
	defer func() {
		if err := recover(); err != nil {
			_ = fmt.Errorf("解析失败：日期错误")
		}
	}()
	//获取到文件头
	strArr := strings.Split(str, " ")
	strDate := ""
	dateStr := 1
	timeStr := 1
	DemandYear := 0
	for _, v := range strArr {
		v = strings.Trim(v, " ")
		if v == "DATE:" {
			dateStr = 2
			continue
		}
		if dateStr == 2 && v != "" {
			dateArr := strings.Split(v, "/")
			if len(dateArr) != 3 {
				return time.Time{}, DemandYear, fmt.Errorf("解析失败：日期错误")
			}
			if i, err := strconv.ParseInt(dateArr[2], 10, 64); err == nil {
				DemandYear = int(i)
			} else {
				return time.Time{}, DemandYear, fmt.Errorf("日期解析错误")
			}
			for i := 2; i >= 0; i-- {
				if i != 2 {
					strDate += "-"
				}
				if len(dateArr[i]) == 1 {
					strDate += "0"
				}
				strDate += dateArr[i]
			}
			strDate += " "
			dateStr = 3
		}
		if v == "TIME:" {
			timeStr = 2
			continue
		}
		if timeStr == 2 && v != "" {
			strDate += v
			timeStr = 3
		}
	}
	//时间转换
	if result, err := time.ParseInLocation("2006-01-02 15:04:05", strDate, TimeLocationShangHai); err == nil {
		return result.In(TimeLocationShangHai), DemandYear, nil
	}
	return time.Time{}, DemandYear, fmt.Errorf("解析失败：日期错误")
}
func (impl *HondaDemandServiceImplement) headWeek(str string, demandYear int) (int, string, error) {
	//先按照"("拆分 去后置数组
	strArr := strings.Split(str, "(")
	if len(strArr) != 2 || strArr[1] == "" {
		return 0, "", fmt.Errorf("解析失败：需求周错误")
	}
	strArr = strings.Split(strArr[1], ")")
	strArr = strings.Split(strArr[0], " ")
	weekCount := 0
	demandWeek := 0
	codeCount := 0
	planCode := ""
	for _, v := range strArr {
		if v == "PLAN" {
			codeCount = 1
		}
		if v == "CODE" && codeCount == 1 {
			codeCount = 2
			continue
		}
		if codeCount == 2 && v == ":" {
			codeCount = 3
			continue
		}
		if codeCount == 3 && v != "" {
			planCode = v
			codeCount = 4
			continue
		}

		if v == "WEEK" {
			weekCount = 1
		}
		if v == "NO." && weekCount == 1 {
			weekCount = 2
		}
		if weekCount == 2 && v == strconv.FormatInt(int64(demandYear), 10) {
			weekCount = 3
			continue
		}
		if weekCount == 3 && v != "" {
			if i, err := strconv.ParseInt(v, 10, 64); err == nil {
				demandWeek = int(i)
			} else {
				return 0, "", fmt.Errorf("解析失败：需求周错误")
			}
		}
	}
	if weekCount != 3 {
		return 0, "", fmt.Errorf("解析失败：需求周错误")
	}
	return demandWeek, planCode, nil
}
func (impl *HondaDemandServiceImplement) bodyInfo(_strArr []string, dateStr string, info *model.HondaDemandItemLst, _errList []model.HondaDemandErrorLst, totalRow int) (string, []model.HondaDemandErrorLst) {
	defer func() {
		if err := recover(); err != nil {
			_errList = append(_errList, model.HondaDemandErrorLst{
				DemandId:    info.DemandId,
				Pos:         info.Pos,
				ErrorType:   "",
				ErrorInfo:   fmt.Sprintf("%v，文件行数：%d", err, totalRow),
				ErrorStatus: "开",
			})
		}
	}()
	if _strArr[0] != "" {
		//为时间
		dateStr = _strArr[0]
	}

	//时间转换
	if result, err := time.ParseInLocation("2006-01-02", dateStr, TimeLocationShangHai); err == nil {
		info.DeliveryDate = grmi.Date(result.In(TimeLocationShangHai))
	}
	info.Color = _strArr[4]
	if info.Color == "" {
		_errList = append(_errList, model.HondaDemandErrorLst{
			DemandId:    info.DemandId,
			Pos:         info.Pos,
			ErrorType:   "",
			ErrorInfo:   fmt.Sprintf("未获取到车型配置代码，文件行数：%d", totalRow),
			ErrorStatus: "开",
		})
	}
	i, err := strconv.Atoi(_strArr[5])
	if err == nil {
		info.PlanQty = i
	}
	if err != nil || info.PlanQty == 0 {
		_errList = append(_errList, model.HondaDemandErrorLst{
			DemandId:    info.DemandId,
			Pos:         info.Pos,
			ErrorType:   "",
			ErrorInfo:   fmt.Sprintf("获取计划数量失败，文件行数：%d;", totalRow),
			ErrorStatus: "开",
		})
	}
	info.ProductFamilyId = _strArr[2] + "-" + _strArr[3] + "-" + _strArr[4]
	info.ConfigValue = _strArr[2]
	info.ColorValue = _strArr[4]
	info.ModelValue = _strArr[3]
	return dateStr, _errList
}
func (impl *HondaDemandServiceImplement) bodyRoArr(str string) []string {
	bodyArr := []string{"", "", "", "", "", ""}
	_str := ""
	_dateArr := []string{"", "", ""}

	for k, v := range str {
		if k == 4 || k == 5 {
			if string(v) == "" {
				_dateArr[0] += "0"
			} else {
				_dateArr[0] += string(v)
			}
		}
		if k == 7 || k == 8 {
			if string(v) == "" {
				_dateArr[1] += "0"
			} else {
				_dateArr[1] += string(v)
			}
		}
		if k == 10 || k == 11 || k == 12 || k == 13 {
			if string(v) == "" {
				_dateArr[2] += "0"
			} else {
				_dateArr[2] += string(v)
			}
			bodyArr[0] = _dateArr[2] + "-" + _dateArr[1] + "-" + _dateArr[0]
		}
		if k == 15 || k == 16 || k == 17 {
			bodyArr[1] += string(v)
		}
		if k == 57 || k == 59 || k == 60 || k == 61 {
			bodyArr[2] += string(v)
		}
		if k == 63 || k == 64 || k == 65 {
			bodyArr[3] += string(v)
		}
		if k == 82 {
			bodyArr[4] = string(v)
		}
		if k == 85 || k == 86 || k == 87 || k == 88 || k == 89 || k == 90 || k == 91 || k == 92 || k == 93 || k == 94 || k == 95 || k == 96 || k == 97 || k == 98 || k == 99 || k == 100 || k == 101 {
			_str += string(v)
			if k == 101 {
				//字符串转数组 去数组第二位
				_strArr := strings.Split(impl.DeleteExtraSpace(_str), " ")
				if len(_strArr) < 2 {
					bodyArr[5] = ""
				} else {
					bodyArr[5] = _strArr[1]
				}
			}
		}
	}
	return bodyArr
}
func (impl *HondaDemandServiceImplement) DeleteExtraSpace(s string) string {
	//删除字符串中的多余空格，有多个空格时，仅保留一个空格
	s1 := strings.Replace(s, "  ", " ", -1)      //替换tab为空格
	regstr := "\\s{2,}"                          //两个及两个以上空格的正则表达式
	reg, _ := regexp.Compile(regstr)             //编译正则表达式
	s2 := make([]byte, len(s1))                  //定义字符数组切片
	copy(s2, s1)                                 //将字符串复制到切片
	spc_index := reg.FindStringIndex(string(s2)) //在字符串中搜索
	for len(spc_index) > 0 {                     //找到适配项
		s2 = append(s2[:spc_index[0]+1], s2[spc_index[1]:]...) //删除多余空格
		spc_index = reg.FindStringIndex(string(s2))            //继续在字符串中搜索
	}
	return string(s2)
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pln/HondaDemandService.DeleteOne
 *
 ******************************************************************************/
func (impl *HondaDemandServiceImplement) DeleteOne(user *global.User, demandId string) error {

	grmi.Log(user, "/services/pln/implments/HondaDemand.service.impl.go", "DeleteOneHondaDemand", "删除一个HondaDemand")

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pln/HondaDemandService.SelectOne
 *
 ******************************************************************************/
func (impl *HondaDemandServiceImplement) SelectOne(user *global.User, demandId string) (*model.HondaDemand, error) {

	grmi.Log(user, "/services/pln/implments/HondaDemand.service.impl.go", "SelectOneHondaDemand", "查询一个HondaDemand")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewHondaDemandDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectOne(demandId)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pln/HondaDemandService.UpdateOne
 *
 ******************************************************************************/
func (impl *HondaDemandServiceImplement) UpdateOne(user *global.User, entity *model.HondaDemand) error {

	grmi.Log(user, "/services/pln/implments/HondaDemand.service.impl.go", "UpdateOneHondaDemand", "修改一个HondaDemand")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewHondaDemandDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(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_ACURA_MOM_BACKEND/services/pln/HondaDemandService.Insert
 *
 ******************************************************************************/
func (impl *HondaDemandServiceImplement) Insert(user *global.User, entities *[]model.HondaDemand) error {

	grmi.Log(user, "/services/pln/implments/HondaDemand.service.impl.go", "InsertHondaDemand", "插入多个HondaDemand")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewHondaDemandDAO(session, user.PlantNr, user.UserId)

	for _, entity := range *entities {
		record, err := dao.SelectOne(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_ACURA_MOM_BACKEND/services/pln/HondaDemandService.Delete
 *
 ******************************************************************************/
func (impl *HondaDemandServiceImplement) Delete(user *global.User, entities *[]model.HondaDemand) error {

	grmi.Log(user, "/services/pln/implments/HondaDemand.service.impl.go", "DeleteHondaDemand", "删除多个HondaDemand")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewHondaDemandDAO(session, user.PlantNr, user.UserId)

	for _, entity := range *entities {
		record, err := dao.SelectOne(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_ACURA_MOM_BACKEND/services/pln/HondaDemandService.Select
 *
 ******************************************************************************/
func (impl *HondaDemandServiceImplement) Select(user *global.User, urlParameters map[string]string) ([]model.HondaDemand, error) {

	grmi.Log(user, "/services/pln/implments/HondaDemand.service.impl.go", "SelectHondaDemand", "查询HondaDemand")

	condition := DefaultConditionOfHondaDemandAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewHondaDemandDAO(session, user.PlantNr, user.UserId)
	result, err := dao.Select(predicates, condition.OrderByFields)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pln/HondaDemandService.SelectAndPaging
 *
 ******************************************************************************/
func (impl *HondaDemandServiceImplement) SelectAndPaging(user *global.User, urlParameters map[string]string) (grmi.PagingResult, error) {

	grmi.Log(user, "/services/pln/implments/HondaDemand.service.impl.go", "SelectHondaDemand", "查询HondaDemand")

	condition := DefaultConditionOfHondaDemandAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	dao := dal.NewHondaDemandDAO(session, user.PlantNr, user.UserId)
	condition.Fill(urlParameters)
	result, err := dao.SelectAndPaging(condition.Paging, predicates, condition.OrderByFields)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/pln/HondaDemandService.Update
 *
 ******************************************************************************/
func (impl *HondaDemandServiceImplement) Update(user *global.User, entities *[]model.HondaDemand) error {

	grmi.Log(user, "/services/pln/implments/HondaDemand.service.impl.go", "UpdateHondaDemand", "修改多个HondaDemand")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewHondaDemandDAO(session, user.PlantNr, user.UserId)

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

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