//将筛选已存在的书进行赋值
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 filter_data_controllers = require('../src/data_manager/Controllers/filter_data_controllers');
const helper = require("../src/helper");
const CMD = {}
async function processTask(){
    let right_status = true
    let connection  = null
    let task_connection = null
    let tg_platform_id = config.platform_fanqie
    try{
        //清理黑岩堆积数据
        //1.遍历书库
        //2.每一本书
        connection = await mysql.createConnection({
            ...dbConfig,
            multipleStatements: true
        });

      

        let sql = `SELECT * FROM filter_data WHERE tg_platform_id = ${tg_platform_id} AND status = 0 AND weight = 0 LIMIT 1`
        
        const [row] = await connection.execute(sql)


        if(row.length<=0){
            await connection.commit();
            throw 0
        }

        let filter_info = row[0]

        task_connection = await mysql.createConnection({
            ...taskdbConfig,
            multipleStatements: true
        });

        sql = `SELECT * FROM video_product WHERE product_id = "${filter_info.book_id}" AND (book_platform = 1 OR book_platform = 18) LIMIT 1`
        
        const [row1] = await task_connection.execute(sql)

        if(row1.length<=0){
            connection.execute(`UPDATE filter_data SET weight = 999 WHERE id = ${filter_info.id}`)
            throw 999
        }

        let video_product_row = row1[0]

        sql = `UPDATE filter_data SET status = 1 , book_name = "${video_product_row.product_name}" , genre = ${video_product_row.genre} ,words = "${video_product_row.words}" WHERE book_id = "${video_product_row.product_id}" AND status = 0 AND tg_platform_id = ${config.platform_heiyan} `

        console.log("processTask:",video_product_row)

        await connection.execute(
            sql
        );

        await connection.commit();
    }catch(e){
        if(e==0){
            right_status = false
        }
        console.error("processTask error:",e)
    } finally{

        if(connection!=null){
            connection.end()
        }

        if(task_connection!=null){
            task_connection.end()
        }

        if(right_status){
            global.setTimeout(processTask, 1000);
        }

    }

}

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

}

CMD.init()