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; __zse_ck=004_Yfd5z9=wVYdipziWJIurZOunLG37mTG2H9iYSlwWRDLk8=MX0olTiRGFlFAjfxcEHEKs3rAZEP/YK23mOi0JdimzivR8x6V8xrTX/SfG2rxez3yjRYZe5TLBDSnO/5x5-qJOwYJOI+PpcVzmlrlnRdtJiOBmlpDaX+iwb4g5wrE5nNLFf5lpJfeqFnUf1/zvSv87a+WPkgCwI5omwr8gRzjTiqCSHq+aDiXaB6KX9RDdi72KjThWCjiJa356jV2Ha; BEC=738c6d0432e7aaf738ea36855cdce904; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1744797535,1747044239; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1747044239; HMACCOUNT=8B23C823A8286BDF; captcha_session_v2=2|1:0|10:1747044240|18:captcha_session_v2|88:WU9XenluNjRDQnRqalZvSmxYU2dNZldqRW1oc1l1aUdUTFh0SmNFWFVOS2E4Zm1ieVVqL0JxTWcwUHB5dng2Qg==|e48d0f7dc867c3386e846e6a046467e209447e0f45de2ec58e40cb5ea89b5024; captcha_ticket_v2=2|1:0|10:1747044266|17:captcha_ticket_v2|728:eyJ2YWxpZGF0ZSI6IkNOMzFfODlzRTFBbml6YmRKcUE1YzFXcHRIOXZ1Q0h4dXBPMXVsQzRNYklwREZpMVlhUkpjY2pseWFEVjR5Y3ZzLktzLnB2NUROQ1Z5LjUxbENrUzQzVFBxTkRqYnlKcWFYYnZRcGM4WGVJQWhQR0dvX3ZIaGlzVldRdzVtelVlcE1sdC5BVTJhYi5VSVM1bWswZUNqdkRlRnRqa1NoWFpjNmdQdUlHVzllX3RWbVFQOG5scmZQUWJBX1JXRWxKTTlBZEgweFpJNkY1U0J2TE52UDlvZlNlY1M1VzhiOGxOcTNrdjA1QzZ1SWhSQTRKQUVQQ2ZOX0tvNHE2RTN6Zk14SklaOVZ6QWtvVS42dE1GbHN3ODJ4b2JGTXlTMXdITGtUNTNpNVJCUUdYWUZ2THdIVTZ3LmNtd3dsX1pGcFJ0VzBfZlRqOU40KjBtcEdEY1JlZVBXbEMwTFlhYlA4bzgxUmxsUWkqZHdKelpKRUdxSnRmKnoqTnhJZl93NlR0Y2RkT3ZvWVVfRFRkVWF3cHl2UlhTcExEb0Q5TldDR0d2cDZxOVJoMU9WNlZXNHdRaEQ0X2Z3U3VPSjlFZipLY3JKTVdvc1o2KkpvVDl6Vms0enVJLkVCLlN0T3JXRm5ZVWduZFlzNW9kY0pCbGRjYkk0Nmd1OUIudlZIQjJIbWdMUHgxQVFiLjk1Q003N192X2lfMSJ9|86552ad9b795608fe66c8628d1a00b37678dfd2c0345979a0ade4da1d9075998; z_c0=2|1:0|10:1747044266|4:z_c0|92:Mi4xWjA2M1hBQUFBQUFBTUJKTENYQ1BHU1lBQUFCZ0FsVk5xaFVQYVFEYmZqdjk5aW90YXVCVWRVaUxjdmcxMlpoNF93|7715e73dbd09a2ff037024e7c3c87c621ee1d97648f3c5a9c82ed50a82e93837; ecom_merchant=1876277363932790784',
            '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;