
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 crypto = require('crypto');
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 chongzhi_id = tg_link_config['chongzhi_id']
    let huichuan_id = tg_link_config['huichuan_id']
    let f_chongzhi_id = tg_link_config['f_chongzhi_id']
    let chongzhi_list = JSON.parse(PlatformInfo.chongzhi)
    let huichuan_list = JSON.parse(PlatformInfo.huichuan)
    let f_chongzhi_list = JSON.parse(PlatformInfo.f_chongzhi)
    let recharge_template_id = ""
    let f_recharge_template_id = ""
    let call_back_template_id = ""

    for (let index = 0; index < chongzhi_list.length; index++) {
        const cz_obj = chongzhi_list[index];
        if(cz_obj.id==chongzhi_id){
          recharge_template_id = cz_obj.value
          break
        }
    }

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

    for (let index = 0; index < f_chongzhi_list.length; index++) {
        const cz_obj = f_chongzhi_list[index];
        if(cz_obj.id==f_chongzhi_id){
            f_recharge_template_id = cz_obj.value
          break
        }
    }

    let param_list = main_info.qm_id.split(',')
    let app_external_id = param_list[1]
    let target_id = param_list[0]

    let postData = {
        admin_account_name:"zhuoyue",
        account_id:target_id,
        project:PlatformInfo.mini_program_platform_id==config.wx?8:6,     // 6 抖音小程序  8 微信小程序
        appid:main_info.app_id,
        book_id:data.product_id,
        chapter_num:1,
        name:`${data.product_name}_${timestamp}_${main_info.id}`,
        media_id: '1', //1  巨量 2 广点通 3 百度 4 微博 5 B站
        is_platform_postback:true,
        postback_rule_id: call_back_template_id, //# 回传规则 value
        // first_panel_id:recharge_template_id, //首充模板id
        repeated_panel_id:f_recharge_template_id,
        recharge_panel_id:recharge_template_id
        // repeated_panel_id:f_recharge_template_id, //# 复充模板id
    }
    
    console.log("postData:",postData)
    
    try{
        let client = tools.getOneNewClinet()
        let uuid = tools.generateCryptoNumericUUID()
        // let params = `?access_key=${config.qimao_config.access_key}&random=${uuid}&timestamp=${timestamp}`
        // let url = `${config.qimao_config.new_create_link_host}${params}`
        // let sign = tools.generateQMSignature(url,config.qimao_config.access_key)
        const baseUrl =config.qimao_config.new_create_link_host;
        const params = {
          access_key: config.qimao_config.access_key,
          random: uuid,
          timestamp: timestamp
        };
      
        // 按参数名排序并拼接
        const sortedParams = Object.keys(params)
          .sort()
          .map(key => `${key}=${params[key]}`)
          .join('&');
      
        // 假设这是您的secret_key，请替换成实际的值
        const secretKey = config.qimao_config.secret_key;  // 这里需要替换成您的实际secret_key
        
        // 计算签名
        const sign = crypto.createHash('md5')
          .update(sortedParams + secretKey)
          .digest('hex');
      
        // 构建最终URL
        const finalUrl = `${baseUrl}?${sortedParams}&sign=${sign}`;
        
        console.log("finalUrl:",finalUrl)

        let response =  await client.post(finalUrl,postData)
        if(response.code!=0){
            throw response
        }
        let n_data = response.data
        console.log("n_data:",n_data)
        let promotion_id = n_data.id
        let promotion_info = n_data.link
        let t_params = promotion_info.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);
    }
}

module.exports = CMD;