const origin_data_controllers = require('../src/data_manager/Controllers/origin_data_controllers');
const helper = require('../src/helper');
const redis_help = require('../src/use_redis');
let tsak_list = []
let count_num = 0
async function processTask(){
    try{
        let isNeedDelete = true
        if(tsak_list.length>0){
            let FilterConfig = await redis_help.getKeyValue("FilterConfig")
            FilterConfig = JSON.parse(FilterConfig)
            let data = tsak_list.shift()
            let d =  filter_and_insert(data,FilterConfig)
            if(d==null){
            }else{
                if(d.channel=="七猫"){
                    // console.log("七猫书id：",d.book_id)
                    isNeedDelete = false
                }else if(d.channel=="点众"){
                    isNeedDelete = false
                    // console.log("点众id：",d.book_id)
                }
            }
            if(isNeedDelete){
                await origin_data_controllers.updateOriginData({id:data.id},{
                    status:3
                })
            }else{
                await origin_data_controllers.updateOriginData({id:data.id},{
                    status:4
                })
            }
        }else{
        }
    
    }catch(e){

    }finally{
        if(tsak_list.length>0){
            setTimeout(processTask,100);
        }else{
            setTimeout(get_500_data,1000);
        }

    }
    // const result = await origin_data_controllers.getOriginDataByStatus({status:1})
    // if(result.success){
    //     let FilterConfig = await redis_help.getKeyValue("FilterConfig")
    //     FilterConfig = JSON.parse(FilterConfig)
    //     let d =  filter_and_insert(result.data,FilterConfig)
    //     if(d==null){
    //         setTimeout(processTask,1000);
    //     }else{
    //         if(d.channel=="七猫"){
    //             console.log("七猫书id：",d.book_id)
    //         }else if(d.channel=="点众"){
    //             console.log("点众id：",d.book_id)
    //         }else{
    //             console.log("result:",result.data)
    //         }
    //     }
    //     origin_data_controllers.updateOriginData({id:result.data.id},{
    //         status:3
    //     })
    //     setTimeout(processTask,1000);
    // }
}
let get_500_data = async function(){

    count_num+=1;

    const result = await origin_data_controllers.findByDateRange({status:1},'create_time','2024-12-17 00:00:00','2024-12-18 00:00:00',500)
    
    if(result.success){
        if(result.data.length>0){
            console.log("当前页数：",count_num)
            tsak_list = result.data
            // console.log("tsak_list:",tsak_list)
            processTask()
        }else{
            console.log("over 没有数据了！")
        }

    }
   
}

function filter_and_insert(origin_data,tg_config){

    if(origin_data.guajian_link.length<=0){
        return null
    }

    let obj = parsePromotion(origin_data.guajian_link,tg_config.source_filter,tg_config.platform_select)
    // console.log("obj::",obj)
    if(obj==null){
        // console.log("xml[挂件地址] error 2:",obj)
        return null
    }
    let tg_platform_id = 0
    if(obj.channel=="七猫"){
        tg_platform_id = 3
        obj.book_id = obj.id
    }else if(obj.channel=="点众"){
        tg_platform_id = 4
        obj.book_id = obj.book_id
    }
    // console.log("评论数正确")
    return {video_id:origin_data.video_id,book_id:obj.book_id,channel:obj.channel,source:obj.source,key:obj.key,video_link:origin_data.video_link,
        like_num:origin_data.like_num,kepp_num:origin_data.kepp_num ,shared_num:origin_data.shared_num,comment_num:origin_data.comment_num,tg_platform_id:tg_platform_id}
}


//解析挂件
function parsePromotion(promotion,source_list,platform_select){
    let list = promotion.split('&')
    if(list.length!=undefined){
        if(list.length>2){
            let params = {}
            for (let index = 0; index < list.length; index++) {
                const element = list[index];
                let obj = parsePromotionItem(element)
                if(obj!=null){
                    if(obj.key=="start_page"&&obj.bookId!=null&&obj.bookId!=undefined){
                        params['bookId'] = obj.bookId
                    }
                    params[obj.key] = obj.value
                }
            }
            let channel = getChannel(params['start_page'],platform_select,promotion)
            // console.log("source_list:",source_list,platform_select,channel)
            if(channel!=null){
                let item_info = {}
                item_info['book_id'] = params['bookId'];
                item_info['channel'] = channel;
                item_info['id'] = params['id']

                const str = params['x-signature']
                const regex = /"name":"([^"]+)"/;
                const match = str.match(regex);
                let source = ''
                if (match && match[1]) {
                    source = match[1]
                }
                for (let j = 0; j < source_list.length; j++) {
                    const source_item = source_list[j];
                    if(source_item==source){
                        return null
                    }
                }
                item_info['source'] = source;
                item_info['key'] = params['key']
                return item_info
            }
            return null
        }else{
            return null
        }
    }else{
        return null
    }
}

function getChannel(start_page,platform_select,promotion){
    // console.log("start_page:",start_page)
    if(start_page=="pages/reader/index?bookId"){ //点众
        return "点众"
    }else if(helper.checkChannel(promotion,'&channel=rd')){ //七猫
        return "七猫"
    }else if(start_page=="pages/bookstore/index?aid"){
        // console.log("移除番茄")
        return null
    }else if(start_page=="pages/readPage/chapter?bookId"){
        // console.log("移除黑岩")
        return null
    }
    // console.log("未知2：",params)
    return null
}

function parsePromotionItem(item){
    let list = item.split('=')
    if(list.length>1){
        let key = list[0]
        let value = list[1]
        if(key==="start_page"&&list.length>2){
            return {key:key,value:value,bookId:list[2]}
        }
        return {key:key,value:value}
    }
    return null
}

redis_help.connect(()=>{
    get_500_data()
})