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

package implments

import (
	"LAPP_ACURA_MOM_BACKEND/common"
	dal "LAPP_ACURA_MOM_BACKEND/dao/base"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/base"
	model "LAPP_ACURA_MOM_BACKEND/models/base"
	"fmt"
	"strconv"
)

/******************************************************************************
 *
 * @Description              : CrossPlanTaskHead的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2022-05-27 14:50:41
 *
 ******************************************************************************/
var DefaultConditionOfCrossPlanTaskHead = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.CrossPlanTaskHead_TaskNr.UrlParameterName:          grmi.NewConditionItem(meta.CrossPlanTaskHead_TaskNr, grmi.Equal, true),
		meta.CrossPlanTaskHead_FromPlantNr.UrlParameterName:     grmi.NewConditionItem(meta.CrossPlanTaskHead_FromPlantNr, grmi.Equal, false),
		meta.CrossPlanTaskHead_ToPlantNr.UrlParameterName:       grmi.NewConditionItem(meta.CrossPlanTaskHead_ToPlantNr, grmi.Equal, false),
		meta.CrossPlanTaskHead_ArtId.UrlParameterName:           grmi.NewConditionItem(meta.CrossPlanTaskHead_ArtId, grmi.Equal, false),
		meta.CrossPlanTaskHead_PlanQty.UrlParameterName:         grmi.NewConditionItem(meta.CrossPlanTaskHead_PlanQty, grmi.Equal, false),
		meta.CrossPlanTaskHead_ActQty.UrlParameterName:          grmi.NewConditionItem(meta.CrossPlanTaskHead_ActQty, grmi.Equal, false),
		meta.CrossPlanTaskHead_Status.UrlParameterName:          grmi.NewConditionItem(meta.CrossPlanTaskHead_Status, grmi.Equal, false),
		meta.CrossPlanTaskHead_OrderType.UrlParameterName:       grmi.NewConditionItem(meta.CrossPlanTaskHead_OrderType, grmi.Equal, false),
		meta.CrossPlanTaskHead_PlanType.UrlParameterName:        grmi.NewConditionItem(meta.CrossPlanTaskHead_PlanType, grmi.Equal, false),
		meta.CrossPlanTaskHead_SchedType.UrlParameterName:       grmi.NewConditionItem(meta.CrossPlanTaskHead_SchedType, grmi.Equal, false),
		meta.CrossPlanTaskHead_BusinessObjType.UrlParameterName: grmi.NewConditionItem(meta.CrossPlanTaskHead_BusinessObjType, grmi.Equal, false),
		meta.CrossPlanTaskHead_BusinessObjId.UrlParameterName:   grmi.NewConditionItem(meta.CrossPlanTaskHead_BusinessObjId, grmi.Equal, false),
		meta.CrossPlanTaskHead_PlanStartTime.UrlParameterName:   grmi.NewConditionItem(meta.CrossPlanTaskHead_PlanStartTime, grmi.Approximate, false),
		meta.CrossPlanTaskHead_PlanEndTime.UrlParameterName:     grmi.NewConditionItem(meta.CrossPlanTaskHead_PlanEndTime, grmi.Approximate, false),
		meta.CrossPlanTaskHead_LastPo.UrlParameterName:          grmi.NewConditionItem(meta.CrossPlanTaskHead_LastPo, grmi.Equal, false),
		meta.CrossPlanTaskHead_ReleaseQty.UrlParameterName:      grmi.NewConditionItem(meta.CrossPlanTaskHead_ReleaseQty, grmi.Equal, false),
		meta.CrossPlanTaskHead_StartTime.UrlParameterName:       grmi.NewConditionItem(meta.CrossPlanTaskHead_StartTime, grmi.Approximate, false),
		meta.CrossPlanTaskHead_AccomplishTime.UrlParameterName:  grmi.NewConditionItem(meta.CrossPlanTaskHead_AccomplishTime, grmi.Approximate, false),
		meta.CrossPlanTaskHead_ErrorMsg.UrlParameterName:        grmi.NewConditionItem(meta.CrossPlanTaskHead_ErrorMsg, grmi.Equal, false),
		meta.CrossPlanTaskHead_Priority.UrlParameterName:        grmi.NewConditionItem(meta.CrossPlanTaskHead_Priority, grmi.Equal, false),
		meta.CrossPlanTaskHead_ProjectId.UrlParameterName:       grmi.NewConditionItem(meta.CrossPlanTaskHead_ProjectId, grmi.Equal, false),
		meta.CrossPlanTaskHead_CtrlStr1.UrlParameterName:        grmi.NewConditionItem(meta.CrossPlanTaskHead_CtrlStr1, grmi.Equal, false),
		meta.CrossPlanTaskHead_CtrlStr2.UrlParameterName:        grmi.NewConditionItem(meta.CrossPlanTaskHead_CtrlStr2, grmi.Equal, false),
		meta.CrossPlanTaskHead_CtrlStr3.UrlParameterName:        grmi.NewConditionItem(meta.CrossPlanTaskHead_CtrlStr3, grmi.Equal, false),
		meta.CrossPlanTaskHead_CtrlStr4.UrlParameterName:        grmi.NewConditionItem(meta.CrossPlanTaskHead_CtrlStr4, grmi.Equal, false),
		meta.CrossPlanTaskHead_CtrInt1.UrlParameterName:         grmi.NewConditionItem(meta.CrossPlanTaskHead_CtrInt1, grmi.Equal, false),
		meta.CrossPlanTaskHead_CtrInt2.UrlParameterName:         grmi.NewConditionItem(meta.CrossPlanTaskHead_CtrInt2, grmi.Equal, false),
		meta.CrossPlanTaskHead_CtrInt3.UrlParameterName:         grmi.NewConditionItem(meta.CrossPlanTaskHead_CtrInt3, grmi.Equal, false),
		meta.CrossPlanTaskHead_CtrInt4.UrlParameterName:         grmi.NewConditionItem(meta.CrossPlanTaskHead_CtrInt4, grmi.Equal, false),
		meta.CrossPlanTaskHead_LastModify.UrlParameterName:      grmi.NewConditionItem(meta.CrossPlanTaskHead_LastModify, grmi.Approximate, false),
		meta.CrossPlanTaskHead_LastUser.UrlParameterName:        grmi.NewConditionItem(meta.CrossPlanTaskHead_LastUser, grmi.Equal, false),
		meta.CrossPlanTaskHead_CreateTime.UrlParameterName:      grmi.NewConditionItem(meta.CrossPlanTaskHead_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : CrossPlanTaskHead的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2022-05-27 14:50:41
 *
 ******************************************************************************/
var DefaultConditionOfCrossPlanTaskHeadAndPaging = grmi.NewCondition(
	DefaultConditionOfCrossPlanTaskHead.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : CrossPlanTaskHeadServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : CrossPlanTaskHead的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2022-05-27 14:50:41
 *
 ******************************************************************************/
type CrossPlanTaskHeadServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewCrossPlanTaskHeadDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个CrossPlanTaskHeadDAOImplement实例
 *
 * @Return Value             : CrossPlanTaskHeadDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2022-05-27 14:50:41
 *
 ******************************************************************************/
func NewCrossPlanTaskHeadServiceImplement() *CrossPlanTaskHeadServiceImplement {
	return &CrossPlanTaskHeadServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/CrossPlanTaskHeadService.InsertOne
 *
 ******************************************************************************/
func (impl *CrossPlanTaskHeadServiceImplement) InsertOne(user *global.User, entity *model.CrossPlanTaskHead) error {

	grmi.Log(user, "/services/base/implments/CrossPlanTaskHead.service.impl.go", "InsertOneCrossPlanTaskHead", "插入一个CrossPlanTaskHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewCrossPlanTaskHeadDAO(session, 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_ACURA_MOM_BACKEND/services/base/CrossPlanTaskHeadService.DeleteOne
 *
 ******************************************************************************/
func (impl *CrossPlanTaskHeadServiceImplement) DeleteOne(user *global.User, taskNr int) error {

	grmi.Log(user, "/services/base/implments/CrossPlanTaskHead.service.impl.go", "DeleteOneCrossPlanTaskHead", "删除一个CrossPlanTaskHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewCrossPlanTaskHeadDAO(session, 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_ACURA_MOM_BACKEND/services/base/CrossPlanTaskHeadService.SelectOne
 *
 ******************************************************************************/
func (impl *CrossPlanTaskHeadServiceImplement) SelectOne(user *global.User, taskNr int) (*model.CrossPlanTaskHead, error) {

	grmi.Log(user, "/services/base/implments/CrossPlanTaskHead.service.impl.go", "SelectOneCrossPlanTaskHead", "查询一个CrossPlanTaskHead")

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

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/CrossPlanTaskHeadService.UpdateOne
 *
 ******************************************************************************/
func (impl *CrossPlanTaskHeadServiceImplement) UpdateOne(user *global.User, entity *model.CrossPlanTaskHead) error {

	grmi.Log(user, "/services/base/implments/CrossPlanTaskHead.service.impl.go", "UpdateOneCrossPlanTaskHead", "修改一个CrossPlanTaskHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewCrossPlanTaskHeadDAO(session, 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_ACURA_MOM_BACKEND/services/base/CrossPlanTaskHeadService.Insert
 *
 ******************************************************************************/
func (impl *CrossPlanTaskHeadServiceImplement) Insert(user *global.User, entities *[]model.CrossPlanTaskHead) error {

	grmi.Log(user, "/services/base/implments/CrossPlanTaskHead.service.impl.go", "InsertCrossPlanTaskHead", "插入多个CrossPlanTaskHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewCrossPlanTaskHeadDAO(session, 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_ACURA_MOM_BACKEND/services/base/CrossPlanTaskHeadService.Delete
 *
 ******************************************************************************/
func (impl *CrossPlanTaskHeadServiceImplement) Delete(user *global.User, entities *[]model.CrossPlanTaskHead) error {

	grmi.Log(user, "/services/base/implments/CrossPlanTaskHead.service.impl.go", "DeleteCrossPlanTaskHead", "删除多个CrossPlanTaskHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewCrossPlanTaskHeadDAO(session, 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_ACURA_MOM_BACKEND/services/base/CrossPlanTaskHeadService.Select
 *
 ******************************************************************************/
func (impl *CrossPlanTaskHeadServiceImplement) Select(user *global.User, urlParameters map[string]string) ([]model.CrossPlanTaskHead, error) {

	grmi.Log(user, "/services/base/implments/CrossPlanTaskHead.service.impl.go", "SelectCrossPlanTaskHead", "查询CrossPlanTaskHead")

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

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

	grmi.Log(user, "/services/base/implments/CrossPlanTaskHead.service.impl.go", "SelectCrossPlanTaskHead", "查询CrossPlanTaskHead")

	condition := DefaultConditionOfCrossPlanTaskHeadAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	dao := dal.NewCrossPlanTaskHeadDAO(session, 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/base/CrossPlanTaskHeadService.Update
 *
 ******************************************************************************/
func (impl *CrossPlanTaskHeadServiceImplement) Update(user *global.User, entities *[]model.CrossPlanTaskHead) error {

	grmi.Log(user, "/services/base/implments/CrossPlanTaskHead.service.impl.go", "UpdateCrossPlanTaskHead", "修改多个CrossPlanTaskHead")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewCrossPlanTaskHeadDAO(session, 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
}

// ReloadTask 修复跨工厂失败的任务
func (impl *CrossPlanTaskHeadServiceImplement) ReloadTask(user *global.User) error  {
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewCrossPlanTaskHeadDAO(session, user.UserId)
	failedTaskLi, err := dao.Select([]grmi.Predicate{
		meta.CrossPlanTaskHead_Status.NewPredicate(grmi.Equal, model.CROSS_TASK_STATUS_ERROR),
	}, nil)
	if err != nil {
		return grmi.NewBusinessError("查询任务数据失败, 错误:" + err.Error())
	}
	if len(failedTaskLi) == 0 {
		return nil
	}
	repairPlantNrLi := make([]int, 0)
	repairPlantMap := make(map[int][]model.CrossPlanTaskHead)
	for _, task := range failedTaskLi {
		_, exist := repairPlantMap[task.ToPlantNr]
		if !exist {
			repairPlantMap[task.ToPlantNr] = make([]model.CrossPlanTaskHead, 0)
			repairPlantNrLi = append(repairPlantNrLi, task.ToPlantNr)
		}
	}
	if err = session.Begin(); err != nil {
		return grmi.NewBusinessError("开启事务失败，错误:" + err.Error())
	}
	for _, task := range failedTaskLi {
		task.Status = model.CROSS_TASK_STATUS_PLAN
		task.ErrorMsg = ""
		err = dao.UpdateOne(&task)
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("更新任务状态失败, 错误:" + err.Error())
		}
	}
	for _, plantNr := range repairPlantNrLi {
		taskLi, err := dao.Select([]grmi.Predicate{
			meta.CrossPlanTaskHead_ToPlantNr.NewPredicate(grmi.Equal, plantNr),
			meta.CrossPlanTaskHead_Status.NewPredicate(grmi.Equal, model.CROSS_TASK_STATUS_PLAN),
		}, []grmi.Field{meta.CrossPlanTaskHead_Priority, meta.CrossPlanTaskHead_TaskNr})
		if err != nil {
			_ = session.Rollback()
			return grmi.NewBusinessError("查询任务数据失败, 错误:" + err.Error())
		}
		repairPlantMap[plantNr] = taskLi
	}
	_ = session.Commit()
	for plantNr, taskLi := range repairPlantMap {
		channel, exist := common.CrossPlantTaskCustOrderChannel[plantNr]
		if !exist {
			return grmi.NewBusinessError(fmt.Sprintf("不存在工厂:%d的任务队列", strconv.Itoa(plantNr)))
		}
		err = channel.ResetChannel()
		if err != nil {
			return grmi.NewBusinessError("刷新任务队列失败, 错误:" + err.Error())
		}
		for _, task := range taskLi {
			err = channel.SendData(task)
			if err != nil {
				return grmi.NewBusinessError("向任务队列中放任务失败, 错误:" + err.Error())
			}
		}
	}
	return nil
}