const CMD = {}
const time_count = 500;
const redis_help = require('../src/use_redis');
const origin_data_controllers = require('../src/data_manager/Controllers/origin_data_controllers');
const filter_data_controllers = require('../src/data_manager/Controllers/filter_data_controllers');

async function processTask(){
    try{
        let FilterConfig = await redis_help.getKeyValue("FilterConfig")
        FilterConfig = JSON.parse(FilterConfig)
        const result = await origin_data_controllers.getOriginDataByStatus({status:0})
        if(result.success){
            console.log("getOriginDataByStatus:",result.data.video_id)
            let filter_result = await filter_data_controllers.getFilterData({video_id:result.data.video_id})
            if(filter_result.success){
                await filter_data_controllers.updateFilterData({id:filter_result.data.id},{
                    like_num:result.data.like_num,
                    kepp_num:result.data.kepp_num,
                    shared_num:result.data.shared_num,
                    comment_num:result.data.comment_num
                })
            }else{

                let filter_data = filter_and_insert(result.data,FilterConfig)
                if(filter_data!=null){
                    filter_data.status = 0; //设置筛选的这个状态未定义
                    await filter_data_controllers.createFilterData({
                        video_id:filter_data.video_id,
                        video_link:filter_data.video_link,
                        title:result.data.title,
                        publish_time:result.data.publish_time,
                        kepp_num:filter_data.kepp_num,
                        comment_num:filter_data.comment_num,
                        like_num:filter_data.like_num,
                        shared_num:filter_data.shared_num,
                        is_guajian:result.data.is_guajian,
                        book_id:filter_data.book_id,
                        book_name:"",
                        genre:0,
                        words:0,
                        guajian_link:result.data.guajian_link,
                        tg_platform_id:filter_data.tg_platform_id,
                        source:filter_data.source,
                        status:0,
                    })
                }
            }
            console.log("result.data.id:",result.data.id)
            origin_data_controllers.updateOriginData({id:result.data.id},{
                status:1
            })
        }
    }catch(e){
        console.log("筛选数据错误：",e)
    } finally{
        global.setTimeout(processTask,time_count)
    }
}

CMD.init = function(){
    redis_help.connect(()=>{

    })
    processTask()
}


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
    }
    // console.log("挂件地址正确")
    if(origin_data.like_num < tg_config.like_num){
        return null
    }
    // console.log("点赞数正确")
    if(origin_data.kepp_num < tg_config.kepp_num){
        return null
    }
    // console.log("收藏数正确")
    if(origin_data.shared_num < tg_config.shared_num){
        return null
    }
    // console.log("分享数正确")
    if(origin_data.comment_num < tg_config.comment_num){
        return null
    }
    let tg_platform_id = 0
    if(obj.channel=="番茄"){
        tg_platform_id = 2
        obj.book_id = obj.key
    }else if(obj.channel=="黑岩"){
        tg_platform_id = 1
    }
    // 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 getChannel(start_page,platform_select){
    let isOpenHeiYan = false
    let isOpenFanQie = false
    for (let index = 0; index < platform_select.length; index++) {
        const element = platform_select[index];
        if(element==1){
            isOpenHeiYan = true
        }
        if(element==2){
            isOpenFanQie = true
        }
    }
    // console.log("start_page:",isOpenHeiYan,isOpenFanQie,start_page)
    if(start_page=="pages/readPage/chapter?bookId"&&isOpenHeiYan){
        return "黑岩"
    }else if(start_page=="pages/bookstore/index?aid"&&isOpenFanQie){
        return "番茄"
    }
    return null
}

//解析挂件
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)
            // 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;

                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 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
}

CMD.init()
