package query

import (
	"context"
	"database/sql"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"
	"time"
	"xingfucha-server/app/main/api/internal/service"
	"xingfucha-server/app/main/model"
	"xingfucha-server/common/ctxdata"
	"xingfucha-server/common/xerr"
	"xingfucha-server/pkg/lzkit/crypto"
	"xingfucha-server/pkg/lzkit/validator"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/stores/redis"

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

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

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

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

func (l *QueryServiceLogic) QueryService(req *types.QueryServiceReq) (resp *types.QueryServiceResp, err error) {
	if req.AgentIdentifier != "" {
		// return nil, errors.Wrapf(xerr.NewErrMsg("系统正在升级，查询服务暂不可用，恢复时间待定"), "查询服务暂停, AgentIdentifier: %s", req.AgentIdentifier)

		l.ctx = context.WithValue(l.ctx, "agentIdentifier", req.AgentIdentifier)
	} else if req.App {
		l.ctx = context.WithValue(l.ctx, "app", req.App)
	}
	return l.PreprocessLogic(req, req.Product)
}

var productProcessors = map[string]func(*QueryServiceLogic, *types.QueryServiceReq) (*types.QueryServiceResp, error){
	"marriage":               (*QueryServiceLogic).ProcessMarriageLogic,
	"homeservice":            (*QueryServiceLogic).ProcessHomeServiceLogic,
	"riskassessment":         (*QueryServiceLogic).ProcessRiskAssessmentLogic,
	"companyinfo":            (*QueryServiceLogic).ProcessCompanyInfoLogic,
	"rentalinfo":             (*QueryServiceLogic).ProcessRentalInfoLogic,
	"preloanbackgroundcheck": (*QueryServiceLogic).ProcessPreLoanBackgroundCheckLogic,
	"backgroundcheck":        (*QueryServiceLogic).ProcessBackgroundCheckLogic,
	"personalData":           (*QueryServiceLogic).ProcessPersonalDataLogic,
}

func (l *QueryServiceLogic) PreprocessLogic(req *types.QueryServiceReq, product string) (*types.QueryServiceResp, error) {
	if processor, exists := productProcessors[product]; exists {
		return processor(l, req) // 调用对应的处理函数
	}
	return nil, errors.New("未找到相应的处理程序")
}
func (l *QueryServiceLogic) ProcessMarriageLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {

	// AES解密
	decryptData, DecryptDataErr := l.DecryptData(req.Data)
	if DecryptDataErr != nil {
		return nil, DecryptDataErr
	}

	// 校验参数
	var data types.MarriageReq
	if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
	}

	if validatorErr := validator.Validate(data); validatorErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
	}

	// 校验验证码
	verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
	if verifyCodeErr != nil {
		return nil, verifyCodeErr
	}

	// 校验三要素
	verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
	if verifyErr != nil {
		return nil, verifyErr
	}

	// 缓存
	params := map[string]interface{}{
		"name":    data.Name,
		"id_card": data.IDCard,
		"mobile":  data.Mobile,
	}
	userID, err := l.GetOrCreateUser()
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
	}
	cacheNo, cacheDataErr := l.CacheData(params, "marriage", userID)
	if cacheDataErr != nil {
		return nil, cacheDataErr
	}
	l.recordQueryUserRecord(params, "marriage", userID, cacheNo)
	token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
	}

	// 获取当前时间戳
	now := time.Now().Unix()
	return &types.QueryServiceResp{
		Id:           cacheNo,
		AccessToken:  token,
		AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
		RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
	}, nil
}

// 处理家政服务相关逻辑
func (l *QueryServiceLogic) ProcessHomeServiceLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {

	// AES解密
	decryptData, DecryptDataErr := l.DecryptData(req.Data)
	if DecryptDataErr != nil {
		return nil, DecryptDataErr
	}

	// 校验参数
	var data types.HomeServiceReq
	if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
	}

	if validatorErr := validator.Validate(data); validatorErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
	}

	// 校验验证码
	verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
	if verifyCodeErr != nil {
		return nil, verifyCodeErr
	}

	// 校验三要素
	verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
	if verifyErr != nil {
		return nil, verifyErr
	}

	// 缓存
	params := map[string]interface{}{
		"name":    data.Name,
		"id_card": data.IDCard,
		"mobile":  data.Mobile,
	}
	userID, err := l.GetOrCreateUser()
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
	}
	cacheNo, cacheDataErr := l.CacheData(params, "homeservice", userID)
	if cacheDataErr != nil {
		return nil, cacheDataErr
	}
	l.recordQueryUserRecord(params, "homeservice", userID, cacheNo)
	token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
	}

	// 获取当前时间戳
	now := time.Now().Unix()
	return &types.QueryServiceResp{
		Id:           cacheNo,
		AccessToken:  token,
		AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
		RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
	}, nil
}

// 处理风险评估相关逻辑
func (l *QueryServiceLogic) ProcessRiskAssessmentLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {

	// AES解密
	decryptData, DecryptDataErr := l.DecryptData(req.Data)
	if DecryptDataErr != nil {
		return nil, DecryptDataErr
	}

	// 校验参数
	var data types.RiskAssessmentReq
	if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
	}

	if validatorErr := validator.Validate(data); validatorErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
	}

	// 校验验证码
	verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
	if verifyCodeErr != nil {
		return nil, verifyCodeErr
	}

	// 校验三要素
	verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
	if verifyErr != nil {
		return nil, verifyErr
	}

	// 缓存
	params := map[string]interface{}{
		"name":    data.Name,
		"id_card": data.IDCard,
		"mobile":  data.Mobile,
	}
	userID, err := l.GetOrCreateUser()
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
	}
	cacheNo, cacheDataErr := l.CacheData(params, "riskassessment", userID)
	if cacheDataErr != nil {
		return nil, cacheDataErr
	}
	l.recordQueryUserRecord(params, "riskassessment", userID, cacheNo)
	token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
	}

	// 获取当前时间戳
	now := time.Now().Unix()
	return &types.QueryServiceResp{
		Id:           cacheNo,
		AccessToken:  token,
		AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
		RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
	}, nil
}

// 处理公司信息查询相关逻辑
func (l *QueryServiceLogic) ProcessCompanyInfoLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
	// AES解密
	decryptData, DecryptDataErr := l.DecryptData(req.Data)
	if DecryptDataErr != nil {
		return nil, DecryptDataErr
	}

	// 校验参数
	var data types.CompanyInfoReq
	if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
	}

	if validatorErr := validator.Validate(data); validatorErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
	}

	// 校验验证码
	verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
	if verifyCodeErr != nil {
		return nil, verifyCodeErr
	}

	// 校验三要素
	verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
	if verifyErr != nil {
		return nil, verifyErr
	}

	// 缓存
	params := map[string]interface{}{
		"name":    data.Name,
		"id_card": data.IDCard,
		"mobile":  data.Mobile,
	}
	userID, err := l.GetOrCreateUser()
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
	}
	cacheNo, cacheDataErr := l.CacheData(params, "companyinfo", userID)
	if cacheDataErr != nil {
		return nil, cacheDataErr
	}
	l.recordQueryUserRecord(params, "companyinfo", userID, cacheNo)
	token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
	}

	// 获取当前时间戳
	now := time.Now().Unix()
	return &types.QueryServiceResp{
		Id:           cacheNo,
		AccessToken:  token,
		AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
		RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
	}, nil
}

// 处理租赁信息查询相关逻辑
func (l *QueryServiceLogic) ProcessRentalInfoLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {

	// AES解密
	decryptData, DecryptDataErr := l.DecryptData(req.Data)
	if DecryptDataErr != nil {
		return nil, DecryptDataErr
	}

	// 校验参数
	var data types.RentalInfoReq
	if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
	}

	if validatorErr := validator.Validate(data); validatorErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
	}

	// 校验验证码
	verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
	if verifyCodeErr != nil {
		return nil, verifyCodeErr
	}

	// 校验三要素
	verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
	if verifyErr != nil {
		return nil, verifyErr
	}

	// 缓存
	params := map[string]interface{}{
		"name":    data.Name,
		"id_card": data.IDCard,
		"mobile":  data.Mobile,
	}
	userID, err := l.GetOrCreateUser()
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
	}
	cacheNo, cacheDataErr := l.CacheData(params, "rentalinfo", userID)
	if cacheDataErr != nil {
		return nil, cacheDataErr
	}
	l.recordQueryUserRecord(params, "rentalinfo", userID, cacheNo)
	token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
	}

	// 获取当前时间戳
	now := time.Now().Unix()
	return &types.QueryServiceResp{
		Id:           cacheNo,
		AccessToken:  token,
		AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
		RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
	}, nil
}

// 处理贷前背景检查相关逻辑
func (l *QueryServiceLogic) ProcessPreLoanBackgroundCheckLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {

	// AES解密
	decryptData, DecryptDataErr := l.DecryptData(req.Data)
	if DecryptDataErr != nil {
		return nil, DecryptDataErr
	}

	// 校验参数
	var data types.PreLoanBackgroundCheckReq
	if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
	}

	if validatorErr := validator.Validate(data); validatorErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
	}

	// 校验验证码
	verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
	if verifyCodeErr != nil {
		return nil, verifyCodeErr
	}

	// 校验三要素
	verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
	if verifyErr != nil {
		return nil, verifyErr
	}

	// 缓存
	params := map[string]interface{}{
		"name":    data.Name,
		"id_card": data.IDCard,
		"mobile":  data.Mobile,
	}
	userID, err := l.GetOrCreateUser()
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
	}
	cacheNo, cacheDataErr := l.CacheData(params, "preloanbackgroundcheck", userID)
	if cacheDataErr != nil {
		return nil, cacheDataErr
	}
	l.recordQueryUserRecord(params, "preloanbackgroundcheck", userID, cacheNo)
	token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
	}

	// 获取当前时间戳
	now := time.Now().Unix()
	return &types.QueryServiceResp{
		Id:           cacheNo,
		AccessToken:  token,
		AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
		RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
	}, nil
}

// 处理人事背调相关逻辑
func (l *QueryServiceLogic) ProcessBackgroundCheckLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
	// AES解密
	decryptData, DecryptDataErr := l.DecryptData(req.Data)
	if DecryptDataErr != nil {
		return nil, DecryptDataErr
	}

	// 校验参数
	var data types.BackgroundCheckReq
	if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
	}

	if validatorErr := validator.Validate(data); validatorErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
	}

	// 校验验证码
	verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
	if verifyCodeErr != nil {
		return nil, verifyCodeErr
	}

	// 校验三要素
	verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
	if verifyErr != nil {
		return nil, verifyErr
	}

	// 缓存
	params := map[string]interface{}{
		"name":    data.Name,
		"id_card": data.IDCard,
		"mobile":  data.Mobile,
	}
	userID, err := l.GetOrCreateUser()
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
	}
	cacheNo, cacheDataErr := l.CacheData(params, "backgroundcheck", userID)
	if cacheDataErr != nil {
		return nil, cacheDataErr
	}
	l.recordQueryUserRecord(params, "backgroundcheck", userID, cacheNo)
	token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
	}

	// 获取当前时间戳
	now := time.Now().Unix()
	return &types.QueryServiceResp{
		Id:           cacheNo,
		AccessToken:  token,
		AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
		RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
	}, nil
}
func (l *QueryServiceLogic) ProcessPersonalDataLogic(req *types.QueryServiceReq) (*types.QueryServiceResp, error) {
	// AES解密
	decryptData, DecryptDataErr := l.DecryptData(req.Data)
	if DecryptDataErr != nil {
		return nil, DecryptDataErr
	}

	// 校验参数
	var data types.PersonalDataReq
	if unmarshalErr := json.Unmarshal(decryptData, &data); unmarshalErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 解密后的数据格式不正确: %+v", unmarshalErr)
	}

	if validatorErr := validator.Validate(data); validatorErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.PARAM_VERIFICATION_ERROR, validatorErr.Error()), "查询服务, 参数不正确: %+v", validatorErr)
	}

	// 校验验证码
	verifyCodeErr := l.VerifyCode(data.Mobile, data.Code)
	if verifyCodeErr != nil {
		return nil, verifyCodeErr
	}

	// 校验三要素
	verifyErr := l.Verify(data.Name, data.IDCard, data.Mobile)
	if verifyErr != nil {
		return nil, verifyErr
	}

	// 缓存
	params := map[string]interface{}{
		"name":    data.Name,
		"id_card": data.IDCard,
		"mobile":  data.Mobile,
	}
	userID, err := l.GetOrCreateUser()
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 处理用户失败: %v", err)
	}
	cacheNo, cacheDataErr := l.CacheData(params, "personalData", userID)
	if cacheDataErr != nil {
		return nil, cacheDataErr
	}
	l.recordQueryUserRecord(params, "personalData", userID, cacheNo)
	token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 生成token失败 : %d", userID)
	}

	// 获取当前时间戳
	now := time.Now().Unix()
	return &types.QueryServiceResp{
		Id:           cacheNo,
		AccessToken:  token,
		AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
		RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
	}, nil
}

func (l *QueryServiceLogic) DecryptData(data string) ([]byte, error) {
	secretKey := l.svcCtx.Config.Encrypt.SecretKey
	key, decodeErr := hex.DecodeString(secretKey)
	if decodeErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "密钥获取失败: %+v", decodeErr)
	}
	decryptData, aesDecryptErr := crypto.AesDecrypt(data, key)
	if aesDecryptErr != nil || len(decryptData) == 0 {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解密失败: %+v", aesDecryptErr)
	}
	return decryptData, nil
}

// 校验验证码
func (l *QueryServiceLogic) VerifyCode(mobile string, code string) error {
	// 开发环境下跳过验证码验证
	if os.Getenv("ENV") == "development" {
		return nil
	}
	secretKey := l.svcCtx.Config.Encrypt.SecretKey
	encryptedMobile, err := crypto.EncryptMobile(mobile, secretKey)
	if err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密手机号失败: %+v", err)
	}
	codeRedisKey := fmt.Sprintf("%s:%s", "query", encryptedMobile)
	cacheCode, err := l.svcCtx.Redis.Get(codeRedisKey)
	if err != nil {
		if errors.Is(err, redis.Nil) {
			return errors.Wrapf(xerr.NewErrMsg("验证码已过期"), "验证码过期: %s", mobile)
		}
		return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "读取验证码redis缓存失败, mobile: %s, err: %+v", mobile, err)
	}
	if cacheCode != code {
		return errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "验证码不正确: %s", mobile)
	}
	return nil
}

// 二、三要素验证
func (l *QueryServiceLogic) Verify(Name string, IDCard string, Mobile string) error {
	// 开发环境下跳过二/三要素验证（避免未授权IP调用天元API失败）
	isDevelopment := os.Getenv("ENV") == "development"
	if isDevelopment {
		return nil
	}

	if !l.svcCtx.Config.SystemConfig.ThreeVerify {
		twoVerification := service.TwoFactorVerificationRequest{
			Name:   Name,
			IDCard: IDCard,
		}
		verification, err := l.svcCtx.VerificationService.TwoFactorVerification(twoVerification)
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "二要素验证失败: %v", err)
		}
		if !verification.Passed {
			return errors.Wrapf(xerr.NewErrCodeMsg(xerr.SERVER_COMMON_ERROR, verification.Err.Error()), "二要素验证不通过: %v", err)
		}
	} else {
		// 三要素验证
		threeVerification := service.ThreeFactorVerificationRequest{
			Name:   Name,
			IDCard: IDCard,
			Mobile: Mobile,
		}
		verification, err := l.svcCtx.VerificationService.ThreeFactorVerification(threeVerification)
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "三要素验证失败: %v", err)
		}
		if !verification.Passed {
			return errors.Wrapf(xerr.NewErrCodeMsg(xerr.SERVER_COMMON_ERROR, verification.Err.Error()), "三要素验证不通过: %v", err)
		}
	}
	return nil
}

// 缓存
func (l *QueryServiceLogic) CacheData(params map[string]interface{}, Product string, userID int64) (string, error) {
	agentIdentifier, _ := l.ctx.Value("agentIdentifier").(string)
	secretKey := l.svcCtx.Config.Encrypt.SecretKey
	key, decodeErr := hex.DecodeString(secretKey)
	if decodeErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 获取AES密钥失败: %+v", decodeErr)
	}
	paramsMarshal, marshalErr := json.Marshal(params)
	if marshalErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 序列化参数失败: %+v", marshalErr)
	}
	encryptParams, aesEncryptErr := crypto.AesEncrypt(paramsMarshal, key)
	if aesEncryptErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 加密参数失败: %+v", aesEncryptErr)
	}
	queryCache := types.QueryCacheLoad{
		Params:          encryptParams,
		Product:         Product,
		AgentIdentifier: agentIdentifier,
	}
	jsonData, marshalErr := json.Marshal(queryCache)
	if marshalErr != nil {
		return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, 序列化参数失败: %+v", marshalErr)
	}
	outTradeNo := "Q_" + l.svcCtx.AlipayService.GenerateOutTradeNo()
	redisKey := fmt.Sprintf(types.QueryCacheKey, userID, outTradeNo)
	cacheErr := l.svcCtx.Redis.SetexCtx(l.ctx, redisKey, string(jsonData), int(2*time.Hour))
	if cacheErr != nil {
		return "", cacheErr
	}
	return outTradeNo, nil
}

// recordQueryUserRecord 写入查询用户记录表，用于通过姓名/身份证/手机号追溯订单
// 重要：name、id_card、mobile 必须以 AES-ECB+Base64 密文入库，禁止写入明文
func (l *QueryServiceLogic) recordQueryUserRecord(params map[string]interface{}, product string, userID int64, queryNo string) {
	getStr := func(k string) string {
		if v, ok := params[k]; ok {
			if s, ok := v.(string); ok {
				return s
			}
		}
		return ""
	}
	secretKey := l.svcCtx.Config.Encrypt.SecretKey
	if secretKey == "" {
		l.Errorf("查询用户记录表加密失败, Encrypt.SecretKey 未配置，拒绝写入明文 queryNo=%s", queryNo)
		return
	}
	key, keyErr := hex.DecodeString(secretKey)
	if keyErr != nil {
		l.Errorf("查询用户记录表加密失败, 密钥解析错误 queryNo=%s err=%v", queryNo, keyErr)
		return
	}
	// 以下三字段仅使用加密后的值赋值，不得使用 getStr 的明文
	encName := ""
	if name := getStr("name"); name != "" {
		if s, err := crypto.AesEcbEncrypt([]byte(name), key); err != nil {
			l.Errorf("查询用户记录表姓名加密失败 queryNo=%s err=%v", queryNo, err)
			return
		} else {
			encName = s
		}
	}
	encIdCard := ""
	if idCard := getStr("id_card"); idCard != "" {
		if s, err := crypto.EncryptIDCard(idCard, key); err != nil {
			l.Errorf("查询用户记录表身份证加密失败 queryNo=%s err=%v", queryNo, err)
			return
		} else {
			encIdCard = s
		}
	}
	encMobile := ""
	if mobile := getStr("mobile"); mobile != "" {
		if s, err := crypto.EncryptMobile(mobile, secretKey); err != nil {
			l.Errorf("查询用户记录表手机号加密失败 queryNo=%s err=%v", queryNo, err)
			return
		} else {
			encMobile = s
		}
	}
	agentIdentifier := sql.NullString{}
	if v, ok := l.ctx.Value("agentIdentifier").(string); ok && v != "" {
		agentIdentifier = sql.NullString{String: v, Valid: true}
	}
	// rec 的 Name、IdCard、Mobile 仅使用密文 encName、encIdCard、encMobile
	rec := &model.QueryUserRecord{
		UserId:          userID,
		Name:            encName,
		IdCard:          encIdCard,
		Mobile:          encMobile,
		Product:         product,
		QueryNo:         queryNo,
		OrderId:         0,
		PlatformOrderId: sql.NullString{},
		AgentIdentifier: agentIdentifier,
	}
	if _, err := l.svcCtx.QueryUserRecordModel.Insert(l.ctx, nil, rec); err != nil {
		l.Errorf("查询用户记录表写入失败 queryNo=%s err=%v", queryNo, err)
	}
}

// GetOrCreateUser 获取或创建用户
// 1. 如果上下文中已有用户ID，直接返回
// 2. 如果是代理查询或APP请求，创建新用户
// 3. 其他情况返回未登录错误
func (l *QueryServiceLogic) GetOrCreateUser() (int64, error) {
	// 尝试获取用户ID
	claims, err := ctxdata.GetClaimsFromCtx(l.ctx)
	if err != nil {
		return 0, err
	}
	userID := claims.UserId
	return userID, nil

	// // 如果不是未登录错误，说明是其他错误，直接返回
	// if !ctxdata.IsNoUserIdError(err) {
	// 	return 0, err
	// }

	// // 检查是否是代理查询或APP请求
	// isAgentQuery := false
	// if agentID, ok := l.ctx.Value("agentIdentifier").(string); ok && agentID != "" {
	// 	isAgentQuery = true
	// }
	// if app, ok := l.ctx.Value("app").(bool); ok && app {
	// 	isAgentQuery = true
	// }

	// // 如果不是代理查询或APP请求，返回未登录错误
	// if !isAgentQuery {
	// 	return 0, ctxdata.ErrNoUserIdInCtx
	// }

	// // 创建新用户
	// return l.svcCtx.UserService.RegisterUUIDUser(l.ctx)
}
