"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MEMBER_PRICES = void 0;
exports.getMemberBenefits = getMemberBenefits;
exports.getMemberStatus = getMemberStatus;
exports.createOrder = createOrder;
exports.mockPaymentSuccess = mockPaymentSuccess;
exports.getOrders = getOrders;
const models_1 = require("../../models");
const types_1 = require("../../types");
// 会员价格
exports.MEMBER_PRICES = {
    monthly: { price: 19.9, days: 30 },
    yearly: { price: 199, days: 365 },
};
// 获取会员权益信息
function getMemberBenefits() {
    return {
        levels: [
            {
                level: 0,
                name: '免费版',
                price: 0,
                quota: types_1.MEMBER_QUOTA[0],
                features: ['每天3次生成', '每次最多5000字', '基础音色'],
            },
            {
                level: 1,
                name: '月度会员',
                price: exports.MEMBER_PRICES.monthly.price,
                quota: types_1.MEMBER_QUOTA[1],
                features: ['每天20次生成', '每次最多50000字', '全部音色', '优先处理'],
            },
            {
                level: 2,
                name: '年度会员',
                price: exports.MEMBER_PRICES.yearly.price,
                quota: types_1.MEMBER_QUOTA[2],
                features: ['无限次生成', '无字数限制', '全部音色', '优先处理', '专属客服'],
            },
        ],
    };
}
// 获取用户会员状态
async function getMemberStatus(userId) {
    const user = await models_1.prisma.user.findUnique({ where: { id: parseInt(userId) } });
    if (!user) {
        throw new Error('用户不存在');
    }
    const today = new Date().toISOString().slice(0, 10);
    let dailyUsage = user.dailyUsage;
    const memberLevel = user.memberLevel;
    const quota = types_1.MEMBER_QUOTA[memberLevel];
    // 重置每日使用次数
    if (user.lastUsageDate !== today) {
        dailyUsage = 0;
    }
    const isValid = memberLevel > 0 && user.memberExpireAt && new Date() < user.memberExpireAt;
    return {
        level: memberLevel,
        levelName: ['免费版', '月度会员', '年度会员'][memberLevel],
        expireAt: user.memberExpireAt,
        isValid,
        quota: {
            dailyLimit: quota.dailyLimit,
            dailyUsed: dailyUsage,
            dailyRemaining: quota.dailyLimit === -1 ? -1 : Math.max(0, quota.dailyLimit - dailyUsage),
            wordLimit: quota.wordLimit,
        },
    };
}
// 创建订单
async function createOrder(userId, productType) {
    const priceInfo = exports.MEMBER_PRICES[productType];
    const orderNo = generateOrderNo();
    const order = await models_1.prisma.order.create({
        data: {
            userId: parseInt(userId),
            orderNo,
            productType,
            amount: priceInfo.price,
            status: 'pending',
        },
    });
    return {
        orderNo: order.orderNo,
        amount: Number(order.amount),
    };
}
// 模拟支付成功
async function mockPaymentSuccess(orderNo, userId) {
    const order = await models_1.prisma.order.findFirst({
        where: { orderNo, userId: parseInt(userId) }
    });
    if (!order) {
        throw new Error('订单不存在');
    }
    if (order.status !== 'pending') {
        throw new Error('订单状态不正确');
    }
    // 更新订单状态
    await models_1.prisma.order.update({
        where: { id: order.id },
        data: {
            status: 'paid',
            paymentMethod: 'mock',
            paidAt: new Date(),
        },
    });
    // 更新用户会员状态
    const user = await models_1.prisma.user.findUnique({ where: { id: parseInt(userId) } });
    if (!user) {
        throw new Error('用户不存在');
    }
    const days = exports.MEMBER_PRICES[order.productType].days;
    const now = new Date();
    // 如果当前是会员，从到期日延长；否则从现在开始
    const startDate = user.memberExpireAt && user.memberExpireAt > now
        ? user.memberExpireAt
        : now;
    const memberLevel = order.productType === 'yearly' ? 2 : 1;
    const memberExpireAt = new Date(startDate.getTime() + days * 24 * 60 * 60 * 1000);
    await models_1.prisma.user.update({
        where: { id: parseInt(userId) },
        data: {
            memberLevel,
            memberExpireAt,
        },
    });
    return {
        success: true,
        memberLevel,
        memberExpireAt,
    };
}
// 获取订单列表
async function getOrders(userId, page = 1, pageSize = 10) {
    const uid = parseInt(userId);
    const total = await models_1.prisma.order.count({ where: { userId: uid } });
    const list = await models_1.prisma.order.findMany({
        where: { userId: uid },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
    });
    return {
        list,
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize),
    };
}
// 生成订单号
function generateOrderNo() {
    const now = new Date();
    const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '');
    const random = Math.random().toString(36).substring(2, 8).toUpperCase();
    return `ORD${dateStr}${random}`;
}
