package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"jyBXCore/rpc/internal/svc"
	"jyBXCore/rpc/model/es"
	"jyBXCore/rpc/model/mysql"
	"jyBXCore/rpc/service"
	"jyBXCore/rpc/type/bxcore"
	"jyBXCore/rpc/util"
)

type ParticipateShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewParticipateShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ParticipateShowLogic {
	return &ParticipateShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 列表数据参标信息接口
func (l *ParticipateShowLogic) ParticipateShow(in *bxcore.ParticipateShowReq) (*bxcore.ParticipateShowRes, error) {
	result := bxcore.ParticipateShowRes{
		Data: []*bxcore.ShowInfo{},
	}
	b, entRoleId := util.IsAllowedParticipate(in.AppId, in.MgoUserId, in.NewUserId, in.AccountId, in.EntAccountId, in.EntId, in.EntUserId, in.PositionId, in.PositionType)
	if !b {
		result.ErrMsg = "没有权限"
		return &result, nil
	}
	participateService := service.NewParticipateBid(in.EntId, in.EntUserId, in.PositionType, in.PositionId)
	participateService.EntRoleId = entRoleId
	// 2. 根据标讯id 查询项目信息 拿到有效的项目id (无项目信息或者已经过开标时间  则不展示按钮  在开标时间内或者没有开标时间字段需要展示)
	// 信息id解密
	infoList, infoSet := service.DecodeId(in.Ids)
	if len(infoList) == 0 {
		result.ErrCode = -1
		result.ErrMsg = "信息id无效"
		return &result, nil
	}
	// 查有效项目id信息
	projectInfos := es.GetValidProjectByInfoId(infoList)
	if projectInfos == nil || len(*projectInfos) == 0 {
		return &result, nil
	}
	// 记录信息id和项目id的映射  用于最后处理返回数据
	infoM, projectIds := service.HandlerProjectId(*projectInfos, infoSet)
	// 3. 查询参标信息 处理按钮 区分个人和企业
	var formatList []*bxcore.ShowInfo
	switch int(in.PositionType) {
	case service.PositionTypePersonal:
		existList := participateService.PersonalExistProject(projectIds)
		formatList = participateService.ListPersonalFormat(existList, infoM)
	case service.PositionTypeEnt:
		isAllow := mysql.IsALLow(in.EntId)
		existList := participateService.EntExistProject(projectIds)              // 查询出已经存在的
		formatList = participateService.ListEntFormat(existList, infoM, isAllow) // 格式化数据
	}
	result.Data = formatList
	return &result, nil
}
