const crypto = require('crypto');

function generateSignature(params) {
    // 1. 按照参数名ASCII码从小到大排序
    const sortedParams = {};
    Object.keys(params)
        .sort()
        .forEach(key => {
            if (params[key] !== undefined && params[key] !== null) {
                sortedParams[key] = params[key];
            }
        });

    // 2. 将参数格式化为 key=value 的形式并用 & 连接
    const paramString = Object.entries(sortedParams)
        .map(([key, value]) => `${key}=${value}`)
        .join('&');

    // 添加特定的密钥或salt（这是关键部分，需要根据实际情况调整）
    const secretKey = 'qimao_iap_miniapp';  // 这里使用推测的密钥
    const stringToHash = paramString + secretKey;

    // 3. 使用SHA256生成签名
    const signature = crypto
        .createHash('sha256')
        .update(stringToHash)
        .digest('hex');

    return { signature, paramString, stringToHash };
}

async function fetchBookData() {
    const params = {
        book_id: "396740",
        page: "1",
        page_size: "50",
        env: "",
        t: "1746001846107"
    };

    const { signature, paramString, stringToHash } = generateSignature(params);

    console.log('Parameters String:', paramString);
    console.log('String to Hash:', stringToHash);
    console.log('Generated Signature:', signature);

    try {
        const queryString = paramString;
        const url = `https://new-media-fx.qimao.com/api/book/data?${queryString}`;

        const response = await fetch(url, {
            method: 'GET',
            headers: {
                "accept": "application/json, text/plain, */*",
                "app-external-id": "9a2737aabb8f11ef93f90293e6ac97a2",
                "authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", // 你的实际token
                "project": "reader_paid_wxminiapp",
                "signature": signature,
                "target-id": ""
            }
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error:', error);
        throw error;
    }
}

// 测试签名生成
const testParams = {
    book_id: "396740",
    page: "1",
    page_size: "50",
    env: "",
    t: "1746001846107"
};

// 生成签名并验证
const result = generateSignature(testParams);
console.log('Final Generated Signature:', result.signature);

// 与目标签名对比
const targetSignature = "66cd5f564e85598c73adabf398496dff8268da075658e6feab4fe3cfe76e438a";
console.log('Target Signature:', targetSignature);
console.log('Signatures Match:', result.signature === targetSignature);

// 使用方法
fetchBookData()
    .then(result => {
        console.log('API Response:', result);
    })
    .catch(error => {
        console.error('API Error:', error);
    });