

const sql_help = require('../use_mysql');
const origin_data_controllers = require('../data_manager/Controllers/origin_data_controllers');
const CMD = {}
const 视频id = 0;
const 视频链接 = 1;
const 标题 = 2;
const 发布时间 = 3;
const 收藏数 = 4;
const 评论数 = 5;
const 点赞数 = 6;
const 分享数 = 7;
const 是否挂件 = 8;
const 挂件地址 = 9;
var isOpenSql = false
CMD.collect_create_task = null
function excelDateToJs(excelDate) {
    return new Date((excelDate - 25569) * 86400 * 1000);
}
CMD.init = function(collect_create_task){
    CMD.collect_create_task = collect_create_task
    sql_help.connect((results)=>{
        if(results){
            isOpenSql = true
        }
    })
}
// ["视频id","视频链接","标题","发布时间","收藏数","评论数","点赞数","分享数","是否挂件","挂件地址"]
CMD.start_filter = async function(tg_config,msg_body,call_back){

    if(isOpenSql==false){
        return call_back({ msg: 'fail not open mysql!',code:10001})
    }

    let FilterConfig = await tg_config.getFilterConfig()

    try{
        let temp_list = JSON.parse(msg_body)
        // console.log("temp_list:",temp_list.length)
        for (let index = 1; index < temp_list.length; index++) {
            const xml = temp_list[index];
            let guajian_link = ''
            let isGuaJian = parseInt(xml[是否挂件])==1
            if(isGuaJian){
                if(xml.length>挂件地址){
                    let data = filter_and_insert(xml,FilterConfig)
                    if(data==null){
                        
                    }else{
                        data.xml = xml
                        await CMD.collect_create_task.recv_collect_task(data) 
                    //    if(data.channel=='番茄'){
                    //         break;
                    //    }
                    }
                    guajian_link = xml[挂件地址]
                }else{  
    
                }
                try{
                    const result = await origin_data_controllers.getOriginData({video_id:xml[视频id]})
                    if(result.success){
                        await origin_data_controllers.updateOriginData({video_id:xml[视频id]},{kepp_num:xml[收藏数],comment_num:xml[评论数],like_num:xml[点赞数],shared_num:xml[分享数],guajian_link:guajian_link})
                    }else{
                        await origin_data_controllers.createOriginData({video_id:xml[视频id],
                            video_link:xml[视频链接],
                            title:xml[标题],
                            // publish_time:xml[发布时间],
                            publish_time:excelDateToJs(xml[发布时间]),
                            kepp_num:xml[收藏数],
                            comment_num:xml[评论数],
                            like_num:xml[点赞数],
                            shared_num:xml[分享数],
                            is_guajian:xml[是否挂件],
                            guajian_link:guajian_link}
                        )
                    }
                }catch(e){
                    console.log("origin_data_controllers error:",e)
                }
     
         
                // sql_help.find('SELECT * FROM origin_data where video_id = '+xml[视频id],(is_find)=>{
                //     if(!is_find){
                //         // console.log("xml[视频id]:",xml[视频id])
                //         sql_help.query('INSERT INTO origin_data SET ?', {video_id:xml[视频id],
                //             video_link:xml[视频链接],
                //             title:xml[标题],
                //             // publish_time:xml[发布时间],
                //             publish_time:excelDateToJs(xml[发布时间]),
                //             kepp_num:xml[收藏数],
                //             comment_num:xml[评论数],
                //             like_num:xml[点赞数],
                //             shared_num:xml[分享数],
                //             is_guajian:xml[是否挂件],
                //             guajian_link:guajian_link}, 
                //         async ()=>{
                //             // console.log("成功创建！")
                //         })
                //     }else{
                //         sql_help.update('UPDATE origin_data SET kepp_num = ?, comment_num = ?  , like_num = ?  , shared_num = ? WHERE video_id = ?', 
                //         [xml[收藏数],xml[评论数],xml[点赞数],xml[分享数],xml[视频id]],
                //         ()=>{
                //             // console.log("更新成功！")
                //         })
                //     }
                // })
            }
           
        }
    }catch(e){
        call_back({msg:"error!"}) 
    };
    call_back({ msg: 'success!',code:10000,data:FilterConfig})
}
// "status":1,
// "material_time":2,
// "is_guajian":1,
// "platform_select":[1,2,3],
// "comment_num":999,
// "like_num":10,
// "kepp_num":10,
// "shared_num":10,
// "genre":[1,2,3],
// "source_filter":["来源1","来源2"]
function filter_and_insert(xml,tg_config){

    if(xml[视频链接].length<=0){
        return null
    }
    // console.log("视频链接正确")
    if(xml[挂件地址]==null||xml[挂件地址]==undefined){
        return null
    }
    let obj = parsePromotion(xml[挂件地址],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(xml[点赞数] < tg_config.like_num){
        return null
    }
    // console.log("点赞数正确")
    if(xml[收藏数] < tg_config.kepp_num){
        return null
    }
    // console.log("收藏数正确")
    if(xml[分享数] < tg_config.shared_num){
        return null
    }
    // console.log("分享数正确")
    if(xml[评论数] < tg_config.comment_num){
        return null
    }
    // console.log("评论数正确")
    return {video_id:xml[视频id],book_id:obj.book_id,channel:obj.channel,source:obj.source,key:obj.key,video_link:xml[视频链接],like_num:xml[点赞数],keep_num:xml[收藏数] ,shared_num:xml[分享数] ,comment_num:xml[评论数]}
}

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.get_origin = async function(tg_config,msg_body,call_back){
    return  call_back({ msg: 'fail!',code:10001})
    let page_size = msg_body.page_size
    let page_number = msg_body.page_number
    let offset = (page_number - 1) * page_size
    let sql = `SELECT * FROM origin_data ORDER BY id LIMIT ${page_size} OFFSET ${offset}`
    sql_help.get(sql,(is_right,list)=>{
        if(is_right){
            call_back({ msg: 'success!',code:10000,data:list})
        }else{
            call_back({ msg: 'fail!',code:10001})
        }
    })
}
CMD.get_origin_total = function(tg_config,msg_body,call_back){
    return  call_back({ msg: 'fail!',code:10001})
    let sql = "SELECT COUNT(*) AS total FROM origin_data"
    sql_help.get(sql,(is_right,total)=>{
        if(is_right){
            call_back({ msg: 'success!',code:10000,data:{total:total[0].total}})
        }else{
            call_back({ msg: 'fail!',code:10001})
        }
    })
}
CMD.get_filter = async function(tg_config,msg_body,call_back){
    return  call_back({ msg: 'fail!',code:10001})
    let page_size = msg_body.page_size
    let page_number = msg_body.page_number
    let offset = (page_number - 1) * page_size
    let sql = `SELECT * FROM filter_data ORDER BY id LIMIT ${page_size} OFFSET ${offset}`
    sql_help.get(sql,(is_right,list)=>{
        if(is_right){
            call_back({ msg: 'success!',code:10000,data:list})
        }else{
            call_back({ msg: 'fail!',code:10001})
        }
    })
}

CMD.get_filter_total = function(tg_config,msg_body,call_back){
    return  call_back({ msg: 'fail!',code:10001})
    let sql = "SELECT COUNT(*) AS total FROM filter_data"
    sql_help.get(sql,(is_right,total)=>{
        if(is_right){
            call_back({ msg: 'success!',code:10000,data:{total:total[0].total}})
        }else{
            call_back({ msg: 'fail!',code:10001})
        }
    })
}
module.exports = CMD;