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

package implments

import (
	"LAPP_LF_MOM_BACKEND/container"
	"LAPP_LF_MOM_BACKEND/dao/api"
	dalOfBase "LAPP_LF_MOM_BACKEND/dao/base"
	dal "LAPP_LF_MOM_BACKEND/dao/qm"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/grmi"
	bmeta "LAPP_LF_MOM_BACKEND/meta/base"
	meta "LAPP_LF_MOM_BACKEND/meta/qm"
	common "LAPP_LF_MOM_BACKEND/models/base"
	model "LAPP_LF_MOM_BACKEND/models/qm"
	"LAPP_LF_MOM_BACKEND/utils"
	"LAPP_LF_MOM_BACKEND/web/models"
	"fmt"
	"github.com/go-xorm/xorm"
	basedal "LAPP_LF_MOM_BACKEND/dao/base"
	"strings"
)

const (
	AreaWidth  = 100
	AreaHeight = 100
)

/******************************************************************************
 *
 * @Description              : View的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-03-23 10:43:27
 *
 ******************************************************************************/
var DefaultConditionOfView = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.View_ViewId.UrlParameterName:      grmi.NewConditionItem(meta.View_ViewId, grmi.Equal, true),
		meta.View_Descr.UrlParameterName:       grmi.NewConditionItem(meta.View_Descr, grmi.Equal, false),
		meta.View_Picture.UrlParameterName:     grmi.NewConditionItem(meta.View_Picture, grmi.Equal, false),
		meta.View_Abrev.UrlParameterName:       grmi.NewConditionItem(meta.View_Abrev, grmi.Equal, false),
		meta.View_Width.UrlParameterName:       grmi.NewConditionItem(meta.View_Width, grmi.Equal, false),
		meta.View_Height.UrlParameterName:      grmi.NewConditionItem(meta.View_Height, grmi.Equal, false),
		meta.View_XLineColor.UrlParameterName:  grmi.NewConditionItem(meta.View_XLineColor, grmi.Equal, false),
		meta.View_YLineColor.UrlParameterName:  grmi.NewConditionItem(meta.View_YLineColor, grmi.Equal, false),
		meta.View_UseXYToggle.UrlParameterName: grmi.NewConditionItem(meta.View_UseXYToggle, grmi.Equal, false),
		meta.View_LastModify.UrlParameterName:  grmi.NewConditionItem(meta.View_LastModify, grmi.Approximate, false),
		meta.View_LastUser.UrlParameterName:    grmi.NewConditionItem(meta.View_LastUser, grmi.Equal, false),
		meta.View_CreateTime.UrlParameterName:  grmi.NewConditionItem(meta.View_CreateTime, grmi.Approximate, false),
	},
	nil,
)

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

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

func (impl *ViewServiceImplement) SetSession(value *container.SessionContext) {

	impl.session = value
}

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ViewService.InsertOne
 *
 ******************************************************************************/
func (impl *ViewServiceImplement) InsertOne(user *models.Usertab, entity *model.View) error {

	grmi.Log(user, "/services/qm/implments/QM_View.service.impl.go", "InsertOneView", "插入一个View")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewViewDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.ViewId)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	err = impl.saveGroups(user, session, entity)
	if err != nil {
		return err
	}
	err = impl.createAreas(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/ViewService.DeleteOne
 *
 ******************************************************************************/
func (impl *ViewServiceImplement) DeleteOne(user *models.Usertab, viewId string) error {

	grmi.Log(user, "/services/qm/implments/QM_View.service.impl.go", "DeleteOneView", "删除一个View")

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

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ViewService.SelectOne
 *
 ******************************************************************************/
func (impl *ViewServiceImplement) SelectOne(user *models.Usertab, viewId string) (*model.View, error) {

	grmi.Log(user, "/services/qm/implments/QM_View.service.impl.go", "SelectOneView", "查询一个View")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewViewDAO(session, user.Pid, user.Userid)
	result, err := dao.SelectOne(viewId)
	if err != nil {
		return nil, err
	}
	if result == nil {
		return nil, nil
	}
	viewValstDAO := dal.NewViewValstDAO(session, user.Pid, user.Userid)
	areas, err := viewValstDAO.Select([]grmi.Predicate{meta.ViewValst_ViewId.NewPredicate(grmi.Equal, viewId)}, nil)
	if err != nil {
		return nil, err
	}
	result.Areas = areas
	viewDefectGrplstDAO := dal.NewViewDefectGrplstDAO(session, user.Pid, user.Userid)
	viewGroups, err := viewDefectGrplstDAO.Select([]grmi.Predicate{meta.ViewDefectGrplst_ViewId.NewPredicate(grmi.Equal, viewId)}, nil)
	if err != nil {
		return nil, err
	}
	groupIds := make([]interface{}, 0, len(viewGroups))
	for _, viewGroup := range viewGroups {
		groupIds = append(groupIds, viewGroup.DefectGrpId)
	}
	defectGrpDAO := dal.NewDefectGrpDAO(session, user.Pid, user.Userid)
	groups, err := defectGrpDAO.Select([]grmi.Predicate{meta.DefectGrp_DefectGrpId.NewPredicate(grmi.Include, groupIds...)}, nil)
	if err != nil {
		return nil, err
	}
	result.Groups = groups
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ViewService.UpdateOne
 *
 ******************************************************************************/
func (impl *ViewServiceImplement) UpdateOne(user *models.Usertab, entity *model.View) error {

	grmi.Log(user, "/services/qm/implments/QM_View.service.impl.go", "UpdateOneView", "修改一个View")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewViewDAO(session, user.Pid, user.Userid)
	record, err := dao.SelectOne(entity.ViewId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = impl.clearGroups(user, session, entity.ViewId)
	if err != nil {
		return err
	}
	err = impl.clearAreas(user, session, entity.ViewId)
	if err != nil {
		return err
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		return err
	}
	err = impl.saveGroups(user, session, entity)
	if err != nil {
		return err
	}
	if entity.Width != record.Width || entity.Height != record.Height {
		err = impl.createAreas(user, session, entity)
		if err != nil {
			return err
		}
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

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

	if entity.Groups != nil {
		defectGrpDAO := dal.NewDefectGrpDAO(session, user.Pid, user.Userid)
		links := make([]model.ViewDefectGrplst, len(entity.Groups))
		for index, group := range entity.Groups {
			record, err := defectGrpDAO.SelectOne(group.DefectGrpId)
			if err != nil {
				return err
			}
			if record == nil {
				return grmi.NewBusinessError("不存在指定缺陷分组!")
			}
			links[index] = model.ViewDefectGrplst{
				ViewId:      entity.ViewId,
				DefectGrpId: group.DefectGrpId,
				Pos:         index + 1,
			}
		}
		viewDefectGrplstDAO := dal.NewViewDefectGrplstDAO(session, user.Pid, user.Userid)
		err := viewDefectGrplstDAO.Insert(&links)
		if err != nil {
			return err
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Function Name            : createAreas
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建视图区域
 *
 * @Function Parameters      : 当前访问人员信息
 *
 * @Function Parameters      : xorm会话
 *
 * @Function Parameters      : 视图
 *
 * @Return Value             : 执行时发生的错误
 *
 * @Author                   : chenglei.wei@le-it.com.cn
 *
 * @Date                     : 2021-03-25
 *
 ******************************************************************************/
func (impl *ViewServiceImplement) createAreas(user *models.Usertab, session *xorm.Session, entity *model.View) error {

	rowCount := entity.Width / AreaWidth
	columnCount := entity.Height / AreaHeight
	if entity.Width%AreaWidth > 0 {
		rowCount++
	}
	if entity.Height%AreaHeight > 0 {
		columnCount++
	}

	areas := make([]model.ViewValst, rowCount*columnCount)
	for row := 0; row < rowCount; row++ {
		for column := 0; column < columnCount; column++ {
			index := row*columnCount + column
			name := fmt.Sprintf("#%d", index)
			areas[index] = model.ViewValst{
				ViewId:  entity.ViewId,
				Pos:     index + 1,
				ValName: name,
				XStart:  column * columnCount,
				YStart:  row * rowCount,
				Width:   AreaWidth,
				Height:  AreaHeight,
				Descr:   name,
			}
		}
	}
	viewValstDAO := dal.NewViewValstDAO(session, user.Pid, user.Userid)
	err := viewValstDAO.Insert(&areas)
	if err != nil {
		return err
	}
	return nil
}

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

	viewDefectGrplstDAO := dal.NewViewDefectGrplstDAO(session, user.Pid, user.Userid)
	links, err := viewDefectGrplstDAO.Select([]grmi.Predicate{meta.ViewDefectGrplst_ViewId.NewPredicate(grmi.Equal, viewId)}, nil)
	if err != nil {
		return err
	}
	if links != nil {
		err = viewDefectGrplstDAO.Delete(&links)
		if err != nil {
			return err
		}
		groupIds := make([]string, len(links))
		for index, link := range links {
			groupIds[index] = link.DefectGrpId
		}
	}
	return nil
}

/******************************************************************************
 *
 * @Function Name            : clearAreas
 *-----------------------------------------------------------------------------
 *
 * @Description              : 清理与视图关联的视图区域
 *
 * @Function Parameters      : 当前访问人员信息
 *
 * @Function Parameters      : xorm会话
 *
 * @Function Parameters      : 视图标识
 *
 * @Return Value             : 执行时发生的错误
 *
 * @Author                   : chenglei.wei@le-it.com.cn
 *
 * @Date                     : 2021-03-25
 *
 ******************************************************************************/
func (impl *ViewServiceImplement) clearAreas(user *models.Usertab, session *xorm.Session, viewId string) error {

	viewValstDAO := dal.NewViewValstDAO(session, user.Pid, user.Userid)
	err := viewValstDAO.DeleteWhere([]grmi.Predicate{meta.ViewValst_ViewId.NewPredicate(grmi.Equal, viewId)})
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_LF_MOM_BACKEND/services/qm/ViewService.Insert
 *
 ******************************************************************************/
func (impl *ViewServiceImplement) Insert(user *models.Usertab, entities *[]model.View) error {

	grmi.Log(user, "/services/qm/implments/QM_View.service.impl.go", "InsertView", "插入多个View")

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

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

	grmi.Log(user, "/services/qm/implments/QM_View.service.impl.go", "DeleteView", "删除多个View")

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

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

	grmi.Log(user, "/services/qm/implments/QM_View.service.impl.go", "SelectView", "查询View")

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

	grmi.Log(user, "/services/qm/implments/QM_View.service.impl.go", "UpdateView", "修改多个View")

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.ViewId)
		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/qm/ViewService.ViewsOfArticle
 *
 ******************************************************************************/
func (impl *ViewServiceImplement) ViewsOfArticle(context *container.RequestContext, orderId string) ([]model.View, error) {

	grmi.Log(impl.session.User(), "/C:/Users/Wei Chenglei/source/repos/GAAS_BackEnd/services/qm/implments/QM_View.service.impl.go", "ViewsOfArticle", "查询与指定Article关联的视图")

	//截取物料id
	bdal := basedal.NewLabelParserHeadDAO(context.Session(), impl.session.User().Pid, impl.session.User().Userid)

	result, err := bdal.SelectOne("Barcode")
	if err != nil {
		return nil,err
	}

	var artId string
	if utils.ValueIsEmpty(result.Split) {
		lstdao := basedal.NewLabelParserDetailLstDAO(context.Session(), impl.session.User().Pid, impl.session.User().Userid)
		list, err := lstdao.Select([]grmi.Predicate{
			bmeta.LabelParserDetailLst_ParserId.NewPredicate(grmi.Equal, "Barcode"),
		}, nil)
		if err != nil {
			return nil, err
		}
		result.Valst = list
		if len(orderId) < result.Length {
			return nil,grmi.NewBusinessError("序列订单错误!")
		}
		codeInfos := common.ParseBarcode(orderId, result.Valst)
		artId = codeInfos["artId"]
	} else {
		artIds := strings.Split(orderId, result.Split)
		artId = artIds[0]
	}

	slaves := db.Eloquent.Slaves()
	slavesession := slaves[0].NewSession()
	defer slavesession.Close()
	apiDao := api.NewACCUNITSTATUSDAO(slavesession, impl.session.User().Userid)
	mesData,err := apiDao.SelectOne(orderId, "LaserWelding")
	if err != nil {
		return nil, err
	}
	if mesData == nil{
		return nil,grmi.NewBusinessError("该唯一码不存在!")
	}
	if mesData.STATUS != "2"{
		return nil,grmi.NewBusinessError("上一工序未完成!")
	}

	// 获取Article
	articleDAO := dalOfBase.NewArticleDAO(context.Session(), impl.session.User().Pid, impl.session.User().Userid)
	article, err := articleDAO.SelectOne(artId)
	if err != nil {
		return nil, err
	}
	if article == nil {
		return nil, grmi.NewBusinessError("不存在指定Article!")
	}
	// 获取Article和视图的关联
	artViewDAO := dal.NewArtViewDAO(context.Session(), impl.session.User().Pid, impl.session.User().Userid)
	artViews, err := artViewDAO.Select([]grmi.Predicate{meta.ArtView_ArtId.NewPredicate(grmi.Equal, article.ArtId)}, nil)
	if err != nil {
		return nil, err
	}
	// 从关联中获取视图标识
	viewIds := make([]interface{}, len(artViews))
	for i, artView := range artViews {
		viewIds[i] = artView.ViewId
	}
	// 获取视图
	viewDAO := dal.NewViewDAO(context.Session(), impl.session.User().Pid, impl.session.User().Userid)
	views, err := viewDAO.Select([]grmi.Predicate{meta.View_ViewId.NewPredicate(grmi.Include, viewIds...)}, nil)
	if err != nil {
		return nil, err
	}
	// 构造视图ID与视图的关联,用以将视图区域和缺陷分组关联到视图
	viewMapping := make(map[string]*model.View, len(artViews))
	for index, view := range views {
		viewMapping[view.ViewId] = &views[index]
	}
	// 获取视图区域
	viewValstDAO := dal.NewViewValstDAO(context.Session(), impl.session.User().Pid, impl.session.User().Userid)
	areas, err := viewValstDAO.Select([]grmi.Predicate{meta.ViewValst_ViewId.NewPredicate(grmi.Include, viewIds...)}, nil)
	if err != nil {
		return nil, err
	}
	// 将视图区域关联到视图
	for _, area := range areas {
		view, ok := viewMapping[area.ViewId]
		if ok {
			view.Areas = append(view.Areas, area)
		}
	}
	// 获取视图缺陷分组关联
	viewDefectGrplstDAO := dal.NewViewDefectGrplstDAO(context.Session(), impl.session.User().Pid, impl.session.User().Userid)
	viewGroups, err := viewDefectGrplstDAO.Select([]grmi.Predicate{meta.ViewDefectGrplst_ViewId.NewPredicate(grmi.Include, viewIds...)}, nil)
	if err != nil {
		return nil, err
	}
	// 1.构造缺陷分组ID到视图ID的映射,用以将缺陷分组关联到视图
	// 2.从关联中获取缺陷分组标识
	group2ViewMapping := make(map[string][]string, len(viewGroups))
	groupIds := make([]interface{}, 0, len(viewGroups))
	for _, viewGroup := range viewGroups {
		groupIds = append(groupIds, viewGroup.DefectGrpId)
		viewIds, ok := group2ViewMapping[viewGroup.DefectGrpId]
		if !ok {
			viewIds = make([]string, 0, 10)
		}
		group2ViewMapping[viewGroup.DefectGrpId] = append(viewIds, viewGroup.ViewId)
	}
	// 获取缺陷缺陷分组
	defectGrpDAO := dal.NewDefectGrpDAO(context.Session(), impl.session.User().Pid, impl.session.User().Userid)
	groups, err := defectGrpDAO.Select([]grmi.Predicate{meta.DefectGrp_DefectGrpId.NewPredicate(grmi.Include, groupIds...)}, nil)
	if err != nil {
		return nil, err
	}
	// 构造缺陷分组ID与缺陷分组的关联,用以将缺陷原因关联到缺陷分组
	groupMapping := make(map[string]*model.DefectGrp, len(groups))
	for index, group := range groups {
		groupIds = append(groupIds, group.DefectGrpId)
		groupMapping[group.DefectGrpId] = &groups[index]
	}
	// 获取缺陷分组关联
	defectGrpReasonLstDAO := dal.NewDefectGrpReasonLstDAO(context.Session(), impl.session.User().Pid, impl.session.User().Userid)
	groupReasons, err := defectGrpReasonLstDAO.Select([]grmi.Predicate{meta.DefectGrpReasonLst_DefectGrpId.NewPredicate(grmi.Include, groupIds...)}, nil)
	if err != nil {
		return nil, err
	}
	// 1.构造缺陷原因ID到缺陷分组ID的映射,用以将缺陷原因关联到缺陷分组
	// 2.从关联中获取缺陷原因标识
	reason2GroupMapping := make(map[string][]string, len(groupReasons))
	reasonIds := make([]interface{}, 0, len(groupReasons))
	for _, groupReason := range groupReasons {
		reasonIds = append(reasonIds, groupReason.DefectReasonId)
		groupIds, ok := reason2GroupMapping[groupReason.DefectReasonId]
		if !ok {
			groupIds = make([]string, 0, 10)
		}
		reason2GroupMapping[groupReason.DefectReasonId] = append(groupIds, groupReason.DefectGrpId)
	}
	// 获取缺陷原因
	defectReasonDAO := dal.NewDefectReasonDAO(context.Session(), impl.session.User().Pid, impl.session.User().Userid)
	reasons, err := defectReasonDAO.Select([]grmi.Predicate{meta.DefectReason_DefectReasonId.NewPredicate(grmi.Include, reasonIds...)}, nil)
	if err != nil {
		return nil, err
	}
	// 将缺陷原因关联到缺陷分组
	for _, reason := range reasons {
		groupIds, ok := reason2GroupMapping[reason.DefectReasonId]
		if ok {
			for _, groupId := range groupIds {
				group, ok := groupMapping[groupId]
				if ok {
					group.Reasons = append(group.Reasons, reason)
				}
			}
		}
	}
	// 将缺陷分组关联到视图,放到最后是因为view.Groups的成员是值而不是引用,如果提前填充view.Groups,里面值的Reasons将会是是nil.
	for _, group := range groups {
		viewIds, ok := group2ViewMapping[group.DefectGrpId]
		if ok {
			for _, viewId := range viewIds {
				view, ok := viewMapping[viewId]
				if ok {
					view.Groups = append(view.Groups, group)
				}
			}
		}
	}
	return views, nil
}
