package logic

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

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

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

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

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

// 投标状态更新
func (l *UpdateBidStatusLogic) UpdateBidStatus(in *bxcore.UpdateBidStatusReq) (*bxcore.UpdateBidStatusRes, error) {
	result := &bxcore.UpdateBidStatusRes{
		ErrCode: -1,
	}
	if msg := util.IsAllowedAccess("updatebidstatus"); msg != "" {
		result.ErrMsg = msg
		return result, nil
	}
	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, _ := service.DecodeId(in.Sid)
	if len(infoList) == 0 {
		result.ErrMsg = "信息id无效"
		return result, nil
	}
	// 根据标讯id 查询项目信息
	projectInfos := es.GetProjectByInfoId(infoList)
	if projectInfos == nil || len(*projectInfos) == 0 {
		result.ErrMsg = "未查询到项目信息"
		return result, nil
	}
	// 判断是否已经过了投标截止时间
	bidendtime := common.Int64All((*projectInfos)[0]["bidendtime"])
	bidopentime := common.Int64All((*projectInfos)[0]["bidopentime"])
	projectId := common.ObjToString((*projectInfos)[0]["_id"])
	now := time.Now().Unix()
	if (now > bidopentime && bidopentime != 0) || (now > bidendtime && bidendtime != 0) {
		result.ErrMsg = "已经过投标截止时间，无法更新"
		return result, nil
	}
	// 验证身份
	if !participateService.CheckUpdateBidPower(projectId, true) {
		result.ErrMsg = "没有更新权限"
		return result, nil
	}
	// 2. 更新
	if err := participateService.UpdateBidStatus(in, projectId); err != nil {
		result.ErrMsg = err.Error()
	} else {
		result.Data = true
		result.ErrCode = 0
	}
	return result, nil
}
