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 = {}
CMD.search_id = async function (bookId) {
    let connection  = null
    try{
        connection = await mysql.createConnection({
                ...dbConfig,
                multipleStatements: true
            });
        let sql = `SELECT * FROM book_iaa_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()
        }
    }
    // const url = 'https://new-media-iaa-fx.qimao.com/api/content/book/list';
    
    // // 请求参数
    // const params = new URLSearchParams({
    //     book_id: bookId,
    //     page: '1',
    //     page_size: '50',
    //     env: '',
    //     t: Date.now()  // 当前时间戳
    // });

    // // 请求头
    // var headers = {
    //     'accept': 'application/json, text/plain, */*',
    //     "app-id": "ttaeafd812319b128201",
    //     'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SUQiOjU1NzcwMjIxODI2MzQ0OTYxMSwiQWNjb3VudE5hbWUiOiJ6aHVveXVlIiwiVGltZVN0YW1wIjoxNzQyMjgwNDU1LCJDbGllbnRJUCI6IjIxOS4xMzYuMTMwLjEwNyIsIkJ1ZmZlclRpbWUiOjAsImV4cCI6MTc0MjM2Njg1NSwiaXNzIjoicW1fbmV3X21lZGlhX2Z4IiwibmJmIjoxNzQyMjgwNDU1LCJFbnYiOiJyZWxlYXNlIiwiSXNTaW11bGF0aW9uTG9naW4iOmZhbHNlfQ.nUn5QkVnC-oQ6qwjc8Bh5jRTsTKqwzPS5cphBIiaBvU',
    //     'project': 'reader_free_dyminiapp',
    //     'signature': '27f1c6bd848f65d15f3454b05872b789b1b8357f16ea2d2aead044780d371e11',
    //     'target-id': '558102575356793781'
    // };

    // headers['authorization'] = await tools.getQMMFToken()
    // 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]
    //     console.error("data:",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) {
    //     return null
    // }
}

CMD.search_name = async function (book_author,origin_book_name) {
    const url = 'https://new-media-iaa-fx.qimao.com/api/content/book/list';
    
    // 请求参数
    const params = new URLSearchParams({
        book_author: book_author,
        book_name:origin_book_name,
        page: '1',
        page_size: '50',
        env: '',
        t: Date.now()  // 当前时间戳
    });

    // 请求头
    var headers = {
        'accept': 'application/json, text/plain, */*',
        "app-id": "ttaeafd812319b128201",
        'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SUQiOjU1NzcwMjIxODI2MzQ0OTYxMSwiQWNjb3VudE5hbWUiOiJ6aHVveXVlIiwiVGltZVN0YW1wIjoxNzQyMjgwNDU1LCJDbGllbnRJUCI6IjIxOS4xMzYuMTMwLjEwNyIsIkJ1ZmZlclRpbWUiOjAsImV4cCI6MTc0MjM2Njg1NSwiaXNzIjoicW1fbmV3X21lZGlhX2Z4IiwibmJmIjoxNzQyMjgwNDU1LCJFbnYiOiJyZWxlYXNlIiwiSXNTaW11bGF0aW9uTG9naW4iOmZhbHNlfQ.nUn5QkVnC-oQ6qwjc8Bh5jRTsTKqwzPS5cphBIiaBvU',
        'project': 'reader_free_dyminiapp',
        'signature': '27f1c6bd848f65d15f3454b05872b789b1b8357f16ea2d2aead044780d371e11',
        'target-id': '558102575356793781'
    };

    headers['authorization'] = await tools.getQMMFToken()
    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){
            throw -1
        }
        let book_info = data.data.list[0]
        console.error("data:",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) {
        if(error==-1){ //这本书没有iaa对应
            console.error("这本书没有iaa对应")
        }
        return null
    }
}
// Node.js 18及以上版本可以直接运行
// Node.js 18以下版本需要先安装 node-fetch:
// npm install node-fetch@2

module.exports = CMD;