package pay

import (
	"context"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"
	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-server/app/main/model"
	"qnc-server/common/ctxdata"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/crypto"

	"github.com/pkg/errors"
	"github.com/redis/go-redis/v9"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type PaymentLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}
type PaymentTypeResp struct {
	amount      float64
	outTradeNo  string
	description string
}

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

func (l *PaymentLogic) Payment(req *types.PaymentReq) (resp *types.PaymentResp, err error) {
	var paymentTypeResp *PaymentTypeResp
	var prepayData interface{}
	l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		switch req.PayType {
		case "agent_vip":
			paymentTypeResp, err = l.AgentVipOrderPayment(req, session)
			if err != nil {
				return err
			}

		case "query":
			paymentTypeResp, err = l.QueryOrderPayment(req, session)
			if err != nil {
				return err
			}
		}

		var createOrderErr error
		if req.PayMethod == "wechat" {
			prepayData, createOrderErr = l.svcCtx.WechatPayService.CreateWechatOrder(l.ctx, paymentTypeResp.amount, paymentTypeResp.description, paymentTypeResp.outTradeNo)
		} else if req.PayMethod == "alipay" {
			prepayData, createOrderErr = l.svcCtx.AlipayService.CreateAlipayOrder(l.ctx, paymentTypeResp.amount, paymentTypeResp.description, paymentTypeResp.outTradeNo)
		} else if req.PayMethod == "appleiap" {
			prepayData = l.svcCtx.ApplePayService.GetIappayAppID(paymentTypeResp.outTradeNo)
		}
		if createOrderErr != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 创建支付订单失败: %+v", createOrderErr)
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	switch v := prepayData.(type) {
	case string:
		// 如果 prepayData 是字符串类型，直接返回
		return &types.PaymentResp{PrepayId: v, OrderNo: paymentTypeResp.outTradeNo}, nil
	default:
		return &types.PaymentResp{PrepayData: prepayData, OrderNo: paymentTypeResp.outTradeNo}, nil
	}
}

func (l *PaymentLogic) QueryOrderPayment(req *types.PaymentReq, session sqlx.Session) (resp *PaymentTypeResp, err error) {
	userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
	if getUidErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取用户信息失败, %+v", getUidErr)
	}
	outTradeNo := req.Id
	redisKey := fmt.Sprintf(types.QueryCacheKey, userID, outTradeNo)
	cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey)
	if cacheErr != nil {
		if cacheErr == redis.Nil {
			return nil, errors.Wrapf(xerr.NewErrMsg("订单已过期"), "生成订单, 缓存不存在, %+v", cacheErr)
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取缓存失败, %+v", cacheErr)
	}
	var data types.QueryCacheLoad
	err = json.Unmarshal([]byte(cache), &data)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 解析缓存内容失败, %v", err)
	}

	product, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, data.Product)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 查找产品错误: %v", err)
	}

	var amount float64
	user, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取用户信息失败: %v", err)
	}

	if data.AgentIdentifier != "" {
		agentLinkModel, findAgentLinkErr := l.svcCtx.AgentLinkModel.FindOneByLinkIdentifier(l.ctx, data.AgentIdentifier)
		if findAgentLinkErr != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取代理订单失败: %+v", findAgentLinkErr)
		}
		amount = agentLinkModel.Price
	} else {
		amount = product.SellPrice
	}

	if user.Inside == 1 {
		amount = 0.01
	}
	var orderID int64
	Status := "pending"
	env := os.Getenv("ENV")
	if env == "" {
		env = "production"
	}
	if env == "development" {
		Status = "paid"
	}
	order := model.Order{
		OrderNo:         outTradeNo,
		UserId:          userID,
		ProductId:       product.Id,
		PaymentPlatform: req.PayMethod,
		PaymentScene:    "app",
		Amount:          amount,
		Status:          Status,
	}
	orderInsertResult, insertOrderErr := l.svcCtx.OrderModel.Insert(l.ctx, session, &order)
	if insertOrderErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存订单失败: %+v", insertOrderErr)
	}
	insertedOrderID, lastInsertIdErr := orderInsertResult.LastInsertId()
	if lastInsertIdErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取保存订单ID失败: %+v", lastInsertIdErr)
	}
	orderID = insertedOrderID

	if data.AgentIdentifier != "" {
		agent, parsingErr := l.agentParsing(data.AgentIdentifier)
		if parsingErr != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 解析代理标识符失败: %+v", parsingErr)
		}
		var agentOrder model.AgentOrder
		agentOrder.OrderId = orderID
		agentOrder.AgentId = agent.AgentID
		_, agentOrderInsert := l.svcCtx.AgentOrderModel.Insert(l.ctx, session, &agentOrder)
		if agentOrderInsert != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存代理订单失败: %+v", agentOrderInsert)
		}
	}

	if env == "development" {
		redisKey := fmt.Sprintf(types.QueryCacheKey, order.UserId, order.OrderNo)
		cache, cacheErr := l.svcCtx.Redis.Get(redisKey)
		if cacheErr != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取缓存内容失败: %+v", cacheErr)
		}
		var data types.QueryCacheLoad
		err = json.Unmarshal([]byte(cache), &data)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 解析缓存内容失败: %+v", err)
		}
		secretKey := l.svcCtx.Config.Encrypt.SecretKey
		key, decodeErr := hex.DecodeString(secretKey)
		if decodeErr != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取AES密钥失败: %+v", decodeErr)
		}
		decryptData, aesdecryptErr := crypto.AesDecrypt(data.Params, key)
		if aesdecryptErr != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 解密参数失败: %+v", aesdecryptErr)
		}
		var paramsMap map[string]string
		if err := json.Unmarshal([]byte(decryptData), &paramsMap); err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 解析参数失败: %+v", err)
		}

		encryptName, err := crypto.AesEncrypt([]byte(paramsMap["name"]), key)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 加密姓名失败: %+v", err)
		}
		encryptIdcard, err := crypto.AesEncrypt([]byte(paramsMap["id_card"]), key)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 加密身份证号失败: %+v", err)
		}
		_, err = l.svcCtx.AuthorizationModel.Insert(l.ctx, nil, &model.Authorization{
			OrderId:      orderID,
			UserId:       order.UserId,
			TargetName:   encryptName,
			TargetIdcard: encryptIdcard,
			Status:       model.AuthorizationStatusPending,
		})
		if err != nil {
			logx.Errorf("支付宝支付回调，插入授权信息失败: %+v", err)
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 插入授权信息失败: %+v", err)
		}
	}
	return &PaymentTypeResp{amount: amount, outTradeNo: outTradeNo, description: product.ProductName}, nil
}
func (l *PaymentLogic) AgentVipOrderPayment(req *types.PaymentReq, session sqlx.Session) (resp *PaymentTypeResp, err error) {
	userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
	if getUidErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取用户信息失败, %+v", getUidErr)
	}
	user, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取用户信息失败: %v", err)
	}
	// 查询用户代理信息
	agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败: %v", err)
	}
	redisKey := fmt.Sprintf(types.AgentVipCacheKey, userID, req.Id)
	cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey)
	if cacheErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取缓存失败, %+v", cacheErr)
	}
	var agentVipCache types.AgentVipCache
	err = json.Unmarshal([]byte(cache), &agentVipCache)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 解析缓存内容失败, %+v", err)
	}
	agentMembershipConfig, err := l.svcCtx.AgentMembershipConfigModel.FindOneByLevelName(l.ctx, agentVipCache.Type)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取代理会员配置失败, %+v", err)
	}

	amount := agentMembershipConfig.Price.Float64
	if user.Inside == 1 {
		amount = 0.01
	}
	agentMembershipRechargeOrder := model.AgentMembershipRechargeOrder{
		OrderNo:       req.Id,
		UserId:        userID,
		AgentId:       agentModel.Id,
		Amount:        amount,
		PaymentMethod: req.PayMethod,
		LevelName:     agentVipCache.Type,
		Status:        "pending",
	}
	_, err = l.svcCtx.AgentMembershipRechargeOrderModel.Insert(l.ctx, session, &agentMembershipRechargeOrder)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存代理会员充值订单失败: %+v", err)
	}
	return &PaymentTypeResp{amount: amount, outTradeNo: req.Id, description: fmt.Sprintf("%s代理会员充值", agentMembershipConfig.LevelName)}, nil
}
func (l *PaymentLogic) agentParsing(agentIdentifier string) (*types.AgentIdentifier, error) {
	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.AesDecryptURL(agentIdentifier, key)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务, %v", err)
	}
	var agentIdentifierStruct types.AgentIdentifier
	err = json.Unmarshal(encrypted, &agentIdentifierStruct)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询服务,反序列化失败 %v", err)
	}
	return &agentIdentifierStruct, nil
}
