const helper = require('../../helper');
const config = require('../../../etc/config.json');
const HttpClient = require('../../HttpClient');
const CMD = {}
//book_id=书籍id
//index=第几章开始生成推广链。
//promotion_name=推广链接名称
//media_source=快应用：1 字节、2 腾讯、6 vivo，不填默认字节；H5：不需要填写 短剧：1 字节、3 快手 4 微信
CMD.send = async function(book_id,index=1,promotion_name="",media_source=1,recharge_template_id,call_back){
    var distributorId = config.fanqie_config.distributorId;
    var secretKey = config.fanqie_config.secretKey;
    const postData = {
        distributor_id: distributorId,
        ts: helper.getCurrentUnixTimestamp(),
        sign: helper.getSign(distributorId,secretKey),
        book_id: book_id,
        index:index,
        promotion_name:promotion_name,
        media_source:media_source,
        recharge_template_id:recharge_template_id
    };
    var url = config.fanqie_config.create_link_host
    var base_params = `/?distributor_id=${postData.distributor_id}&ts=${postData.ts}&sign=${postData.sign}`
    var other_params = `&book_id=${postData.book_id}&index=${postData.index}&promotion_name=${postData.promotion_name}&media_source=${postData.media_source}&recharge_template_id=${postData.recharge_template_id}`
    let clinet = new HttpClient()
    try{
        let response = await clinet.request(`${url}${base_params}${other_params}`)
        // 检查响应是否存在
        if (!response) {
            throw new Error('No response received');
        }
        if(response.promotion_url==undefined){
            if(response.code==4000){
                console.log("response promotion_name:",promotion_name)
            }else{
                console.log("response :",response)
            }
            call_back(null,null, response)
        }else{
            let params = response.promotion_url.split('?')
            let start_page = params[0]
            let start_param = params[1]
            if(call_back!=null){
                call_back(start_page,start_param, response)
            }
        }
    }catch(e){
        console.log("create_fanqie_book_link error:",e)
    }

}


module.exports = CMD;