const helper = require('../src/helper');
const config = require('../etc/config.json');
const redis_help = require('../src/use_redis');
const tools = require('../tools');
const axios = require('axios');
const CMD = {}
CMD.runTask = async function(t_data,main_info,PlatformInfo,call_back){
    try{
        let  promotion_info =  await CMD.makeRequest(t_data,main_info,PlatformInfo)
        if(promotion_info==null){
            throw "创建失败！"
        }
        let t_params = promotion_info.ad_link.split('?')
        let start_page = t_params[0]
        let start_param = t_params[1]
        t_data.promotion_id = promotion_info.ad_link_id
        t_data.start_page = start_page
        t_data.start_param = start_param
        console.log('t_data:',t_data)
        call_back(t_data,null)
    }catch(error){
        call_back(t_data,error)
        return null;
    }
}

CMD.makeRequest = async function(t_data,main_info,PlatformInfo) {
    let hasSuccess = false; // 标记是否已经成功获取数据
    try {
        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 chongzhi_list = JSON.parse(PlatformInfo.chongzhi)
        let huichuan_list = JSON.parse(PlatformInfo.huichuan)
        let payment_template_id = ""
        let callback_rule_id = ""
        // let section_id = main_info.zh_id
        // console.log("section_id:",section_id)
        for (let index = 0; index < chongzhi_list.length; index++) {
            const cz_obj = chongzhi_list[index];
            if(cz_obj.id==chongzhi_id){
                payment_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){
                callback_rule_id = hc_obj.value
              break
            }
        }

        let app_type = 4
        if(PlatformInfo.mini_program_platform_id==config.wx){
            app_type = 6
        }else if(PlatformInfo.mini_program_platform_id==config.dy){
            app_type = 4
        }
        const response = await axios({
            method: 'POST',
            url: 'https://ecom.zhihu.com/api/km-agent/ad-link',
            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',
            'content-type': 'application/json;charset=UTF-8',
            'priority': 'u=1, i',
            'sec-ch-ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Microsoft Edge";v="134"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'x-requested-with': 'XMLHttpRequest',
            'cookie': '_xsrf=7bCsoKjmfrIE0D36ajUc9s6CM9OxdPHQ; _zap=aa0b20fb-9951-4f27-9f66-dafff809f1a9; d_c0=ADASSwlwjxmPTrW0768vZ0BKygxzh_LFDDI=|1731902666; captcha_session_v2=2|1:0|10:1741447186|18:captcha_session_v2|88:bjAvUkJMR1pmaENoaU9lNmNQUHI4VUVOcmNlV29DOUdhc2paN3k4NXgzR1dDbTZZS2hlSE9oT0NHbE9Wd1RHbg==|2c30267bc15ea23a591951d569b02a5866c6fe4153bfe9844e03238e35bb08f1; captcha_ticket_v2=2|1:0|10:1741447199|17:captcha_ticket_v2|728:eyJ2YWxpZGF0ZSI6IkNOMzFfdHgzRlhadC5pRzFLUjhCdTRILlVieUtfKmE4THJTZExjRG5zR0RQQ3piczJOZm1UeFhOWlVlWmVZRSpweGZ0ckhhSGdJUkF2ZVBWVDNVVXdlNk5VdGdaRWswLmlOVHRfZXlMX1BJYjl5YmQ0aVNUU3gxY09lT0FIbXZrRU5jd3RVc1MyWHpiQXo1dGRGX1NUa21Tc0tHYjEuaFFmRHBkMFJtdUNRKjJxMzUucVNZMkRQdktoM2N0c3hlR0syVW1FZ1ltUEVQWF9XR2JxSE5LekRHa2NxdzRua1lkVURPSVBod1g0TktuZFBOcV9mZkVydGxQMUIyYlkyLk5PT1oxRjN3LlhhTTlUUWx3T1QzQ3A4WkswcypsdDljXzNPOVh0S2o0QnFTNkhtM2ZMMjY1MTF6ZUVfeEw4Sm1YX2Y4ZEprQ29vUjVqdnpWZ0xfVjNaSVJQYWJCYnRJU2FhcFBVKlVJZWFPS3FGaVJMKjJBdipXb1dGd3BQUkZWSnNreTZWU0Z2QWttUzAqSGNobFJMVTlIaml2Um9ZZDUweklHclppclM1bGxDYV9lTWpCa2RCUk50TFNlbzEyeU81OXRMY2lYYUhKOHlVUFRuM09Mem1LRjl4RS4yY1RUd1Y5eFp2OVllKnZFMFdEVGNLeEZIRzAya1J5TnRrTUptMExYQ1N3WkduNGc3N192X2lfMSJ9|d385252c1df14a29550fa1bd5e7c0ea7188926820724b891b1e45b4a7957e487; ecom_merchant=1857114769787609088; __zse_ck=004_sIi5cAl5BMYEcRjXCzN9Ss/sPdTgyWyqqlROJEfAC536m/14KU5f3bsu9YkOtEpb3SB7LJcTJmDSF8VOPwDBT7qZQ1X2bc6ZpoxxcZPN4dSC/cCKSAsWTyUcPEiGer9H-GPnGh0a+WoC5zsijY40YdUadlvVR/3+w/qxaA/4xpDkxT3/6olByfH30JO+JQrRdZpbKLEfYzUNaHK7p4+Hk5FsyZtHEgz5/T2iZiDiR3W7ciBwMe0Xo9otuzN31fIED3FRq52IXIf8RBHjNa8bqSsG+C2fN2dlxWq6C9Nzt5SA=; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1739763111,1741447186,1741685631; z_c0=2|1:0|10:1741685631|4:z_c0|92:Mi4xN1lrbldnQUFBQUFBTUJKTENYQ1BHU1lBQUFCZ0FsVk5JSzY1YUFDY1RrZmZuVXJRTXVQYWplQ1ZiRkVTNUZXUXp3|687b16cb02ca463cfff332a2e451e60a2feceada4a94f4afdbb01fdabda2f0f1; BEC=4589376d83fd47c9203681b16177ae43',
            'Referer': `https://ecom.zhihu.com/vip-apps/out-distribution/contentLib/detail?&sectionId=${t_data.promotion_id}&workId=${t_data.promotion_id}&appId=${main_info.app_id}&media_channel_type=5`,
            'Referrer-Policy': 'no-referrer-when-downgrade'
            },
            data: {
                multi_sections: "0",
                ad_link_name: `${t_data.product_name}_${main_info.id}`,
                media_channel_id: 5,
                app_type: app_type,
                app_id: main_info.app_id,
                callback_type: 0,
                payment_template_id: `${payment_template_id}`,
                num: 1,
                callback_rule_id: `${callback_rule_id}`,
                section_id: t_data.product_id
            }
            // data: {
            //     multi_sections: "0",
            //     ad_link_name: "断子绝孙是渣男应得的_81_fuck",
            //     media_channel_id: 5,
            //     app_type: 4,
            //     app_id: "ttbe09c8b4213ae0bf01",
            //     callback_type: 0,
            //     payment_template_id: "1610",
            //     num: 1,
            //     callback_rule_id: "1857508752934199296",
            //     section_id: "1885351423992124349"
            //   }
        });
        if(response.data){
            hasSuccess = true;
        }
   
      console.log('响应状态:', response.status);
      console.log('响应数据:', response.data);
      return response.data.data
    } catch (error) {
        if(hasSuccess){

        }else{
            console.error('请求错误:', error.message);
            if (error.response) {
              console.error('错误状态码:', error.response.status);
              console.error('错误数据:', error.response.data);
            }
            return null
        }
    }
  }
module.exports = CMD;