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

package implments

import (
	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"
	baseModel "LAPP_LF_MOM_BACKEND/models/base"
	model "LAPP_LF_MOM_BACKEND/models/om"
	"LAPP_LF_MOM_BACKEND/web/models"
	"strconv"
)

/******************************************************************************
 *
 * @Description              : WorkOrderStatus的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-19 14:04:47
 *
 ******************************************************************************/
var DefaultConditionOfWorkOrderStatus = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.WorkOrderStatus_WorkOrderId.UrlParameterName:        grmi.NewConditionItem(meta.WorkOrderStatus_WorkOrderId, grmi.Equal, true),
		meta.WorkOrderStatus_Status.UrlParameterName:             grmi.NewConditionItem(meta.WorkOrderStatus_Status, grmi.Equal, false),
		meta.WorkOrderStatus_TriggerEvent.UrlParameterName:       grmi.NewConditionItem(meta.WorkOrderStatus_TriggerEvent, grmi.Equal, false),
		meta.WorkOrderStatus_TriggerObjectId.UrlParameterName:    grmi.NewConditionItem(meta.WorkOrderStatus_TriggerObjectId, grmi.Equal, false),
		meta.WorkOrderStatus_TriggerSubObjectId.UrlParameterName: grmi.NewConditionItem(meta.WorkOrderStatus_TriggerSubObjectId, grmi.Equal, false),
		meta.WorkOrderStatus_LastModify.UrlParameterName:         grmi.NewConditionItem(meta.WorkOrderStatus_LastModify, grmi.Approximate, false),
		meta.WorkOrderStatus_LastUser.UrlParameterName:           grmi.NewConditionItem(meta.WorkOrderStatus_LastUser, grmi.Equal, false),
		meta.WorkOrderStatus_CreateTime.UrlParameterName:         grmi.NewConditionItem(meta.WorkOrderStatus_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : WorkOrderStatus的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-19 14:04:47
 *
 ******************************************************************************/
var DefaultConditionOfWorkOrderStatusAndPaging = grmi.NewCondition(
	DefaultConditionOfWorkOrderStatus.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : WorkOrderStatusServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : WorkOrderStatus的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-19 14:04:47
 *
 ******************************************************************************/
type WorkOrderStatusServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewWorkOrderStatusDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个WorkOrderStatusDAOImplement实例
 *
 * @Return Value             : WorkOrderStatusDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-19 14:04:47
 *
 ******************************************************************************/
func NewWorkOrderStatusServiceImplement() *WorkOrderStatusServiceImplement {
	return &WorkOrderStatusServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/WorkOrderStatusService.InsertOne
 *
 ******************************************************************************/
func (impl *WorkOrderStatusServiceImplement) InsertOne(user *models.Usertab, entity *model.WorkOrderStatus) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewWorkOrderStatusDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.WorkOrderId)
	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/WorkOrderStatusService.DeleteOne
 *
 ******************************************************************************/
func (impl *WorkOrderStatusServiceImplement) DeleteOne(user *models.Usertab, workOrderId string) error {

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/WorkOrderStatusService.SelectOne
 *
 ******************************************************************************/
func (impl *WorkOrderStatusServiceImplement) SelectOne(user *models.Usertab, workOrderId string) (*model.WorkOrderStatus, error) {

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

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/om/WorkOrderStatusService.UpdateOne
 *
 ******************************************************************************/
func (impl *WorkOrderStatusServiceImplement) UpdateOne(user *models.Usertab, entity *model.WorkOrderStatus) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewWorkOrderStatusDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.WorkOrderId)
	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/WorkOrderStatusService.Insert
 *
 ******************************************************************************/
func (impl *WorkOrderStatusServiceImplement) Insert(user *models.Usertab, entities *[]model.WorkOrderStatus) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.WorkOrderId)
		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/WorkOrderStatusService.Delete
 *
 ******************************************************************************/
func (impl *WorkOrderStatusServiceImplement) Delete(user *models.Usertab, entities *[]model.WorkOrderStatus) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.WorkOrderId)
		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/WorkOrderStatusService.Select
 *
 ******************************************************************************/
func (impl *WorkOrderStatusServiceImplement) Select(user *models.Usertab, urlParameters map[string]string) (interface{}, error) {

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

	condition := DefaultConditionOfWorkOrderStatusAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewWorkOrderStatusDAO(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/WorkOrderStatusService.Update
 *
 ******************************************************************************/
func (impl *WorkOrderStatusServiceImplement) Update(user *models.Usertab, entities *[]model.WorkOrderStatus) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.WorkOrderId)
		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/WorkOrderStatusService.ChangeStatus
 *
 ******************************************************************************/
func (impl *WorkOrderStatusServiceImplement) ChangeStatus(user *models.Usertab, li []model.WorkOrderStatusChange) error {
	grmi.Log(user, "/services/om/implments/WorkOrderStatus.service.impl.go", "ChangeStatus", "修改多个WorkOrderStatus")
	log, _ := logger.NewLogger(user.Userid, "OM")
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewWorkOrderStatusDAO(session, user.Pid, user.Userid)
	recDao := dal.NewWorkOrderStatusRecLstDAO(session, user.Pid, user.Userid)
	for _, entity := range li {

		record, err := dao.SelectOne(entity.WorkOrderId)
		if err != nil {
			return err
		}
		if record == nil {
			return grmi.NewBusinessError("不存在指定记录!")
		}
		switch entity.Status {
		case baseModel.WO_STATUS_UNPLANNED:
			return grmi.NewBusinessError("order status is already WO_STATUS_UNPLANNED, workOderId: "+ entity.WorkOrderId)
		case baseModel.WO_STATUS_PLANNED:
			if record.Status == baseModel.WO_STATUS_UNPLANNED {
				return grmi.NewBusinessError("order status is non sequence, workOrderId:" + entity.WorkOrderId + " change status:" + strconv.Itoa(entity.Status))
			}
		case baseModel.WO_STATUS_LOCKED:
			if record.Status == baseModel.WO_STATUS_PLANNED {
				return grmi.NewBusinessError("order status is non sequence, workOrderId:" + entity.WorkOrderId + " change status:" + strconv.Itoa(entity.Status))
			}
		case baseModel.WO_STATUS_RELEASED:
			if record.Status == baseModel.WO_STATUS_LOCKED {
				return grmi.NewBusinessError("order status is non sequence, workOrderId:" + entity.WorkOrderId + " change status:" + strconv.Itoa(entity.Status))
			}
		case baseModel.WO_STATUS_RUNNING:
			if record.Status == baseModel.WO_STATUS_RELEASED || record.Status == baseModel.WO_STATUS_INTERRUPT{
				return grmi.NewBusinessError("order status is non sequence, workOrderId:" + entity.WorkOrderId + " change status:" + strconv.Itoa(entity.Status))
			}
		case baseModel.WO_STATUS_FINISHED:
			if record.Status == baseModel.WO_STATUS_RUNNING {
				return grmi.NewBusinessError("order status is non sequence, workOrderId:" + entity.WorkOrderId + " change status:" + strconv.Itoa(entity.Status))
			}
		case baseModel.WO_STATUS_DISPATCHED:
			if record.Status == baseModel.WO_STATUS_FINISHED {
				return grmi.NewBusinessError("order status is non sequence, workOrderId:" + entity.WorkOrderId + " change status:" + strconv.Itoa(entity.Status))
			}
		case baseModel.WO_STATUS_FROZEN:
			if record.Status == baseModel.WO_STATUS_DISPATCHED {
				return grmi.NewBusinessError("order status is non sequence, workOrderId:" + entity.WorkOrderId + " change status:" + strconv.Itoa(entity.Status))
			}
		case baseModel.WO_STATUS_CANCELED:
			if record.Status == baseModel.WO_STATUS_FROZEN {
				return grmi.NewBusinessError("order status is non sequence, workOrderId:" + entity.WorkOrderId + " change status:" + strconv.Itoa(entity.Status))
			}
		}
		//maxPos, err := recDao.GetMaxPos(entity.WorkOrderId)
		//if err != nil {
		//	log.Debug("get max pos failed, error:" + err.Error(), record.WorkOrderId)
		//	session.Rollback()
		//	return err
		//}
		rec := model.WorkOrderStatusRecLst{
			WorkOrderId: record.WorkOrderId,
			//Pos: maxPos+1,
			PrevStatus: record.Status,
		}
		err = recDao.InsertOne(&rec)
		if err != nil {
			log.Debug("insert rec status data failed, error: " + err.Error(), record.WorkOrderId)
			session.Rollback()
			return err
		}
		record.Status = entity.Status
		err = dao.UpdateOne(record)
		if err != nil {
			log.Debug("update work order status failed, error: " + err.Error(), record.WorkOrderId)
			session.Rollback()
			return err
		}
	}
	return nil
}
