const fetch = require('node-fetch'); // Node.js 18以下版本需要安装 node-fetch
const helper = require('../src/helper');
const config = require('../etc/config.json');
const redis_help = require('../src/use_redis');
const CMD = {}
CMD.runTask = async function(t_data,main_info,PlatformInfo,call_back){
    try{
        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 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
            }
          }

        const 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": "\"Not A(Brand\";v=\"8\", \"Chromium\";v=\"132\", \"Microsoft Edge\";v=\"132\"",
            "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_RAwxSX7iODkHf=KcaqfMYfLtUB=liEm/v0fmgVHxEqKYzUEWDsJ4I5wkbR1yz3X=sAOsMm7PcwNXoQHjg5IxNkMc38yFAYS9Vcvho/AB5CWvfKZL7JZ6yb8JNCk=hJhs-xC0Hm7QqNBqkjTYlQ0LGKY50XF8sCD+ku+G/FUcrxDHtM9cxwgjtwoE7C9tAtkeLkUwyYVe6lZG1PpW/gndPL1lhcrZ53odQtwGooASih8FG2HI3W7Xpo3Bq+eqzshzK; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1735787111,1735909747,1736148711; captcha_session_v2=2|1:0|10:1736148772|18:captcha_session_v2|88:YkZmazRKNXExV2dHaTkvaWIyQkJaUXpPZDFEbFNwWTR1bjNKK0dpUUdJRTcxZldZOUtFQlFSMUQzT1h1TFlNZw==|7015dcf5d48280e56784ef6d89a2b4d15352adcb1e257453c9907a664ceaa0d9; captcha_ticket_v2=2|1:0|10:1736148810|17:captcha_ticket_v2|728:eyJ2YWxpZGF0ZSI6IkNOMzFfKkxBeEhrcDFRYnhkeGxtTGRnSlZZWVdHbjhtLlc4R3BmQWl5dFNLYlA1ekZITXYydi5KRypfa3plX3poZGJRRExveDlSR3lFVDJJbmQ4Q1ZHNnJFSWkqdyppMDZKMzlXYVZJcFlIX0VHc0ZRRDBsa1BvblJrNVJldWVDNFRNeFBXRmZZcXVJWHB1Yip0ckY1SWFQdVNoS0YyKjZmUHhUKnFiOXpDaFVsc0djdHVBX1hjWENfYkNQemlxREwwSWpWekdSZHlqWUFWQ0d5aE5TaWFzZEhzdWRDWCprYy5QKkh6ajV6VU9nM2lQT296YVBxSzlXemYqcXZzRF9ENWVPU2dGQmhoUWd3d3RZb3ByT0t0M0ZpVSp3SUZsc1FmZTVMRDJwSDhTcHBOZUF4VkhWYkVEdC4zVU1USkl3SjhRWCoqb0xrKnlhU2RudDNXOElfV01mMV84RzF1d05NeUpJS0YqcmJ3MTBsejNDX2lnMFJYM2FMUTBZT04ySDFqRkpZYlNCMCpfVjJseENYdmRPMEtZanJqTEh2b3RFbERnc2xzTDF4eS5TSWZSU3owY3kxRmFpU3hadkNxV00ubUJvbExKQy5JR1BvMG1uLmtNZHRuNElMMGx6NE9DcmdKMXFHeV81aUhUMGhNajZxVTRmdFlSU1JlNUxlbkJGWWdzcnZWZnFxNVk3N192X2lfMSJ9|9a0d71076f5273fc22dd67c3e4eabb975e479e875191d79a44e51972d2d848cc; z_c0=2|1:0|10:1736148810|4:z_c0|92:Mi4xN1lrbldnQUFBQUFBTUJKTENYQ1BHU1lBQUFCZ0FsVk5TdFZvYUFCUDI3aTJFNk5MNThBZ215bXIyZVJIWXhvNXN3|707e10b967760748115ffeee34231345d9323f18a7e61ff853b0d3cf9967dae2; ecom_merchant=1857114769787609088; BEC=6c53268835aec2199978cd4b4f988f8c",
            "Referer": `https://ecom.zhihu.com/vip-apps/out-distribution/contentLib/detail?&sectionId=${t_data.product_id}&workId=${t_data.product_id}&appId=${main_info.app_id}&media_channel_type=5`,
            "Referrer-Policy": "no-referrer-when-downgrade"
        };

        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
        }
    
        let postData = {
            "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,
        };
        console.log("postData:",postData)

        let response = await fetch("https://ecom.zhihu.com/api/km-agent/ad-link", {
            method: "POST",
            headers: headers,
            body: JSON.stringify(postData)
        });

        const data = await response.json();
        console.log('CMD.runTask:响应数据:', data);
        if(data.success!=true){
            throw data
        }
        let promotion_info = data.data
        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('CMD.runTask::响应状态:', response.status);
        console.log('t_data:',t_data)
        call_back(t_data,null)
    }catch(error){
        console.error('CMD.runTask:请求错误:', error);
        call_back(t_data,error)
        return null;
    }
}
module.exports = CMD;