const fetch = require('node-fetch'); // Node.js 18以下版本需要安装 node-fetch
const tools = require('../../../tools');
const helper = require('../../helper');
const mysql = require('mysql2/promise');
const config = require("../../../etc/config.json");
const dbConfig = config.isDebug?config.debug_mysql:config.release_mysql
const CMD = {}
const crypto = require('crypto')
const { format } = require('date-fns');
CMD.search_id = async function (bookId) {
    // const url = 'https://new-media-fx.qimao.com/api/content/book/list';
    let connection  = null
    try{
        connection = await mysql.createConnection({
                ...dbConfig,
                multipleStatements: true
            });
        let sql = `SELECT * FROM book_info WHERE id = ${bookId} LIMIT 1`
        const [rows] = await connection.execute(
            sql
        );

        if(rows.length<=0){
            throw 0
        }
        let book_info = rows[0]
        let info = {}
        info.words =  Math.floor(parseFloat(book_info.wordCount)*10000)
        info.book_name =  book_info.title
        info.book_id =  book_info.id
        info.publish_time = book_info.addTime
        if(book_info.type="短篇"){
            info.genre = 3;
        }else{
            info.genre = 1;
        }
        return info;

    }catch(e){
        console.error(e)
        return null
    }finally{
        if(connection!=null){
            connection.end()
        }
    }
    // return await makeRequest(bookId);
    // // 请求参数
    // const params = new URLSearchParams({
    //     book_id: bookId,
    //     page: '1',
    //     page_size: '50',
    //     env: '',
    //     // t: Date.now()  // 当前时间戳
    //     t:"1746001071923"
    // });

    // // 请求头
    // var headers = {
    //     "accept": "application/json, text/plain, */*",
    //     "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
    //     "app-external-id": "14f237fdbb7711ef93f90293e6ac97a2",
    //     "authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SUQiOjU0NDA1NjQxNjM3MTI4MjExMSwiQWNjb3VudE5hbWUiOiJ6aHVveXVlIiwiVGltZVN0YW1wIjoxNzQ2MDAwOTcyLCJDbGllbnRJUCI6IjEyMS4zMy4yMTcuMjE4IiwiQnVmZmVyVGltZSI6MCwiZXhwIjoxNzQ2MDg3MzcyLCJpc3MiOiJxbV9uZXdfbWVkaWFfZngiLCJuYmYiOjE3NDYwMDA5NzIsIkVudiI6InJlbGVhc2UiLCJJc1NpbXVsYXRpb25Mb2dpbiI6ZmFsc2V9.r4Heb9qmhrpSvDQW5QiTi1dVW_hyX_JKoyenpEnUMDg",
    //     "project": "reader_paid_dyminiapp",
    //     "sec-ch-ua": "\"Microsoft Edge\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
    //     "sec-ch-ua-mobile": "?1",
    //     "sec-ch-ua-platform": "\"Android\"",
    //     "sec-fetch-dest": "empty",
    //     "sec-fetch-mode": "cors",
    //     "sec-fetch-site": "same-origin",
    //     "signature": "01b4982bffb69237587a38de6428cce9e1948cce3517c357bd136aa66cfd192b",
    //     "target-id": "549124667291906201",
    //     "cookie": "sensorsdata2015jssdkcross=%7B%22%24device_id%22%3A%22193bdc124645e2-0cbeaee172d4ce8-4c657b58-921600-193bdc12465567%22%7D; sa_jssdk_2015_new-media-fx_qimao_com=%7B%22distinct_id%22%3A%22193bdc124645e2-0cbeaee172d4ce8-4c657b58-921600-193bdc12465567%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E5%BC%95%E8%8D%90%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%2C%22%24latest_referrer%22%3A%22http%3A%2F%2F120.79.128.142%3A4999%2F%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTkzYmRjMTI0NjQ1ZTItMGNiZWFlZTE3MmQ0Y2U4LTRjNjU3YjU4LTkyMTYwMC0xOTNiZGMxMjQ2NTU2NyJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%7D; acw_tc=ac11000117460009692805554e0074ec3c1591025be468ce51e9071843da7f",
    //     "Referer": "https://new-media-fx.qimao.com/backend/book-manage/index?projectId=reader_paid_dyminiapp&appId=14f237fdbb7711ef93f90293e6ac97a2&accountId=549124667291906201",
    //     "Referrer-Policy": "strict-origin-when-cross-origin"
    // };

    // // headers['authorization'] = await tools.getQMToken()
    // try {
    //     const response = await fetch(`${url}?${params}`, {
    //         method: 'GET',
    //         headers: headers
    //     });

    //     const data = await response.json();
    //     if(data.code!=200){
    //         throw data
    //     }
    //     // console.log('响应状态:', response.status);
    //     // console.log('响应数据:', data.data.list[0]);
    //     if(data.data.list.length<=0){
    //         return null
    //     }
    //     let book_info = data.data.list[0]
    //     let info = {}
    //     info.words =  Math.floor(parseFloat(book_info.book_word_count)*10000)
    //     info.book_name =  book_info.book_name
    //     info.book_id =  book_info.book_id
    //     info.genre = 999;
    //     if(book_info.book_type==2){  //七猫只有长或者短
    //         info.genre = 3;
    //     }else{
    //         info.genre = 1;
    //     }
    //     return info;
    // } catch (error) {
    //     console.log(error)
    //     return null
    // }
}



CMD.search_id_new = async function(book_id) {
    let client = tools.getOneNewClinet()
    let uuid = tools.generateCryptoNumericUUID()
    let timestamp = helper.getCurrentUnixTimestamp()
    const baseUrl = "https://new-media-mapi.qimao.com/mapi/v1/book-info";
    const params = {
        access_key: config.qimao_config.access_key,
        admin_account_name:"zhuoyue",
        book_id:book_id,
        random: uuid,
        timestamp: timestamp,
    };


    const sortedParams = Object.keys(params)
    .sort()
    .map(key => `${key}=${params[key]}`)
    .join('&');

    const secretKey = config.qimao_config.secret_key;

    const sign = crypto.createHash('md5')
            .update(sortedParams + secretKey)
            .digest('hex');
    const finalUrl = `${baseUrl}?${sortedParams}&sign=${sign}`;

    console.log("finalUrl:",finalUrl)
    try{
        let response =  await client.get(finalUrl)
        console.log("response:",response.data)
        if(response.data.code!=0){
            throw response.data
        }
        let book_info = response.data.data.book
        let info = {}
        info.words =  book_info.word_count
        info.book_name =  book_info.name
        info.book_id =  book_info.id
        info.genre = 999;
        info.publish_time = format(new Date(book_info.create_time*1000), 'yyyy-MM-dd HH:mm:ss')
        if(book_info.type==2){  //七猫只有长或者短
            info.genre = 3;
        }else{
            info.genre = 1;
        }
        return info;
    }catch(e){
        console.log(e)
        return null
    }

    return
    const url = `https://new-media-fx.qimao.com/api/content/book/list?book_id=${book_id}&page=1&page_size=50&env=&t=1746001846107`;
    
    const headers = {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "app-external-id": "14f237fdbb7711ef93f90293e6ac97a2",
        "authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SUQiOjU0NDA1NjQxNjM3MTI4MjExMSwiQWNjb3VudE5hbWUiOiJ6aHVveXVlIiwiVGltZVN0YW1wIjoxNzQ2MDAwOTcyLCJDbGllbnRJUCI6IjEyMS4zMy4yMTcuMjE4IiwiQnVmZmVyVGltZSI6MCwiZXhwIjoxNzQ2MDg3MzcyLCJpc3MiOiJxbV9uZXdfbWVkaWFfZngiLCJuYmYiOjE3NDYwMDA5NzIsIkVudiI6InJlbGVhc2UiLCJJc1NpbXVsYXRpb25Mb2dpbiI6ZmFsc2V9.r4Heb9qmhrpSvDQW5QiTi1dVW_hyX_JKoyenpEnUMDg",
        "project": "reader_paid_dyminiapp",
        "sec-ch-ua": "\"Microsoft Edge\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
        "sec-ch-ua-mobile": "?1",
        "sec-ch-ua-platform": "\"Android\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "signature": "66cd5f564e85598c73adabf398496dff8268da075658e6feab4fe3cfe76e438a",
        "target-id": "549124667291906201",
        "cookie": "sensorsdata2015jssdkcross=%7B%22%24device_id%22%3A%22193bdc124645e2-0cbeaee172d4ce8-4c657b58-921600-193bdc12465567%22%7D; sa_jssdk_2015_new-media-fx_qimao_com=%7B%22distinct_id%22%3A%22193bdc124645e2-0cbeaee172d4ce8-4c657b58-921600-193bdc12465567%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E5%BC%95%E8%8D%90%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%2C%22%24latest_referrer%22%3A%22http%3A%2F%2F120.79.128.142%3A4999%2F%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTkzYmRjMTI0NjQ1ZTItMGNiZWFlZTE3MmQ0Y2U4LTRjNjU3YjU4LTkyMTYwMC0xOTNiZGMxMjQ2NTU2NyJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%7D; acw_tc=ac11000117460009692805554e0074ec3c1591025be468ce51e9071843da7f",
        "Referer": "https://new-media-fx.qimao.com/backend/book-manage/index?projectId=reader_paid_dyminiapp&appId=14f237fdbb7711ef93f90293e6ac97a2&accountId=549124667291906201"
    };

    try {
        const response = await fetch(url, {
            method: 'GET',
            headers: headers
        });

        const data = await response.json();
        if(data.code!=200){
            throw data
        }
        // console.log('响应状态:', response.status);
        // console.log('响应数据:', data.data.list[0]);
        if(data.data.list.length<=0){
            return null
        }
        let book_info = data.data.list[0]
        let info = {}
        info.words =  Math.floor(parseFloat(book_info.book_word_count)*10000)
        info.book_name =  book_info.book_name
        info.book_id =  book_info.book_id
        info.genre = 999;
        info.publish_time = book_info.create_time
        if(book_info.book_type==2){  //七猫只有长或者短
            info.genre = 3;
        }else{
            info.genre = 1;
        }
        return info;
    } catch (error) {
        console.log(error)
        return null
    }
}

// 执行请求
// Node.js 18及以上版本可以直接运行
// Node.js 18以下版本需要先安装 node-fetch:
// npm install node-fetch@2

module.exports = CMD;