const CMD = {}
const video_product_controllers = require('../src/data_manager/Controllers/video_product_controllers');
const filter_data_controllers = require('../src/data_manager/Controllers/filter_data_controllers');
const video_applet_product_controllers = require('../src/data_manager/Controllers/video_applet_product_controllers');
const other_book_controllers = require('../src/data_manager/Controllers/other_book_controllers');
const redis_help = require('../src/use_redis');
const config = require('../etc/config.json');
const mysql = require('mysql2/promise');
const tools = require('../tools');
const dbConfig = config.isDebug?config.debug_mysql:config.release_mysql
const taskdbConfig = config.isDebug?config.debug_task_mysql:config.release_task_mysql
const time_count = 1000;
const task_queue = []

function getProductById(product_list,product_id){
    for (let index = 0; index < product_list.length; index++) {
        const product_item = product_list[index];
        if(product_item.product_id==product_id){
            return product_item
        }
    }
    return null
}

async function processTask(){
    let result = null
    try{
        let isPauseTask =  await redis_help.getKeyValue("isPauseTask")
        if(isPauseTask=="true"){
            return
        }
        let FilterConfig = await redis_help.getKeyValue("FilterConfig")
        FilterConfig = JSON.parse(FilterConfig)
        result = await filter_data_controllers.getFilterDataByStatusAndLimit({ status: 0 , tg_platform_id: config.platform_qmmf },500,"DESC");
        if(result.success){
            let ProductIds = []
            let FilterList = []
            let Ids = []
            if(result.data.length<=0){
                throw '没有数据可处理！'
            }
            for (let index = 0; index < result.data.length; index++) {
                let filter_item = result.data[index];
                ProductIds.push(filter_item.book_id)
                FilterList[filter_item.book_id] = filter_item
            }

            let product_list_result = await video_product_controllers.findNonExistentProductIds(ProductIds);
            if(product_list_result.success){
                for (let index = 0; index < result.data.length; index++) {
                    let filter_item = result.data[index];
                    if(product_list_result.data.existingProductIds.has(filter_item.book_id)){
                        let info = filter_item;
                        let product_item = getProductById(product_list_result.data.existingRecords,filter_item.book_id)
                        if (!info) {
                            throw `No filter info found for book_id: ${filter_item.book_id}`
                        }
                        if (!product_item) {
                            throw `product_item is null: ${filter_item.book_id}`
                        }
                        info.words = product_item.words
                        info.genre =  product_item.genre
                        info.book_id = product_item.product_id
                        info.book_name = product_item.product_name
                        await CMD.update_filter_data(FilterConfig,info)
                        await new Promise(resolve => setTimeout(resolve,100));
                    } else{
                        Ids.push(filter_item.id)
                    }
                }

                let remove_product_list = []

                for (let index = 0; index < product_list_result.data.nonExistentIds.length; index++) {
                    const product_id = product_list_result.data.nonExistentIds[index];
                    if(remove_product_list[product_id]==true){
          
                    }else{
                        remove_product_list[product_id] = true
                        task_queue.push({result:{data:FilterList[product_id]}})
                    }
                }
                // if(Ids.length>0){
                //     console.log("Ids:",Ids)
                //     await filter_data_controllers.updateFilterDataByIds({ids:Ids},{status:1})
                // }
              
            }
            
        }
    }catch(e){
        console.error("processTask error:",e)
        // if(result!=null&&result!=undefined){
        //     await filter_data_controllers.updateFilterData({id:result.data.id},{status:2})
        // }
    } finally{
        global.setTimeout(processTask, 100);
    }

}

async function processCreateTask(){
    let result = null
    try{
        if(task_queue.length>0){
            let task_queue_item = task_queue.pop()
            result = task_queue_item.result
            let other_book = await other_book_controllers.getData({product_id:task_queue_item.result.data.book_id})
            if(other_book.success){
                await filter_data_controllers.updateFilterData({id:result.data.id},{status:2,book_id:other_book.data.product_id,book_name:other_book.data.product_name,material_sync_status:2})
                throw "处理了一条长篇或者筛选不要的书"
            }
            let product = await video_product_controllers.getProductData({ book_id: task_queue_item.result.data.book_id });
            let FilterConfig = await redis_help.getKeyValue("FilterConfig")
            FilterConfig = JSON.parse(FilterConfig)
            if(!product.success){
                let tg_platform_id = result.data.tg_platform_id
                if(tg_platform_id==config.platform_qmmf){ //七猫
                    let qm_book_data = await require('../src/api/qm_mf/qm_mf_search_book').search_id(result.data.book_id)
                    if(qm_book_data==null){
                        result.data.genre = 999
                    }else{
                        qm_book_data.tg_platform_id = result.data.tg_platform_id
                        // if(CMD.isGenre(FilterConfig,qm_book_data.genre)){
                        //     await CMD.insert_product(qm_book_data)
                        // }
                        await CMD.insert_product(qm_book_data)
                        result.data.words = qm_book_data.words
                        result.data.genre = qm_book_data.genre
                        result.data.book_id = qm_book_data.book_id
                        result.data.book_name = qm_book_data.book_name
                    }
                }
            }else{
                result.data.words = product.words
                result.data.genre = product.genre
                result.data.book_id = product.product_id
                result.data.book_name = product.product_name
            }
            await CMD.update_filter_data(FilterConfig,result.data)
        }
    }catch(e){
        console.log("error::",e)
        // if(result!=null){
        //     await filter_data_controllers.updateFilterData({id:result.data.id},{status:2})
        // }
        console.log("processCreateTask:",e)
    } finally{
        global.setTimeout(processCreateTask, time_count);
    }
}
CMD.init = async function(){
    redis_help.connect((results)=>{
        if(results){
        }
    })
    processTask();
    processCreateTask();
}

CMD.getAppInfoByPlatformId = function(AppConfig,tg_platform_id){
    let temp = []
    for (let index = 0; index < AppConfig.length; index++) {
        const element = AppConfig[index];
        if(element.tg_platform_id==tg_platform_id){
            temp.push(element)
        }
    }
    return temp
}
CMD.isBlackBook = function(all_black_books,book_id){
    if(all_black_books==null){
        return false
    }
    for (let index = 0; index < all_black_books.length; index++) {
        const black_book = all_black_books[index];
        if(black_book.product_id==book_id){
            return true
        }
    }
    return false
}
CMD.getMainInfoByAppid = function(MainConfig,app_id){
    let list = []
    for (let index = 0; index < MainConfig.length; index++) {
        const element = MainConfig[index];
        if(element.app_id==app_id){
            list.push(element)
        }
    }
    return list
}
CMD.isGenre = function(FilterConfig,genre){
    let is_need  = false
    // 判断长篇短篇是否是要的数据
    for (let index = 0; index < FilterConfig.genre.length; index++) {
        const element = FilterConfig.genre[index];
        if(genre==element){
            is_need = true
            break
        }
    }
    // if(genre==3||genre==1){
    //     return true
    // }
    return is_need
}

CMD.getPlatformInfo = function(PlatformConfig,tg_platform_id){
    for (let index = 0; index < PlatformConfig.length; index++) {
        const element = PlatformConfig[index];
        if(element.tg_platform_id==tg_platform_id){
            return element
        }
    }
}
CMD.getSharedPlatform = function(PlatformShared,platform_shared_id){
    for (let index = 0; index < PlatformShared.length; index++) {
        const element = PlatformShared[index];
        if(element.id==platform_shared_id){
            return JSON.parse(element.info)
        }
    }
}

CMD.update_filter_data = async function(FilterConfig,data) {
    // let isGenre = CMD.isGenre(FilterConfig,data.genre)
    let isGenre = true
    if(isGenre){
        console.log("data:",data)
        await filter_data_controllers.updateFilterData({id:data.id},{status:1,book_id:data.book_id,book_name:data.book_name,genre:data.genre,words:data.words})
        //创建一个小程序    

        let MainConfig = await redis_help.getKeyValue("MainConfig")

        MainConfig = JSON.parse(MainConfig)

        let AppConfig = await redis_help.getKeyValue("AppConfig")

        AppConfig = JSON.parse(AppConfig)

        let PlatformShared = await redis_help.getKeyValue("PlatformShared")

        PlatformShared = JSON.parse(PlatformShared)
        
        let PlatformConfig = await redis_help.getKeyValue("PlatformConfig")

        PlatformConfig = JSON.parse(PlatformConfig)

        let PlatformInfo = CMD.getPlatformInfo(PlatformConfig,config.platform_qmmf)


        let all_platform_list = CMD.getSharedPlatform(PlatformShared,PlatformInfo.platform_shared_id)


        for (let i = 0; i < all_platform_list.length; i++) {
            const tg_platform_id = all_platform_list[i];

            let AppInfoList = CMD.getAppInfoByPlatformId(AppConfig,tg_platform_id)


            for (let j = 0; j < AppInfoList.length; j++) {
                const AppInfo = AppInfoList[j];
                data.app_id = AppInfo.app_id

                let list = CMD.getMainInfoByAppid(MainConfig,data.app_id)

                if(list.length<0){
                    return console.error("获取主体错误：",data)
                }

                let black_books = await redis_help.getKeyValue("all_black_books")
                
                if(black_books!=null){
                    black_books = JSON.parse(black_books)
                }
        
                for (let index = 0; index < list.length; index++) {
                    const main_info = list[index];
                    data.main_id = main_info.id
                    data.main_name = main_info.main_name
                    let butler_id = main_info.butler_id
                    if(main_info.tg_link_config==undefined||main_info.tg_link_config==null){
                        console.error("主体配置推广链接错误：",main_info)
                    }else{
                        let mian_genre = main_info.genre
                        let book_genre = data.genre
                        let min_book_word = main_info.min_book_word
                        let max_book_word = main_info.max_book_word
                        let word = data.words
                        let material_platform_id = main_info.material_platform_id
                        if(!CMD.isBlackBook(black_books,data.book_id)&&word>=min_book_word&&word<=max_book_word){
                            //符合标准进行创建表
                            let butler_video_applet_info = await tools.getAppletProductDataByButlerId(butler_id,data.book_id,data.main_id)
                            if(butler_video_applet_info==null){
                                const result = await video_applet_product_controllers.getAppletProductData({book_id:data.book_id,main_id:data.main_id})
                                if(!result.success){
                                    let product_parent_id  =  await CMD.get_product_parent_id(data.book_id)
                                    //没有找到 可以创建
                                    await video_applet_product_controllers.createAppletProductData({
                                        book_platform:config.platform_qmmf,
                                        product_name:data.book_name,
                                        product_id:data.book_id,
                                        dy_small_program_start:"",
                                        dy_small_program_start_data:"",
                                        dy_small_applet_app_id:data.app_id,
                                        status:0,
                                        main_id:data.main_id,
                                        promotion_id:"",
                                        wait_status:0,
                                        material_platform_id:material_platform_id,
                                        butler_id:butler_id,
                                        product_parent_id: product_parent_id
                                    })
                                }
                            }
                        }
                    }
                }
            }
        }
    }else{
        await other_book_controllers.createData({product_id:data.book_id,product_name:data.book_name,tg_platform_id:data.tg_platform_id})
        await filter_data_controllers.updateFilterData({id:data.id},{status:2,book_id:data.book_id,book_name:data.book_name,genre:data.genre,material_sync_status:2})
    }
}

CMD.get_product_parent_id = async function(product_id) {
    try{
        let product_parent_id = product_id
        let iap_book_info = await CMD.getIAPInfo(product_id)
        if(iap_book_info!=null){
            product_parent_id = iap_book_info.book_id
        }
        return product_parent_id
    }catch(e){
        console.error("get_product_parent_id err::",e)
        return ""
    }
    return ""

}

CMD.insert_product = async function(data){

    //查找父id，如果找到就赋值，否则父id就是自己
    let product_parent_id = data.book_id
    let iap_book_info = await CMD.getIAPInfo(data.book_id)
    if(iap_book_info!=null){
        product_parent_id = iap_book_info.book_id
    }
    let table_data = {
        book_platform:data.tg_platform_id,
        product_name:data.book_name,
        genre:data.genre,
        product_id:data.book_id,
        words:data.words,
        product_parent_id:product_parent_id
    }

    if(product_parent_id!=data.book_id){
        //寻找父id的书
        let product_info = await video_product_controllers.getProductData({book_id:product_parent_id}); 
        if(!product_info.success){//如果没有这本付费的书
            await video_product_controllers.createProductData({
                book_platform:config.platform_qimao,
                product_name:data.book_name,
                genre:data.genre,
                product_id:product_parent_id,
                words:data.words
            })
        }
    }

    console.log("table_data:",table_data)
    return await video_product_controllers.createProductData(table_data)
}

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()