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){
    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 = ""

    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 member_token = main_info.member_token
    let timestamp = helper.getCurrentUnixTimestamp()
    let postData = {
        "timestamp": `${timestamp}`,
        "app_id": config.zhihu_conifg.app_id,
        "data": {
            "member_token": member_token,
            "work_id": t_data.product_id,
            "media_channel_type": 5,
            "ad_link_name": `${t_data.product_name}_${main_info.id}`,
            "app_id": main_info.app_id,
            "callback_type": 0,
            "callback_rule_id": callback_rule_id,
            "payment_template_id": payment_template_id,
            "num": 1
        }
    }
    let sign = tools.zh_sign(JSON.stringify(postData),config.zhihu_conifg.app_secret)

    let client = tools.getOneNewClinet({
        "Content-Type":"application/json; charset=utf-8",
        "Accept":"application/json",
        "x-sign":sign
    })

    try{
        let response =  await client.post("https://open.zhihu.com/openapi/km-agent/v1/new-ad-link", postData )
        if(response.data.success!=true){
            throw response.data
        }

        // console.log("response.data.data:",response.data.data)
        let t_params = response.data.data.ad_link_list[0]
        let start_page = t_params.ad_link_url
        let start_param = t_params.ad_link_query
        t_data.promotion_id = t_params.ad_link_id
        t_data.start_page = start_page
        t_data.start_param = start_param
        call_back(t_data,null)
        return response.data;
    }catch(e){
        console.error('zh_create_link_new::请求错误:', e);
        call_back(t_data,error)
        return null;
    }

}

module.exports = CMD;