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 redis_help = require('../src/use_redis');
const config = require('../etc/config.json');
const other_book_controllers = require('../src/data_manager/Controllers/other_book_controllers');
const tools = require('../tools');
const helper = require('../src/helper');
const { default: axios } = require('axios');
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 findSameFilterData(product_list,FilterConfig) {
    for (let index = 0; index < product_list.length; index++) {
        const product_item = product_list[index];
        let result = await filter_data_controllers.getFilterDataByBookIdAndLimit({ book_id:product_item.product_id,status:0},500);
        if(result.success){
            if(result.data.length<=0){
                
            }else{
                let Ids = []
                let notNeedMaterial = []
                for (let j = 0; j < result.data.length; j++) {
                    let info  = result.data[j]
                    info.words = product_item.words
                    info.genre =  product_item.genre
                    info.book_id = product_item.product_id
                    info.book_name = product_item.product_name

                    let isGenre = CMD.isGenre(FilterConfig,info.genre)
                    if(isGenre){
                        Ids.push(info.id)
                    }else{
                        notNeedMaterial.push(info.id)
                    }
                }
                if(notNeedMaterial.length>0){
                    await filter_data_controllers.updateFilterDataByIds({ids:notNeedMaterial},{status:1,material_sync_status:2})
                }
              
                if(Ids.length>0){
                    await filter_data_controllers.updateFilterDataByIds({ids:Ids},{status:1})
                }

                await new Promise(resolve => setTimeout(resolve,100));
            }
        }
    }

}

async function updateSameProductId(list,product_item) {
    await filter_data_controllers.updateFilterDataByIds({ids:list},{status:1,book_id:product_item.book_id,book_name:product_item.book_name,genre:product_item.genre,words:product_item.words})
}

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_heiyan },1,"DESC");
        if(result.success){
            // let ProductIds = []
            // let FilterList = []
            // let UpdateProductList = []
            if(result.data.length<=0){
                throw '没有数据可处理！'
            }
            for (let index = 0; index < result.data.length; index++) {
                let filter_item = result.data[index];
                let product_info = await video_product_controllers.getProductData({book_id:filter_item.book_id});
                if(!product_info.success){
                    task_queue.push({result:{data:filter_item}})
                }else{
                    await filter_data_controllers.updateFilterData({id:filter_item.id},{status:1,book_id:filter_item.book_id,book_name:filter_item.book_name,genre:filter_item.genre,words:filter_item.words})
                }
                // ProductIds.push(filter_item.book_id)
                // FilterList[filter_item.book_id] = filter_item
                // if(UpdateProductList[filter_item.book_id]==null){
                //     UpdateProductList[filter_item.book_id]= []
                // }
                // UpdateProductList[filter_item.book_id].push(filter_item.id)
            }

            // let product_list_result = await video_product_controllers.findNonExistentProductIds(ProductIds);
            // if(product_list_result.success){
            //     let FinishProductList = []
            //     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)&&!FinishProductList[filter_item.book_id]){
            //             let info = filter_item;
            //             FinishProductList[filter_item.book_id] = true
            //             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
            //             info.book_platform = product_item.book_platform
            //             await CMD.update_filter_data(FilterConfig,info)
            //             await updateSameProductId(UpdateProductList[info.book_id],info)
            //             await new Promise(resolve => setTimeout(resolve,100));
            //         }
            //     }

            //     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]}})
            //         }
            //     }

            // }
            
        }
    }catch(e){
        console.error("processTask error:",e)
    } finally{
        global.setTimeout(processTask, 2000);
    }

}

async function processCreateTask(){
    let result = null
    try{
        if(task_queue.length>0){
            let task_queue_item = task_queue.pop()
            result = task_queue_item.result
            console.log("result:",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: 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_heiyan){
                    let hy_book_data = await require('./collect_hy_book').runTask(result.data)
                    if(hy_book_data!=null){
                        if(hy_book_data.is_c500){
                            hy_book_data.tg_platform_id = config.platform_heiyanmf
                        }
                        if(hy_book_data.genre==1){ //长篇给黑岩免费长篇添加进去
                            // await CMD.insert_product({
                            //     tg_platform_id:config.platform_heiyanmf,
                            //     book_name:hy_book_data.book_name,
                            //     genre:hy_book_data.genre,
                            //     book_id:hy_book_data.book_id,
                            //     words:hy_book_data.words
                            // })
                        }
                        await CMD.insert_product(hy_book_data)
                        result.data.words = hy_book_data.words
                        result.data.genre = hy_book_data.genre
                        result.data.book_id = hy_book_data.book_id
                        result.data.book_name = hy_book_data.book_name
                        result.data.book_platform = hy_book_data.tg_platform_id
                    }else{
                        result.data.words = 0
                        result.data.genre = 999
                        result.data.book_id = result.data.book_id
                        result.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
                result.data.book_platform = product.book_platform
            }
            await CMD.update_filter_data(FilterConfig,result.data)
        }
    }catch(e){
        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,isMf){
    let list = []
    for (let index = 0; index < MainConfig.length; index++) {
        const element = MainConfig[index];
        if(element.app_id==app_id){
            if(isMf){
                if(config.platform_heiyanmf==element.tg_platform_id){
                    list.push(element)
                }
            }else{
                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
        }
    }
    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,is_update_lib=true) {
    // let isGenre = CMD.isGenre(FilterConfig,data.genre)
    let isGenre = true
    let isMf = data.book_platform==config.platform_heiyanmf
    console.log("data.book_platform:",data.book_platform)
    if(isGenre){
        if(is_update_lib){
            if(data.genre==999){
                return  await filter_data_controllers.updateFilterData({id:data.id},{status:2,book_id:data.book_id,book_name:data.book_name,genre:data.genre,words:data.words})
            }else{
                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 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,isMf==true?config.platform_heiyanmf:config.platform_heiyan)

        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)
            // console.log("AppInfoList:",AppInfoList)
            for (let j = 0; j < AppInfoList.length; j++) {
                const AppInfo = AppInfoList[j];
                data.app_id = AppInfo.app_id

                let PlatformInfo = await redis_help.getKeyValue("PlatformConfig")

                PlatformInfo = JSON.parse(PlatformInfo)

                if(PlatformInfo==null){
                    return console.error("平台配置错误：",data)
                }

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

                MainConfig = JSON.parse(MainConfig)

                // console.log("list:",MainConfig,data.app_id,isMf)

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

                // console.log("list:",list,isMf,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 material_platform_id = main_info.material_platform_id
                        let min_book_word = main_info.min_book_word
                        let max_book_word = main_info.max_book_word
                        let word = data.words
                        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 table_data = {
                                        book_platform:config.platform_heiyan,
                                        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
                                    }
    
                                    if(main_info.pay_type==0){
                                        table_data.book_platform = config.platform_heiyan
                                        table_data.product_parent_id =  await CMD.get_product_parent_id(data.book_id)
                                    }


                                    // console.log("table_data:",table_data)
                                    //没有找到 可以创建
                                    await video_applet_product_controllers.createAppletProductData(table_data)
                                }
                            }
                        }
                    }
                }
            }
        }
        
    }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 bookIds = []
        bookIds.push(product_id)
        if(bookIds.length>0){
            let timestamp = helper.getCurrentUnixTimestamp()
            let sign = helper.generateSign({
                "pid":config.heiyan_config.pid,
                "timestamp":timestamp,
                "sign":"",
                "bookIds":bookIds.join(',')
            },config.heiyan_config.key)
            var url = config.heiyan_config.copyBooks
            var base_params = `/?sign=${sign}&pid=${config.heiyan_config.pid}&timestamp=${timestamp}`
            var other_params = `&bookIds=${bookIds.join(',')}`
            url = `${url}${base_params}${other_params}`
            // console.log("url:",url)
            let response = await axios.get(url)
            let data  = response.data
            if(data.code==1){
                let list = data.data
                let parent_id = ""
                console.log("get_hy_origin_books:",list)
                for (let index = 0; index < list.length; index++) {
                    const element = list[index];
                    parent_id = element.bookId
                    break
                }
                return parent_id
            }
        }
    }catch(e){
        console.error("get_product_parent_id err::",e)
        return ""
    }
    return ""

}

CMD.insert_product = async function(data){
    let product_parent_id =  await CMD.get_product_parent_id(data.book_id)
    if(product_parent_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_heiyan,
                product_name:data.book_name.substring(0, data.book_name.length - 4),
                genre:data.genre,
                product_id:product_parent_id,
                words:data.words
            })
            // console.log("免费：",data)
            await CMD.update_filter_data(null,{book_platform:config.platform_heiyan,book_id:product_parent_id,words:data.words,genre:data.genre,book_name:data.book_name.substring(0, data.book_name.length - 4)},false)
        }
    }
    await video_product_controllers.createProductData({
        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
    })
}


CMD.init()