const CMD = {}
const video_applet_product_controllers = require('../src/data_manager/Controllers/video_applet_product_controllers');
const sql_task_help = require('./use_task_mysql');
const axios = require('axios');
const time_count = 2000;
const redis_help = require('../src/use_redis');
const works_controllers = require('../src/data_manager/Controllers/works_controllers');
const checks_products_controllers = require('../src/data_manager/Controllers/checks_products_controllers');
const spreads_controllers = require('../src/data_manager/Controllers/spreads_controllers');

// const cp_type = new Map()
// cp_type.set('CD','常读')
// cp_type.set('YW','阅文')
// cp_type.set('WD','文鼎')
// cp_type.set('HY','黑岩')
// cp_type.set('JDY','绝顶云')
// cp_type.set('YG','阳光')
// cp_type.set('QM','七猫')

const buildCheckUrl = (info) => {
    return `https://n8-adv-ocean.s6kuwan.com/open/click/report?spread_id=${info.id}&project_id=__PROJECT_ID__&promotion_id=__PROMOTION_ID__&request_id=__REQUEST_ID__&adv_click_id=__CLICK_ID__&csite=__CSITE__&convert_id=__CONVERT_ID__&imei=__IMEI__&idfa=__IDFA__&android_id=__ANDROIDID__&oaid=__OAID__&oaid_md5=__OAID_MD5__&os=__OS__&ip=__IPV4__&ip6=__IPV6__&ua=__UA__&click_at=__TS__&callback_param=__CALLBACK_PARAM__&model=__MODEL__&union_site=__UNION_SITE__&mid1=__MID1__&mid2=__MID2__&mid3=__MID3__&sign=d9a814d4bccfb06b84fe4d4ba6bce6f4`;
}

CMD.getMainInfoById = function(MainConfig,main_id){
    // console.log("MainConfig:",MainConfig)
    for (let index = 0; index < MainConfig.length; index++) {
        const element = MainConfig[index];
        if(element.id==main_id){
            return element
        }
    }
    return null
}

async function processTask() {
    try {
       let result = await video_applet_product_controllers.getAppletProductByStatusAndLimit({status:0,wait_status:1},100)
       if(result.success){
            let video_applet_product_data_list = result.data
            
 
            if(video_applet_product_data_list.length<=0){
                throw "no data!"
            }


            let id_list = []

            for (let index = 0; index < video_applet_product_data_list.length; index++) {
                const element = video_applet_product_data_list[index];
                id_list.push(element.id)
            }
            const placeholders = id_list.join(',');
            sql_task_help.update(`UPDATE video_applet_product SET status = ?, wait_status = ?  , check_url = ?   WHERE  id IN  (${placeholders})`, 
                [1,2,"https://n8-adv-ocean.s6kuwan.com"],
                ()=>{
                    // console.log("update_video_applet_product:更新成功！")
                })
            return

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

            for (let index = 0; index < video_applet_product_data_list.length; index++) {
                const video_applet_product_item = video_applet_product_data_list[index];
                let main_id = video_applet_product_item.main_id
                let main_info = CMD.getMainInfoById(MainConfig,main_id)
                let product_id = video_applet_product_item.product_id
                let product_name = video_applet_product_item.product_name
                let promotion_id = video_applet_product_item.promotion_id
                let dy_small_program_start = video_applet_product_item.dy_small_program_start
                let dy_small_program_start_data = video_applet_product_item.dy_small_program_start_data
                if(main_info==null&&video_applet_product_item.is_close_execution==1){
                    let CloseMainConfig = await redis_help.getKeyValue("CloseMainConfig")
                    CloseMainConfig = JSON.parse(CloseMainConfig)
                    main_info = CMD.getMainInfoById(CloseMainConfig,main_id)
                }

                if(main_info!=null){
                    let checks_products_item = await checks_products_controllers.queryArrayValue('main_id_info',main_id+"")
                    // let checks_products_item = await checks_products_controllers.getData({main_id:main_id})
                    if(checks_products_item.success){
                        let cp_type = checks_products_item.data.cp_type
                        let works_item = await works_controllers.getData({product_id:product_id})
                        let id = -1
                        if(!works_item.success){
                            let works_result =  await works_controllers.createData({cp_work_id:product_id,cp_type:cp_type,name:product_name})
                            if(works_result.success){
                                id = works_result.data.id
                            }
                        }else{
                            id = works_item.data.id
                        }
                        if(id!=-1){
                            let tableData = {
                                product_id:checks_products_item.data.id,
                                name:product_name,
                                cp_type:cp_type,
                                cp_spread_id:promotion_id,
                                work_id:id,
                                chapter_id:1,
                                adv_alias:"OCEAN",
                                link_type:"CG",
                                status:"ENABLE",
                                admin_id:1,
                                hap_url:"",
                                h5_url:"",
                                http_url:"",
                                apk_url:"",
                                convert_callback_strategy_id:0,
                                page_path:`${dy_small_program_start}?${dy_small_program_start_data}`
                            }
                            let check_info = {cp_spread_id:promotion_id,cp_type:cp_type,product_id:checks_products_item.data.id}
                            let spreads_result = await spreads_controllers.getData(check_info)
                            if(spreads_result.success){
                                let check_url = buildCheckUrl({id:spreads_result.data.id})
                                CMD.update_video_applet_product({promotion_id:promotion_id,
                                   product_id:product_id,check_url:check_url
                               })
                            }else{
                                spreads_result =  await spreads_controllers.createData(tableData)
                                if(spreads_result.success){
                                     let check_url = buildCheckUrl({id:spreads_result.data.id})
                                     CMD.update_video_applet_product({promotion_id:promotion_id,
                                        product_id:product_id,check_url:check_url
                                    })
                                }
                            }
                  
                        }

                    }else{
                        let check_url = ""
                        CMD.update_video_applet_product({promotion_id:promotion_id,
                           product_id:product_id,check_url:check_url
                        })
                        await new Promise(resolve => setTimeout(resolve,100));
                    }
                }else{
                       throw `主体是空的 ！：${main_id}` 
                }
            }

       }else{
            throw "查询表格失败！"
       }
    } catch (e) {
        console.log("暂无监测链接创建",e)
    }finally{
        global.setTimeout(processTask,time_count)
    }
}

CMD.init = async function(){
    sql_task_help.connect((results)=>{
        if(results){
            console.log("send_data_server：sql_task_help")
        }
    })
    redis_help.connect((results)=>{
        if(results){
        }
    })
    // let checks_products_item = await checks_products_controllers.queryArrayValue('main_id_info',161+"")
    // console.log("checks_products_item:",checks_products_item)
    processTask()
    // let sql = `SELECT * FROM video_applet_product WHERE TIMESTAMPDIFF(HOUR, create_at, NOW()) < 24 AND status = 0 AND wait_status = 1 ORDER BY create_at DESC LIMIT 1;`
    // setInterval(() => {
    //     sql_task_help.get(sql,(is_right,data)=>{
    //         if(is_right){
    //             // console.log("sql:",data)
    //             if(data.length>0){
    //                 CMD.build_check_url( data[0])
    //             }
    //         }
    //     })
    // }, time_count);
}

CMD.build_check_url = function(data){
    let url = 'https://clipvideoup.s6kuwan.com/sapi/check/get_check_url';
    const formData = new FormData();
    formData.append('platform_id', data.book_platform);
    formData.append('cp_spread_id', data.promotion_id);
    // console.log("formData:", formData);
    axios.post(url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    .then(response => {
        if(response.data.code==10000){
            CMD.update_video_applet_product({promotion_id:data.promotion_id,
                product_id:data.product_id,check_url:response.data.content.check_url
            })
        }
    })
    .catch(error => {
        console.error('create_link was an error!', error);
    });
}

CMD.update_video_applet_product = function(data){
    if(data.check_url==""){
        sql_task_help.update('UPDATE video_applet_product SET status = ?, wait_status = ?  , check_url = ?   WHERE promotion_id = ? and product_id = ?', 
            [1,3,data.check_url,data.promotion_id,data.product_id],
            ()=>{
                // console.log("update_video_applet_product:更新成功！")
            })
    }else{
        sql_task_help.update('UPDATE video_applet_product SET status = ?, wait_status = ?  , check_url = ?   WHERE promotion_id = ? and product_id = ?', 
            [1,2,data.check_url,data.promotion_id,data.product_id],
            ()=>{
                // console.log("update_video_applet_product:更新成功！")
            })
    }

}
CMD.init()