//执行一个创建点众链接任务
const axios = require('axios');
const helper = require('../src/helper');
const config = require('../etc/config.json')
const HttpClient = require('../src/HttpClient')
const CMD = {}

CMD.runTask = async function(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 recharge_template_id = ""
    let call_back_template_id = ""
    let timestamp = helper.getCurrentUnixTimestamp()
    let signKey = helper.md5(config.dianzhong_config.clientId+config.dianzhong_config.token+timestamp)
    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
        }
      }

    try {
        let client = new HttpClient()
        let clientId= config.dianzhong_config.clientId;
        let bookId = data.product_id;
        let chapterIdx = 1;
        let name = data.product_name;
        let mediaSource = "dy";
        let channelId = main_info.channelId;
        let batchId = recharge_template_id;
        let CallbackConfigId = call_back_template_id;
        let fromDrId = "zywzfromDrId";
        let chapterChargeStart = 1;
        let chapterKandian = 1;
        let postData ={
            signKey:signKey,
            clientId:clientId,
            timestamp:timestamp,
            bookId:bookId,
            chapterIdx:chapterIdx,
            name:`${name}${main_info.id}`,
            mediaSource:mediaSource,
            channelId:channelId,
            batchId:batchId,
            CallbackConfigId:CallbackConfigId,
            fromDrId:fromDrId,
            chapterChargeStart:chapterChargeStart,
            chapterKandian:chapterKandian
        }

        // console.log("postData:",postData)
        let response =  await client.post(config.dianzhong_config.create_link_host,postData)

        if(response.code!=1){
            throw response
        }
        let params = response.data.path.split('?')
        let start_page = params[0]
        let start_param = params[1]
        let promotion_id = response.data.referralId
        data.start_page = start_page
        data.start_param = start_param
        data.promotion_id = promotion_id
        // console.log("response:",response)
        call_back(data,null)
    } catch (error) {
        call_back(data,error)
        console.error('dz_create_link :Error:', error);
        // 处理错误
    }

}

module.exports = CMD;