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

package implments

import (
	apiDal "LAPP_LF_MOM_BACKEND/dao/api"
	dal "LAPP_LF_MOM_BACKEND/dao/om"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/grmi"
	"LAPP_LF_MOM_BACKEND/infra/logger"
	meta "LAPP_LF_MOM_BACKEND/meta/om"
	model "LAPP_LF_MOM_BACKEND/models/om"
	"LAPP_LF_MOM_BACKEND/web/models"
	"strconv"
	"time"
)

/******************************************************************************
 *
 * @Description              : DemandHeadFromDB的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-05-13 16:05:11
 *
 ******************************************************************************/
var DefaultConditionOfDemandHeadFromDB = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.DemandHeadFromDB_TaskNr.UrlParameterName:     grmi.NewConditionItem(meta.DemandHeadFromDB_TaskNr, grmi.Equal, true),
		meta.DemandHeadFromDB_TaskDate.UrlParameterName:   grmi.NewConditionItem(meta.DemandHeadFromDB_TaskDate, grmi.Approximate, false),
		meta.DemandHeadFromDB_Status.UrlParameterName:     grmi.NewConditionItem(meta.DemandHeadFromDB_Status, grmi.Equal, false),
		meta.DemandHeadFromDB_ErrNum.UrlParameterName:     grmi.NewConditionItem(meta.DemandHeadFromDB_ErrNum, grmi.Equal, false),
		meta.DemandHeadFromDB_ErrInfo.UrlParameterName:    grmi.NewConditionItem(meta.DemandHeadFromDB_ErrInfo, grmi.Equal, false),
		meta.DemandHeadFromDB_LastModify.UrlParameterName: grmi.NewConditionItem(meta.DemandHeadFromDB_LastModify, grmi.Approximate, false),
		meta.DemandHeadFromDB_LastUser.UrlParameterName:   grmi.NewConditionItem(meta.DemandHeadFromDB_LastUser, grmi.Equal, false),
		meta.DemandHeadFromDB_CreateTime.UrlParameterName: grmi.NewConditionItem(meta.DemandHeadFromDB_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : DemandHeadFromDB的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-05-13 16:05:11
 *
 ******************************************************************************/
var DefaultConditionOfDemandHeadFromDBAndPaging = grmi.NewCondition(
	DefaultConditionOfDemandHeadFromDB.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : DemandHeadFromDBServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : DemandHeadFromDB的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-05-13 16:05:11
 *
 ******************************************************************************/
type DemandHeadFromDBServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewDemandHeadFromDBDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个DemandHeadFromDBDAOImplement实例
 *
 * @Return Value             : DemandHeadFromDBDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-05-13 16:05:11
 *
 ******************************************************************************/
func NewDemandHeadFromDBServiceImplement() *DemandHeadFromDBServiceImplement {
	return &DemandHeadFromDBServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadFromDBService.InsertOne
 *
 ******************************************************************************/
func (impl *DemandHeadFromDBServiceImplement) InsertOne(user *models.Usertab, entity *model.DemandHeadFromDB) error {

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadFromDBService.DeleteOne
 *
 ******************************************************************************/
func (impl *DemandHeadFromDBServiceImplement) DeleteOne(user *models.Usertab, taskNr int) error {

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadFromDBService.SelectOne
 *
 ******************************************************************************/
func (impl *DemandHeadFromDBServiceImplement) SelectOne(user *models.Usertab, taskNr int) (*model.DemandHeadFromDB, error) {

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadFromDBService.UpdateOne
 *
 ******************************************************************************/
func (impl *DemandHeadFromDBServiceImplement) UpdateOne(user *models.Usertab, entity *model.DemandHeadFromDB) error {

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadFromDBService.Insert
 *
 ******************************************************************************/
func (impl *DemandHeadFromDBServiceImplement) Insert(user *models.Usertab, entities *[]model.DemandHeadFromDB) error {

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

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

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadFromDBService.Delete
 *
 ******************************************************************************/
func (impl *DemandHeadFromDBServiceImplement) Delete(user *models.Usertab, entities *[]model.DemandHeadFromDB) error {

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

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

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

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

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

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

	condition := DefaultConditionOfDemandHeadFromDBAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewDemandHeadFromDBDAO(session, user.Pid, user.Userid)
	if condition.Fill(urlParameters) {
		result, err := dao.SelectAndPaging(condition.Paging, predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		return result, nil
	} else {
		result, err := dao.Select(predicates, condition.OrderByFields)
		if err != nil {
			return nil, err
		}
		return result, nil
	}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadFromDBService.Update
 *
 ******************************************************************************/
func (impl *DemandHeadFromDBServiceImplement) Update(user *models.Usertab, entities *[]model.DemandHeadFromDB) error {

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

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

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/DemandHeadFromDBService.CreateParseTask
 *
 ******************************************************************************/
func (impl *DemandHeadFromDBServiceImplement) CreateParseTask(plantNr int, taskType string) {
	user := "crontab"
	log, _ := logger.NewLogger(user, "OM")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return
	}
	headDao := dal.NewDemandHeadFromDBDAO(session, plantNr, user)
	lstDao := dal.NewDemandLstDAO(session, plantNr, user)
	task := model.DemandHeadFromDB{
		TaskDate: grmi.Date(time.Now()),
		TaskType: taskType,
		Status:   model.DemandHeadUnParsedStatus,
	}
	result, err := headDao.InsertOne(&task)
	if err != nil {
		log.Error("CreateParseTask insert task failed, error:" + err.Error())
		_ = session.Rollback()
		return
	}
	taskNr := result.TaskNr
	slaves := db.Eloquent.Slaves()
	if len(slaves) < 2 {
		log.Error("TransferSerialOrderToMes mes db not exist")
		return
	}
	portalEngine := slaves[1]
	portalSession := portalEngine.NewSession()
	portalDao := apiDal.NewVwPlanInfoDAO(portalSession, user)
	today := time.Now().Format("2006-01-02")

	portalWorkOrderLi, err := portalDao.SelectNeedParseData(today, taskType)
	if err != nil {
		log.Error("get need parse data failed, error:" + err.Error())
		_ = session.Rollback()
		return
	}
	var pos int
	demandLstLi := make([]model.DemandLst, 0, len(portalWorkOrderLi))
	for _, portalWorkOrder := range portalWorkOrderLi {
		pos++
		demandWorkOrder := model.DemandLst{
			Pos:              pos,
			DemandNr:         int(portalWorkOrder.AutoId),
			BarCode:          portalWorkOrder.Barcode,
			BarCodeDesc:      portalWorkOrder.BarcodeDesc,
			PartCode:         portalWorkOrder.PartCode,
			PlanDttm:         portalWorkOrder.PlanDttm,
			Class1:           portalWorkOrder.Class1,
			ConfigDesc:       portalWorkOrder.ConfigDesc,
			ConfigKey:        portalWorkOrder.ConfigKey,
			Seq:              int(portalWorkOrder.Seq),
			State:            portalWorkOrder.State,
			StateName:        portalWorkOrder.StateName,
			Station:          portalWorkOrder.Station,
			StationCode:      portalWorkOrder.StationCode,
			StationDesc:      portalWorkOrder.StationDesc,
			DemandCreateTime: portalWorkOrder.CreateTime,
			IsRefreshToggle:  portalWorkOrder.IsRefresh,
			Serial:           portalWorkOrder.Serial,
			CustomId:         portalWorkOrder.CustomId,
			LogTime:          portalWorkOrder.LogTime,
			CodeBar:          portalWorkOrder.Codebar,
			Memo:             portalWorkOrder.Memo,
			TaskNr:           taskNr,
		}
		demandLstLi = append(demandLstLi, demandWorkOrder)
	}
	if len(demandLstLi) == 0 {
		log.Warn("CreateParseTask get demand lst is zero, error")
		session.Rollback()
		return
	}
	// 批量插入时 一次最多插入50条
	tempLi := make([]model.DemandLst, 0, 50)
	for index, demandLst := range demandLstLi {
		if index%50 == 0 {
			err = lstDao.Insert(&tempLi)
			if err != nil {
				log.Error("CreateParseTask insert demand lst failed, error:" + err.Error())
				_ = session.Rollback()
				return
			}
			tempLi = make([]model.DemandLst, 0, 50)
		}
		tempLi = append(tempLi, demandLst)
	}
	if len(tempLi) != 0 {
		err = lstDao.Insert(&tempLi)
		if err != nil {
			log.Error("CreateParseTask insert demand lst failed, error:" + err.Error())
			_ = session.Rollback()
			return
		}
	}
	session.Commit()
	log.Info("CreateParseTask success taskNr:" + strconv.Itoa(taskNr))
}
