package agent

import (
	"context"
	"xingfucha-server/app/main/model"
	"xingfucha-server/common/ctxdata"
	"xingfucha-server/common/xerr"
	"xingfucha-server/pkg/lzkit/crypto"
	"encoding/hex"
	"encoding/json"
	"strconv"

	"github.com/Masterminds/squirrel"
	"github.com/pkg/errors"

	"xingfucha-server/app/main/api/internal/svc"
	"xingfucha-server/app/main/api/internal/types"

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

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

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

func (l *GeneratingLinkLogic) GeneratingLink(req *types.AgentGeneratingLinkReq) (resp *types.AgentGeneratingLinkResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成代理链接, %v", err)
	}
	productModel, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, req.Product)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成代理链接, %v", err)
	}

	agentProductConfig, err := l.svcCtx.AgentProductConfigModel.FindOneByProductId(l.ctx, productModel.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成代理链接, %v", err)
	}
	price, err := strconv.ParseFloat(req.Price, 64)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成代理链接, %v", err)
	}
	if price < agentProductConfig.PriceRangeMin || price > agentProductConfig.PriceRangeMax {
		return nil, errors.Wrapf(xerr.NewErrMsg("请设定范围区间内的价格"), "")
	}
	agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		return nil, err
	}

	build := l.svcCtx.AgentLinkModel.SelectBuilder().Where(squirrel.And{
		squirrel.Eq{"user_id": userID},
		squirrel.Eq{"product_id": productModel.Id}, // 添加 product_id 的匹配条件
		squirrel.Eq{"price": price},                // 添加 price 的匹配条件
		squirrel.Eq{"agent_id": agentModel.Id},     // 添加 agent_id 的匹配条件
	})

	agentLinkModel, err := l.svcCtx.AgentLinkModel.FindAll(l.ctx, build, "")
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成代理链接, %v", err)
	}
	if len(agentLinkModel) > 0 {
		return &types.AgentGeneratingLinkResp{
			LinkIdentifier: agentLinkModel[0].LinkIdentifier,
		}, nil
	}

	var agentIdentifier types.AgentIdentifier
	agentIdentifier.AgentID = agentModel.Id
	agentIdentifier.Product = req.Product
	agentIdentifier.Price = req.Price
	agentIdentifierByte, err := json.Marshal(agentIdentifier)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单,序列化标识失败, %v", err)
	}
	key, decodeErr := hex.DecodeString("8e3e7a2f60edb49221e953b9c029ed10")
	if decodeErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取AES密钥失败: %+v", decodeErr)
	}

	// Encrypt the params
	encrypted, err := crypto.AesEncryptURL(agentIdentifierByte, key)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成代理链接, %v", err)
	}

	var agentLink model.AgentLink
	agentLink.AgentId = agentModel.Id
	agentLink.UserId = userID
	agentLink.LinkIdentifier = encrypted
	agentLink.ProductId = productModel.Id
	agentLink.Price = price
	_, err = l.svcCtx.AgentLinkModel.Insert(l.ctx, nil, &agentLink)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成代理链接, %v", err)
	}
	return &types.AgentGeneratingLinkResp{
		LinkIdentifier: encrypted,
	}, nil
}
