package pay

import (
	"context"
	"encoding/hex"
	"strings"

	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/crypto"

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

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

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

func (l *QueryPaymentCheckLogic) QueryPaymentCheck(req *types.QueryPaymentCheckReq) (resp *types.QueryPaymentCheckResp, err error) {
	order, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询订单失败: %v", err)
	}
	product, err := l.svcCtx.ProductModel.FindOne(l.ctx, order.ProductId)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询产品失败: %v", err)
	}
	resp = new(types.QueryPaymentCheckResp)
	resp.OrderStatus = order.Status
	resp.ProductName = product.ProductName
	if order.Status == "paid" {
		authorization, err := l.svcCtx.AuthorizationModel.FindOneByOrderId(l.ctx, order.Id)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询授权信息失败: %v", err)
		}
		resp.AuthorizationStatus = authorization.Status
		key, decodeErr := hex.DecodeString(l.svcCtx.Config.Encrypt.SecretKey)
		if decodeErr != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询授权信息失败: %v", decodeErr)
		}
		decryptName, err := crypto.AesDecrypt(authorization.TargetName, key)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询授权信息失败: %v", err)
		}
		idCard, err := crypto.AesDecrypt(authorization.TargetIdcard, key)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询授权信息失败: %v", err)
		}
		resp.Name = maskName(string(decryptName))
		resp.IdCard = maskIDCard(string(idCard))
	}

	return resp, nil
}

// 姓名脱敏
func maskName(name string) string {
	// 将字符串转换为rune切片以正确处理中文字符
	runes := []rune(name)
	length := len(runes)

	if length <= 1 {
		return name
	}

	if length == 2 {
		// 两个字：保留第一个字，第二个字用*替代
		return string(runes[0]) + "*"
	}

	// 三个字及以上：保留首尾字，中间用*替代
	first := string(runes[0])
	last := string(runes[length-1])
	mask := strings.Repeat("*", length-2)

	return first + mask + last
}

// 身份证号脱敏
func maskIDCard(idCard string) string {
	length := len(idCard)
	if length <= 10 {
		return idCard // 如果长度太短，可能不是身份证，不处理
	}
	// 保留前3位和后4位
	return idCard[:3] + strings.Repeat("*", length-7) + idCard[length-4:]
}
