
const fetch = require('node-fetch'); // Node.js 18以下版本需要安装 node-fetch
const tools = require('../tools');
const helper = require('../src/helper');
const config = require('../etc/config.json')
const CMD = {}
CMD.runTask = async function (data,main_info,PlatformInfo,call_back) {
    let timestamp = helper.getCurrentUnixTimestamp()
    let tg_link_config = JSON.parse(main_info.tg_link_config)
    let huichuan_id = tg_link_config['huichuan_id']
    let huichuan_list = JSON.parse(PlatformInfo.huichuan)

    let call_back_template_id = ""

    let app_id = main_info.app_id

    for (let index = 0; index < huichuan_list.length; index++) {
        const hc_obj = huichuan_list[index];
        if(hc_obj.id==huichuan_id){
          call_back_template_id = hc_obj.value
          break
        }
    }


    const url = 'https://new-media-iaa-fx.qimao.com/api/promotion/create';

    let postData = {
        media_id: '1', //今日头条
        postback_rule_id: call_back_template_id, //# 回传规则 value
        book_id:data.product_id,
        book_name:data.product_name,
        chapter_num:1,
        // repeated_panel_id:f_recharge_template_id, //# 复充模板id
        batch_num:1,
        promotion_name:`${data.product_name}_${timestamp}_${main_info.id}`,
        env: '',
        t: timestamp  // 当前时间戳
    }
    
    console.log("postData:",postData)
    // 请求参数
    const params = new URLSearchParams(postData);
    let param_list = main_info.qm_id.split(',')
    // let app_external_id = param_list[1]
    let target_id = param_list[0]
    // 请求头
    var dy_headers = {
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        "app-id": `${app_id}`,
        'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SUQiOjU1NzcwMjIxODI2MzQ0OTYxMSwiQWNjb3VudE5hbWUiOiJ6aHVveXVlIiwiVGltZVN0YW1wIjoxNzQyMjgwNDU1LCJDbGllbnRJUCI6IjIxOS4xMzYuMTMwLjEwNyIsIkJ1ZmZlclRpbWUiOjAsImV4cCI6MTc0MjM2Njg1NSwiaXNzIjoicW1fbmV3X21lZGlhX2Z4IiwibmJmIjoxNzQyMjgwNDU1LCJFbnYiOiJyZWxlYXNlIiwiSXNTaW11bGF0aW9uTG9naW4iOmZhbHNlfQ.nUn5QkVnC-oQ6qwjc8Bh5jRTsTKqwzPS5cphBIiaBvU',
        'project': 'reader_free_dyminiapp',
        "Content-Type": "application/json;charset=UTF-8",
        'signature': '7387e151c84a34ed10a3d3580e89bb8280fcb058087ad8e5c7bae07e6f38f083',
        'target-id': `${target_id}`,
        'cookie': 'sensorsdata2015jssdkcross=%7B%22%24device_id%22%3A%22193bdc124645e2-0cbeaee172d4ce8-4c657b58-921600-193bdc12465567%22%7D; sa_jssdk_2015_new-media-iaa-fx_qimao_com=%7B%22distinct_id%22%3A%22195a243a180505-022ff8224617bd2-4c657b58-921600-195a243a1815e0%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E5%BC%95%E8%8D%90%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%2C%22%24latest_referrer%22%3A%22http%3A%2F%2F120.79.128.142%3A4999%2F%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk1YTI0M2ExODA1MDUtMDIyZmY4MjI0NjE3YmQyLTRjNjU3YjU4LTkyMTYwMC0xOTVhMjQzYTE4MTVlMCJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%7D; acw_tc=0a47318117422869658617238e00c50400e0d073060f4b030334140762ab3f',
    };

    var wx_headers = {
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        "app-id": `${app_id}`,
        'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SUQiOjU1NzcwMjIxODI2MzQ0OTYxMSwiQWNjb3VudE5hbWUiOiJ6aHVveXVlIiwiVGltZVN0YW1wIjoxNzQyMjgwNDU1LCJDbGllbnRJUCI6IjIxOS4xMzYuMTMwLjEwNyIsIkJ1ZmZlclRpbWUiOjAsImV4cCI6MTc0MjM2Njg1NSwiaXNzIjoicW1fbmV3X21lZGlhX2Z4IiwibmJmIjoxNzQyMjgwNDU1LCJFbnYiOiJyZWxlYXNlIiwiSXNTaW11bGF0aW9uTG9naW4iOmZhbHNlfQ.nUn5QkVnC-oQ6qwjc8Bh5jRTsTKqwzPS5cphBIiaBvU',
        'project': 'reader_free_dyminiapp',
        "Content-Type": "application/json;charset=UTF-8",
        'signature': '7387e151c84a34ed10a3d3580e89bb8280fcb058087ad8e5c7bae07e6f38f083',
        'target-id': `${target_id}`,
        'cookie': 'sensorsdata2015jssdkcross=%7B%22%24device_id%22%3A%22193bdc124645e2-0cbeaee172d4ce8-4c657b58-921600-193bdc12465567%22%7D; sa_jssdk_2015_new-media-iaa-fx_qimao_com=%7B%22distinct_id%22%3A%22195a243a180505-022ff8224617bd2-4c657b58-921600-195a243a1815e0%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E5%BC%95%E8%8D%90%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%2C%22%24latest_referrer%22%3A%22http%3A%2F%2F120.79.128.142%3A4999%2F%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk1YTI0M2ExODA1MDUtMDIyZmY4MjI0NjE3YmQyLTRjNjU3YjU4LTkyMTYwMC0xOTVhMjQzYTE4MTVlMCJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%7D; acw_tc=0a47318117422869658617238e00c50400e0d073060f4b030334140762ab3f',
    };

    let headers = ""
    if(PlatformInfo.mini_program_platform_id==config.wx){
        headers = wx_headers
    }else if(PlatformInfo.mini_program_platform_id==config.dy){
        headers = dy_headers
    }

    headers['authorization'] = await tools.getQMMFToken()
    try {
        const response = await fetch(`${url}?${params}`, {
            method: 'Post',
            headers: headers
        });

        const result = await response.json();
        // { code: 200, data: {}, msg: 'ok' }
        if(result.code!=200){
            throw result
        }
        console.log('响应状态:', response.status);
        console.log('响应数据:', result);
        
        let n_data = await require("../src/api/qm_mf/get_qm_mf_promotion").getPromotionList(app_id,target_id,postData.promotion_name,PlatformInfo.mini_program_platform_id)
        console.log('n_data:', n_data);
        if(n_data==null){
            throw result
        }

        if(n_data.code!=200){
            throw result
        }
        let promotion_id = n_data.promotion_id
        let promotion_info = n_data.data
        let t_params = promotion_info.promotion_url.split('?')
        let start_page = t_params[0]
        let start_param = t_params[1]
        data.start_page = start_page
        data.start_param = start_param
        data.promotion_id = promotion_id
        call_back(data,null)
    } catch (error) {
        call_back(data,error)
        console.error('请求错误:', error);
    }
}

// Node.js 18及以上版本可以直接运行
// Node.js 18以下版本需要先安装 node-fetch:
// npm install node-fetch@2

module.exports = CMD;