const config = require("./etc/config.json");
const helper = require("./src/helper");
const redis_help = require('./src/use_redis');
const mysql = require('mysql2/promise');
const tools = require("./tools");
const dbConfig = config.isDebug?config.debug_mysql:config.release_mysql
const CMD = {}
async function processTask(){
    let connection  = null
    let status = 0
    try{
        const today = helper.getLocalDate();
        let date = today.replace(/-/g, '');
        let table_name = `qm_iap_lib`;
        // 创建数据库连接
        connection = await mysql.createConnection({
            ...dbConfig,
            multipleStatements: true
        });

        // 检查表是否存在
        const [tableCheck] = await connection.execute(
            `SELECT TABLE_NAME 
            FROM information_schema.tables 
            WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`,
            [dbConfig.database, table_name]
        );

        if (tableCheck.length === 0) {
            // 表不存在
            console.error(`表 ${table_name} 不存在`);
            throw new Error(`表 ${table_name} 不存在`);
        } else {
            const [rows] = await connection.execute(
                `SELECT * FROM ${table_name} WHERE is_have_iaa = -1  LIMIT 100`
            );
    
            if(rows.length<=0){
                throw -1
            }
            for (let index = 0; index < rows.length; index++) {
                const element = rows[index];
                let iaa_book_info = await require('./src/api/qm_mf/qm_mf_search_book').search_name(element.book_author,element.book_origin_name)
                if(iaa_book_info!=null){
                    await connection.execute(
                        `UPDATE ${table_name} SET is_have_iaa = 1 , iaa_book_id = ${iaa_book_info.book_id}  WHERE book_id = ${element.book_id}`
                    );    
                }else{
                    await connection.execute(
                        `UPDATE ${table_name} SET is_have_iaa = 0  WHERE book_id = ${element.book_id}`
                    );        
                }
            }
        }
        
    }catch(e){
        if(e==-1){
            status = -1
        }
        console.error("processTask error:",e)
    } finally{
        if(status!=-1){
            global.setTimeout(processTask, 1000);
        }else{
            console.log("完成所有定义！")
        }
        if(connection!=null){
            await connection.end();
        }
    }

}


CMD.init = async function(){
    redis_help.connect((results)=>{
        if(results){
            processTask();
        }
    })

}

CMD.init()