package logic

import (
	"app.yhyue.com/moapp/jybase/common"
	"app.yhyue.com/moapp/jybase/encrypt"
	"context"
	"jyBXCore/rpc/model/es"
	"jyBXCore/rpc/model/mysql"
	"jyBXCore/rpc/service"
	"jyBXCore/rpc/util"
	"time"

	"jyBXCore/rpc/internal/svc"
	"jyBXCore/rpc/type/bxcore"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

// 详情页参标信息接口
func (l *ParticipateInfoLogic) ParticipateInfo(in *bxcore.ParticipateInfoReq) (*bxcore.ParticipateInfoRes, error) {
	format := &bxcore.ParticipateDetailInfo{}
	result := bxcore.ParticipateInfoRes{
		Data: format,
	}
	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
	// 信息id解密
	infoList, infoSet := service.DecodeId(in.Sid)
	if len(infoList) == 0 {
		result.ErrCode = -1
		result.ErrMsg = "信息id无效"
		return &result, nil
	}
	// 2. 根据标讯id 查询项目信息
	projectInfos := es.GetProjectByInfoId(infoList)
	if projectInfos == nil || len(*projectInfos) == 0 {
		result.ErrMsg = "未查到此项目信息"
		return &result, nil
	}
	// 判断是否已经过了投标截止时间
	isValid := true
	bidendtime := common.Int64All((*projectInfos)[0]["bidendtime"])
	bidopentime := common.Int64All((*projectInfos)[0]["bidopentime"])
	now := time.Now().Unix()
	if (now > bidopentime && bidopentime != 0) || (now > bidendtime && bidendtime != 0) {
		isValid = false
	}
	//   获取项目id
	_, projectIds := service.HandlerProjectId(*projectInfos, infoSet)
	//区分个人和企业
	var formatData *bxcore.ParticipateDetailInfo
	switch int(in.PositionType) {
	case service.PositionTypePersonal:
		existList := participateService.PersonalExistProject(projectIds)
		formatData = participateService.DetailPersonalFormat(existList, isValid, bidendtime)
	case service.PositionTypeEnt:
		isAllow := mysql.IsALLow(in.EntId)
		existList := participateService.EntExistProject(projectIds)                              // 查询出已经存在的
		formatData = participateService.DetailEntFormat(existList, isValid, isAllow, bidendtime) // 格式化数据
	}
	formatData.ProjectId = encrypt.EncodeArticleId2ByCheck(projectIds[0])
	result.Data = formatData
	return &result, nil

}
