
const video_product_controllers = require("../data_manager/Controllers/video_product_controllers")
const video_applet_product_controllers = require("../data_manager/Controllers/video_applet_product_controllers")
const axios = require('axios');
const filter_data_controllers = require('../data_manager/Controllers/filter_data_controllers');
const tools = require("../../tools");
const CMD = {}
const 视频id = 0;
const 视频链接 = 1;
const 标题 = 2;
const 发布时间 = 3;
const 收藏数 = 4;
const 评论数 = 5;
const 点赞数 = 6;
const 分享数 = 7;
const 是否挂件 = 8;
const 挂件地址 = 9;
CMD.tg_config = null
var hy_create_link_task_list = []
var fq_create_link_task_list = []
var find_video_applet_product_task_list = []
var insert_filter_data_task_list = []
var insert_video_product_task_list = []
function excelDateToJs(excelDate) {
    return new Date((excelDate - 25569) * 86400 * 1000);
}
CMD.init = function(tg_config){
    CMD.tg_config = tg_config
    // sql_help.connect((results)=>{
    //     if(results){
    //         console.log("collect_and_create_data_server：sql_help")
    //     }
    // })

    // sql_task_help.connect((results)=>{
    //     if(results){
    //         console.log("collect_and_create_data_server：sql_task_help")
    //     }
    // })

    setInterval(() => {
        
        if(hy_create_link_task_list.length>0){
            let hy_create_link_task = hy_create_link_task_list.pop()
            require('./hy_create_link').runTask(hy_create_link_task.n_data
                ,hy_create_link_task.main_info,
                hy_create_link_task.PlatformInfo,finish_call_back)
        }

        if(fq_create_link_task_list.length>0){
            let fq_create_link_task = fq_create_link_task_list.pop()
            require('./fq_create_link').runTask(fq_create_link_task.n_data
                ,fq_create_link_task.main_info,
                fq_create_link_task.PlatformInfo,finish_call_back)
        }

        if(find_video_applet_product_task_list.length>0){
            let find_video_applet_product = find_video_applet_product_task_list.pop()
            CMD.find_video_applet_product(find_video_applet_product,finish_find_video_applet_product)
        }

        if(insert_filter_data_task_list.length>0){
            let insert_filter_data_item = insert_filter_data_task_list.pop()
            CMD.insert_filter_data(insert_filter_data_item.xml,insert_filter_data_item.data)
        }

        if(insert_video_product_task_list.length>0){
            let insert_video_product_item = insert_video_product_task_list.pop()
            CMD.insert_video_product(insert_video_product_item.data)
        }
        
    }, 2000);
}

CMD.finish_create_link = function(data){
    // console.log("finish_create_link:",data)
    let url = tools.getSupdate()+'/sapi/video_product_material/supdate';
    const formData = new FormData();
    // formData.append('dy_id', data.xml[视频id]);
    // formData.append('dy_url', data.xml[视频链接]);
    // formData.append('product_id', data.book_id);
    // formData.append('product_name', data.book_name);
    // formData.append('d_z_number', data.xml[点赞数]);
    // formData.append('collect_number',data.xml[收藏数]);
    // formData.append('comment_number', data.xml[评论数]);
    // formData.append('forward_number',data.xml[分享数]);
    // formData.append('book_platform', data.tg_platform_id);
    // formData.append('yun_fabu_time', excelDateToJs(data.xml[发布时间]));
    formData.append('data',JSON.stringify({
        dy_id:data.xml[视频id],
        dy_url:data.xml[视频链接],
        product_id:data.book_id,
        product_name:data.book_name,
        d_z_number:data.xml[点赞数],
        collect_number:data.xml[收藏数],
        comment_number: data.xml[评论数],
        forward_number: data.xml[分享数],
        book_platform: data.tg_platform_id,
        yun_fabu_time:excelDateToJs(data.xml[发布时间])
    }))
    // console.log("formData:", formData);
    axios.post(url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    .then(response => {
        if(response.data.code===10000){
            console.log("插入任务表成功:", response.data);
        }else{
            console.log("插入任务表失败:", formData);
        }
   
    })
    .catch(error => {
        console.error("插入任务表失败:", error,formData);
    });
}
function deepCopy3(obj) {
    return JSON.parse(JSON.stringify(obj));
}

let finish_find_video_applet_product = (is_find,video_applet_product_item,n_data,main_info,PlatformInfo)=>{
    if(is_find){
        n_data.start_page = video_applet_product_item.dy_small_program_start
        n_data.start_param = video_applet_product_item.dy_small_program_start_data
        CMD.finish_create_link(n_data)
    }else{
        if(n_data.channel=="黑岩"){
            hy_create_link_task_list.push({
                n_data:n_data,
                main_info:main_info,
                PlatformInfo:PlatformInfo
            })
        }else if(n_data.channel=="番茄"){
            fq_create_link_task_list.push({
                n_data:n_data,
                main_info:main_info,
                PlatformInfo:PlatformInfo
            })
        }
    }

}
let finish_call_back = async (new_data)=>{
    try{
        const result = await video_applet_product_controllers.createAppletProductData({
            book_platform:new_data.tg_platform_id,
            product_name:new_data.book_name,
            product_id:new_data.book_id,
            dy_small_program_start:new_data.start_page,
            dy_small_program_start_data:new_data.start_param,
            dy_small_applet_app_id:new_data.app_id,
            status:0,
            main_id:new_data.main_id,
            promotion_id:new_data.promotion_id,
            // dy_id:new_data.xml[视频id],
            // dy_url:new_data.xml[视频链接],
            // title:new_data.xml[标题],
            // d_z_number:new_data.xml[点赞数],
            // collect_number:new_data.xml[收藏数],
            // comment_number:new_data.xml[评论数],
            // forward_number:new_data.xml[分享数],
            // yun_fabu_time:new_data.xml[发布时间],
            wait_status:0,
        })

        if(result.success){
            CMD.finish_create_link(new_data)
        }
    }catch(e){
        console.log("finish_call_back error:",e)
    }
    // sql_task_help.query('INSERT INTO video_applet_product SET ?', {
    //     book_platform:new_data.tg_platform_id,
    //     product_name:new_data.book_name,
    //     product_id:new_data.book_id,
    //     dy_small_program_start:new_data.start_page,
    //     dy_small_program_start_data:new_data.start_param,
    //     dy_small_applet_app_id:new_data.app_id,
    //     status:0,
    //     main_id:new_data.main_id,
    //     promotion_id:new_data.promotion_id,
    //     // dy_id:new_data.xml[视频id],
    //     // dy_url:new_data.xml[视频链接],
    //     // title:new_data.xml[标题],
    //     // d_z_number:new_data.xml[点赞数],
    //     // collect_number:new_data.xml[收藏数],
    //     // comment_number:new_data.xml[评论数],
    //     // forward_number:new_data.xml[分享数],
    //     // yun_fabu_time:new_data.xml[发布时间],
    //     wait_status:0,
    // }, 
    // async ()=>{
    //     CMD.finish_create_link(new_data)
    //     // console.log("成功创建！")
    // })
}

CMD.finish_find_book = function(data){
    let is_need = false
    let FilterConfig =  CMD.tg_config.getStaticFilterConfig()
    //判断长篇短篇是否是要的数据
    for (let index = 0; index < FilterConfig.genre.length; index++) {
        const element = FilterConfig.genre[index];
        if(data.genre==element){
            is_need = true
            break
        }
    }
    // console.log("finish_find_book:",data,is_need,FilterConfig)
    if(is_need){ 
        //在这里插入数据到筛选库里
        insert_filter_data_task_list.push({xml:data.xml,data:data})
        insert_video_product_task_list.push({data:data})
        // CMD.insert_filter_data(data.xml,data)
        // CMD.insert_video_product(data)

        let PlatformInfo = CMD.tg_config.getStaticPlatformInfoByName(data.channel)
        if(PlatformInfo==null){
            return console.error("平台配置错误：",data)
        }
        let list = CMD.tg_config.getMainInfoByAppid(data.app_id)
        if(list.length<0){
            return console.error("获取主体错误：",data)
        }
        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
            if(main_info.tg_link_config==undefined||main_info.tg_link_config==null){
                console.error("主体配置推广链接错误：",main_info)
            }else{
                //判断 video_applet_product 表里是否存在这个 主体下的书
                let n_data = deepCopy3(data)
                n_data.tg_link_config = main_info.tg_link_config
                find_video_applet_product_task_list.push({book_id:n_data.book_id,main_id:main_info.id,n_data:n_data,main_info:deepCopy3(main_info),PlatformInfo:deepCopy3(PlatformInfo)})
            }
        }

   
    }
}

CMD.insert_filter_data = async function(xml,data){
    try{
        const result = await filter_data_controllers.getFilterData({ video_id: xml[视频id] });
        if(result.success){
            filter_data_controllers.updateFilterData({video_id: xml[视频id]},{
                kepp_num:xml[收藏数],
                comment_num:xml[评论数],
                like_num:xml[点赞数],
                shared_num:xml[分享数]
            })
        }else{
            filter_data_controllers.createFilterData({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:xml[挂件地址],
                book_name:data.book_name,
                genre:data.genre,
                book_id:data.book_id,
                words:data.words,
                tg_platform_id:data.tg_platform_id,
                source:data.source
            })
        }
        console.log(result);
    }catch(e){
        console.log("insert_filter_data error:",e)
    }
  

    // sql_help.find('SELECT * FROM filter_data where video_id = '+xml[视频id],(is_find)=>{
    //     if(!is_find){
    //         // console.log("xml[视频id]:",xml[视频id])
    //         sql_help.query('INSERT INTO filter_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:xml[挂件地址],
    //             book_name:data.book_name,
    //             genre:data.genre,
    //             book_id:data.book_id,
    //             words:data.words,
    //             tg_platform_id:data.tg_platform_id,
    //             source:data.source
    //         }, 
    //         async ()=>{
    //             // console.log("成功创建！")
    //         })
    //     }else{
    //         sql_help.update('UPDATE filter_data SET kepp_num = ?, comment_num = ?  , like_num = ?  , shared_num = ? WHERE video_id = ?', 
    //         [xml[收藏数],xml[评论数],xml[点赞数],xml[分享数],xml[视频id]],
    //         ()=>{
    //             // console.log("更新成功！")
    //         })
    //     }
    // })
}
//status 0 未配置 1开启 2关闭
CMD.find_video_applet_product = async function(data,call_back){
    try{
        const result = await video_applet_product_controllers.getAppletProductData({book_id:data.book_id,main_id:data.main_id})
        if(result.success){
            call_back(true,result.data,data.n_data,data.main_info,data.PlatformInfo)
        }else{
            call_back(false,null,data.n_data,data.main_info,data.PlatformInfo)
        }
    }catch(e){

    }
    // let sql = `SELECT * FROM video_applet_product where product_id = ${data.book_id} and main_id = ${data.main_id}`
    // sql_task_help.find(sql,(is_find,video_applet_product_item)=>{
    //     if(!is_find){
    //         // console.log("xml[视频id]:",xml[视频id])
    //         call_back(false,null,data.n_data,data.main_info,data.PlatformInfo)
    //     }else{
    //         call_back(is_find,video_applet_product_item,data.n_data,data.main_info,data.PlatformInfo)
    //     }
    // })
}

//插入 video_product 书表
CMD.insert_video_product = async function(data){
    try{
        const result = await  video_product_controllers.getProductData({book_id:data.book_id})
        if(result.success){
          
        }else{
            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
            })
        }
    }catch(e){

    }

    // sql_task_help.find('SELECT * FROM video_product where product_id = '+data.book_id,(is_find)=>{
    //     if(!is_find){
    //         // console.log("xml[视频id]:",xml[视频id])
    //         sql_task_help.query('INSERT INTO video_product SET ?', {
    //             book_platform:data.tg_platform_id,
    //             product_name:data.book_name,
    //             genre:data.genre,
    //             product_id:data.book_id,
    //             words:data.words
    //         }, 
    //         async ()=>{
    //             // console.log("成功创建！")
    //         })
    //     }else{
    //         // sql_help.update('UPDATE video_product SET words = ?', 
    //         // [words],
    //         // ()=>{
    //         //     // console.log("更新成功！")
    //         // })
    //     }
    // })
}

CMD.recv_collect_task = async function(data){
    let PlatformInfo = await CMD.tg_config.getPlatformInfoByName(data.channel)
    if(PlatformInfo!=null){

        data.tg_platform_id = PlatformInfo.tg_platform_id;
        data.tg_platform_name = PlatformInfo.tg_platform_name;

        let AppInfo = CMD.tg_config.getAppInfoByPlatformId(data.tg_platform_id)
        data.app_id = AppInfo.app_id

        if(data.channel=="黑岩"){
            require('./collect_hy_book').runTask(data,CMD.finish_find_book)
        }else if(data.channel=="番茄"){
            require('./collect_fq_book').runTask(data,CMD.finish_find_book)
        }
    }else{
        console.log("recv_collect_task PlatformInfo == null error:",data)
    }

    return
}


module.exports = CMD;