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

package implments

import (
	dal "LAPP_LF_MOM_BACKEND/dao/qm"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/grmi"
	meta "LAPP_LF_MOM_BACKEND/meta/qm"
	model "LAPP_LF_MOM_BACKEND/models/qm"
	"LAPP_LF_MOM_BACKEND/web/models"
	"github.com/go-xorm/xorm"
)

/******************************************************************************
 *
 * @Description              : DefectGrp的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-03-23 10:43:27
 *
 ******************************************************************************/
var DefaultConditionOfDefectGrp = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.DefectGrp_DefectGrpId.UrlParameterName: grmi.NewConditionItem(meta.DefectGrp_DefectGrpId, grmi.Equal, true),
		meta.DefectGrp_Descr.UrlParameterName:       grmi.NewConditionItem(meta.DefectGrp_Descr, grmi.Equal, false),
		meta.DefectGrp_LastModify.UrlParameterName:  grmi.NewConditionItem(meta.DefectGrp_LastModify, grmi.Approximate, false),
		meta.DefectGrp_LastUser.UrlParameterName:    grmi.NewConditionItem(meta.DefectGrp_LastUser, grmi.Equal, false),
		meta.DefectGrp_CreateTime.UrlParameterName:  grmi.NewConditionItem(meta.DefectGrp_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : DefectGrp的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-03-23 10:43:27
 *
 ******************************************************************************/
var DefaultConditionOfDefectGrpAndPaging = grmi.NewCondition(
	DefaultConditionOfDefectGrp.Items,
	grmi.NewPaging(),
)

/******************************************************************************
*
* @Struct Name              : DefectGrpServiceImplement
*-----------------------------------------------------------------------------
*
* @Description              : DefectGrp的服务实现
*
* @Author                   : 代码生成器创建
*
* @Date                     : 2021-03-23 10:43:27
*
******************************************************************************/
type DefectGrpServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewDefectGrpDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个DefectGrpDAOImplement实例
 *
 * @Return Value             : DefectGrpDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-03-23 10:43:27
 *
 ******************************************************************************/
func NewDefectGrpServiceImplement() *DefectGrpServiceImplement {
	return &DefectGrpServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/DefectGrpService.InsertOne
 *
 ******************************************************************************/
func (impl *DefectGrpServiceImplement) InsertOne(user *models.Usertab, entity *model.DefectGrp) error {

	grmi.Log(user, "/services/qm/implments/QM_DefectGrp.service.impl.go", "InsertOneDefectGrp", "插入一个DefectGrp")

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/DefectGrpService.DeleteOne
 *
 ******************************************************************************/
func (impl *DefectGrpServiceImplement) DeleteOne(user *models.Usertab, defectGrpId string) error {

	grmi.Log(user, "/services/qm/implments/QM_DefectGrp.service.impl.go", "DeleteOneDefectGrp", "删除一个DefectGrp")

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/DefectGrpService.SelectOne
 *
 ******************************************************************************/
func (impl *DefectGrpServiceImplement) SelectOne(user *models.Usertab, defectGrpId string) (*model.DefectGrp, error) {

	grmi.Log(user, "/services/qm/implments/QM_DefectGrp.service.impl.go", "SelectOneDefectGrp", "查询一个DefectGrp")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewDefectGrpDAO(session, user.Pid, user.Userid)
	result, err := dao.SelectOne(defectGrpId)
	if err != nil {
		return nil, err
	}
	// 获取缺陷分组关联
	defectGrpReasonLstDAO := dal.NewDefectGrpReasonLstDAO(session, user.Pid, user.Userid)
	groupReasons, err := defectGrpReasonLstDAO.Select([]grmi.Predicate{meta.DefectGrpReasonLst_DefectGrpId.NewPredicate(grmi.Equal, defectGrpId)}, nil)
	if err != nil {
		return nil, err
	}
	reasonIds := make([]interface{}, 0, len(groupReasons))
	for _, groupReason := range groupReasons {
		reasonIds = append(reasonIds, groupReason.DefectReasonId)
	}
	defectReasonDAO := dal.NewDefectReasonDAO(session, user.Pid, user.Userid)
	reasons, err := defectReasonDAO.Select([]grmi.Predicate{meta.DefectReason_DefectReasonId.NewPredicate(grmi.Include, reasonIds...)}, nil)
	if err != nil {
		return nil, err
	}
	result.Reasons = reasons
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/DefectGrpService.UpdateOne
 *
 ******************************************************************************/
func (impl *DefectGrpServiceImplement) UpdateOne(user *models.Usertab, entity *model.DefectGrp) error {

	grmi.Log(user, "/services/qm/implments/QM_DefectGrp.service.impl.go", "UpdateOneDefectGrp", "修改一个DefectGrp")

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

/******************************************************************************
 *
 * @Function Name            : saveReasons
 *-----------------------------------------------------------------------------
 *
 * @Description              : 保存缺陷分组下的缺陷原因
 *
 * @Function Parameters      : 当前访问人员信息
 *
 * @Function Parameters      : xorm会话
 *
 * @Function Parameters      : 缺陷分组
 *
 * @Return Value             : 执行时发生的错误
 *
 * @Author                   : chenglei.wei@le-it.com.cn
 *
 * @Date                     : 2021-03-25
 *
 ******************************************************************************/
func (impl *DefectGrpServiceImplement) saveReasons(user *models.Usertab, session *xorm.Session, entity *model.DefectGrp) error {

	if entity.Reasons != nil {
		links := make([]model.DefectGrpReasonLst, len(entity.Reasons))
		for index, reason := range entity.Reasons {
			links[index] = model.DefectGrpReasonLst{
				DefectGrpId:    entity.DefectGrpId,
				DefectReasonId: reason.DefectReasonId,
				Pos:            index + 1,
			}
		}
		defectGrpReasonLstDAO := dal.NewDefectGrpReasonLstDAO(session, user.Pid, user.Userid)
		err := defectGrpReasonLstDAO.Insert(&links)
		if err != nil {
			return err
		}
		defectReasonDAO := dal.NewDefectReasonDAO(session, user.Pid, user.Userid)
		err = defectReasonDAO.Insert(&entity.Reasons)
		if err != nil {
			return err
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Function Name            : clearReasons
 *-----------------------------------------------------------------------------
 *
 * @Description              : 清理缺陷分组下的缺陷原因
 *
 * @Function Parameters      : 当前访问人员信息
 *
 * @Function Parameters      : xorm会话
 *
 * @Function Parameters      : 缺陷分组标识
 *
 * @Return Value             : 执行时发生的错误
 *
 * @Author                   : chenglei.wei@le-it.com.cn
 *
 * @Date                     : 2021-03-25
 *
 ******************************************************************************/
func (impl *DefectGrpServiceImplement) clearReasons(user *models.Usertab, session *xorm.Session, defectGrpId string) error {

	defectGrpReasonLstDAO := dal.NewDefectGrpReasonLstDAO(session, user.Pid, user.Userid)
	links, err := defectGrpReasonLstDAO.Select([]grmi.Predicate{meta.DefectGrpReasonLst_DefectGrpId.NewPredicate(grmi.Equal, defectGrpId)}, nil)
	if err != nil {
		return err
	}
	if links != nil {
		err = defectGrpReasonLstDAO.Delete(&links)
		if err != nil {
			return err
		}
		reasonIds := make([]interface{}, len(links))
		for index, link := range links {
			reasonIds[index] = link.DefectReasonId
		}
		defectReasonDAO := dal.NewDefectReasonDAO(session, user.Pid, user.Userid)
		err = defectReasonDAO.DeleteWhere([]grmi.Predicate{meta.DefectReason_DefectReasonId.NewPredicate(grmi.Include, reasonIds...)})
		if err != nil {
			return err
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/DefectGrpService.Insert
 *
 ******************************************************************************/
func (impl *DefectGrpServiceImplement) Insert(user *models.Usertab, entities *[]model.DefectGrp) error {

	grmi.Log(user, "/services/qm/implments/QM_DefectGrp.service.impl.go", "InsertDefectGrp", "插入多个DefectGrp")

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

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

	grmi.Log(user, "/services/qm/implments/QM_DefectGrp.service.impl.go", "DeleteDefectGrp", "删除多个DefectGrp")

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

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

	grmi.Log(user, "/services/qm/implments/QM_DefectGrp.service.impl.go", "SelectDefectGrp", "查询DefectGrp")

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

	grmi.Log(user, "/services/qm/implments/QM_DefectGrp.service.impl.go", "UpdateDefectGrp", "修改多个DefectGrp")

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

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

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