const axios = require('axios');
const dns = require('dns').promises;
const qs = require('querystring');
const CMD = {}
async function addReferral(bookId, chapterId, adminId,bookName) {
    try {
        // 1. DNS解析
        const ip = await dns.resolve4('admin.wqxsw.com')
            .then(addresses => addresses[0])
            .catch(() => '47.101.128.171');

        // 2. 构建请求体
        const requestBody = {
            'row[admin_id]': adminId,
            'row[book_id]': bookId,
            'row[chapter_id]': chapterId,
            'row[chapter_name]': '第1章',
            'row[name]': bookName,
            'row[create_num]': 1,
            'row[media_source]': 'dy',  //抖音
            'extend[guide_chapter]': '',
            'extend[charge_switch]': 0,
            'extend[chapter_charge_start]': '',
            'extend[consume_type]': 1,
            'extend[chapter_kandian]': '',
            'extend[words_price]': '',
            'row[token]': '',
            'extend[xt_benefit]': '',
            'extend[jx_benefit]': '',
            'extend[vivo_ad_id]': '',
            'extend[vivo_ad_source]': '',
            'extend[vivo_access_token]': '',
            'extend[oppo_ad_id]': '',
            'extend[oppo_api_id]': '',
            'extend[oppo_api_key]': '',
            'extend[youkuAppKey]': '',
            'extend[youkuToken]': '',
            'extend[huaweiSecretKey]': '',
            'extend[wifiClientId]': '',
            'extend[wifiSecretKey]': '',
            'extend[appKey360]': '',
            'extend[secret360]': '',
            'extend[jzqs]': '',
            'extend[sph_id]': '',
            'extend[sp_id]': '',
            'row[callbacktype]': 1,
            'row[callback_config_id]': 368330,  //回传id
            'row[recharge-template-type]': 1,
            'row[referral_goods_batch_id]': 18438416   //充值模板id
        };

        // 3. 构建请求配置
        const config = {
            baseURL: `https://${ip}`,
            url: '/admin/referral/referral/add',
            method: 'post',
            headers: {
                'Host': 'admin.wqxsw.com',
                'accept': 'application/json, text/javascript, */*; q=0.01',
                '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/x-www-form-urlencoded; charset=UTF-8',
                'x-requested-with': 'XMLHttpRequest',
                'cookie': 'PHPSESSID=gaucu8us1dmvsjstqfgtp3676a; keeplogin=61920%7C604800%7C1734659746%7C2e8827290dda8e35651c20483ee07396',
                'Referer': `https://admin.wqxsw.com/admin/referral/referral/add?book_id=${bookId}&chapter_id=${chapterId}&dialog=1`
            },
            params: {
                book_id: bookId,
                chapter_id: chapterId,
                dialog: 1
            },
            data: qs.stringify(requestBody),
            httpsAgent: new (require('https').Agent)({
                rejectUnauthorized: false,
                servername: 'admin.wqxsw.com'
            }),
            validateStatus: function (status) {
                return status >= 200 && status < 500;
            }
        };

        // 4. 发送请求
        const response = await axios(config);

        // 5. 处理响应
        if (response.status === 200) {
            return response.data;
        } else {
            throw new Error(`请求失败，状态码: ${response.status}`);
        }

    } catch (error) {
        console.error('添加推荐失败:', {
            message: error.message,
            code: error.code,
            response: error.response?.data
        });
        throw error;
    }
}

// 使用示例
async function main() {
    try {
        const bookId = '11010287703';
        const chapterId = '1';
        const adminId = '61920'; //channelId
        
        const result = await addReferral(bookId, chapterId, adminId);
        console.log('添加推荐成功:', result);
    } catch (error) {
        console.error('操作失败:', error.message);
    }
}

// 如果直接运行此文件
if (require.main === module) {
    main();
}

module.exports = CMD;