const config = require("../etc/config.json");
const mysql = require('mysql2/promise');
const dbConfig = config.isDebug?config.debug_mysql:config.release_mysql
const taskdbConfig = config.isDebug?config.debug_task_mysql:config.release_task_mysql
const redis_help = require('../src/use_redis');
const CMD = {}
async function processTask(){
    let right_status = true
    let connection  = null
    try{
        connection = await mysql.createConnection({
            ...taskdbConfig,
            multipleStatements: true
        });

        //先获取所有没有父id的七猫免费书籍
        const [rows] = await connection.execute(
            `SELECT * FROM video_product WHERE book_platform = 19 AND product_parent_id ="" LIMIT 323`
        );

        if(rows.length<=0){
            throw 0
        }

        for (let index = 0; index < rows.length; index++) {
            let video_product_info = rows[index]
            let product_parent_id = video_product_info.product_id
            let iap_book_info = await CMD.getIAPInfo(video_product_info.product_id)
            if(iap_book_info!=null){
                product_parent_id = iap_book_info.book_id
            }
            await connection.execute(
                `UPDATE video_product SET product_parent_id = "${product_parent_id}" WHERE id = ${video_product_info.id} `
            );
        }


    }catch(e){
        if(e==0){
            right_status = false
        }
        console.error("processTask error:",e)
    } finally{
        if(right_status){
            // global.setTimeout(processTask, 1000);
        }

    }

}


CMD.getIAPInfo = async function(iaa_book_id){
    let connection = await mysql.createConnection({
        ...dbConfig,
        multipleStatements: true
    });

    const [rows] = await connection.execute(
        `SELECT * FROM qm_iap_lib WHERE iaa_book_id = ${iaa_book_id} AND is_have_iaa = 1  LIMIT 1`
    );
    await connection.end();
    
    if(rows.length<=0){
        return null
    }
    return rows[0]
}

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

}

CMD.init()