
const fetch = require('node-fetch'); // Node.js 18以下版本需要安装 node-fetch
const tools = require('../../../tools');
const config  = require('../../../etc/config.json');
const helper = require('../../helper');
const crypto = require('crypto');
const CMD = {}

async function getPanelGroupDetail(mini_program_platform_id,qm_id) {
    try {
        let param_list = qm_id.split(',')
        let app_external_id = param_list[1]
        let target_id = param_list[0]
        let project = ""
        if(mini_program_platform_id==config.wx){
            project = "reader_paid_wxminiapp"
        }else if(mini_program_platform_id==config.dy){
            project = "reader_paid_dyminiapp"
        }
        const response = await fetch("https://new-media-fx.qimao.com/api/charge-configure/panel-group/list?name=&page=1&page_size=50&env=&t=1746011001781", {
            headers: {
                "accept": "application/json, text/plain, */*",
                "app-external-id": `${app_external_id}`,
                "target-id": `${target_id}`,
                "authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SUQiOjU0NDA1NjQxNjM3MTI4MjExMSwiQWNjb3VudE5hbWUiOiJ6aHVveXVlIiwiVGltZVN0YW1wIjoxNzQ2MDA4MDM3LCJDbGllbnRJUCI6IjEyMS4zMy4yMTcuMjE4IiwiQnVmZmVyVGltZSI6MCwiZXhwIjoxNzQ2MDk0NDM3LCJpc3MiOiJxbV9uZXdfbWVkaWFfZngiLCJuYmYiOjE3NDYwMDgwMzcsIkVudiI6InJlbGVhc2UiLCJJc1NpbXVsYXRpb25Mb2dpbiI6ZmFsc2V9._TsiA0wcWU_g7baeeg2Khc1IFZ7JvUDmDV-wsYXHUZA",
                "project": `${project}`,
                "signature": "4813f70615a44e684c562a5df51e884f14a3bc7c4f84c32fbf3e3beccd326c20",
            }
        });

        const data = await response.json();

        if(data.code!=200){
            throw data
        }
        
        console.log('响应状态:', response.status);
        console.log('响应数据:', data);
        return data.data;
    } catch (error) {
        console.error('Error:', error);
        return null
    }
}

CMD.get_recharge_template_new = async function(mini_program_platform_id=config.dy,qm_id){
    try{
        let client = tools.getOneNewClinet()
        let uuid = tools.generateCryptoNumericUUID()
        let timestamp = helper.getCurrentUnixTimestamp()
        const baseUrl = config.qimao_config.recharge_list_host_new;
        const params = {
            access_key: config.qimao_config.access_key,
            admin_account_name:"zhuoyue",
            project:mini_program_platform_id==config.wx?8:6,     // 6 抖音小程序  8 微信小程序
            random: uuid,
            timestamp: timestamp,
            page_size:100,
        };

        // appid:"tt79e30f5ee6d455b601",
        // page:1,
        // page_size:20,
    
        const sortedParams = Object.keys(params)
        .sort()
        .map(key => `${key}=${params[key]}`)
        .join('&');
    
        const secretKey = config.qimao_config.secret_key;
    
        const sign = crypto.createHash('md5')
                .update(sortedParams + secretKey)
                .digest('hex');
        const finalUrl = `${baseUrl}?${sortedParams}&sign=${sign}`;
    
        console.log("finalUrl:",finalUrl)
        let response =  await client.get(finalUrl)
            
        if(response.data.code!=0){
            throw response.data
        }

        return response.data
    }catch(e){
        console.error("get_recharge_template_new:",e)
        return null
    }finally{

    }
}
//  "category": "1" 复充充值模板
//  "category": "0" 首充充值模板
CMD.get_recharge_template = async function (category,mini_program_platform_id=config.dy,qm_id) {
    return await getPanelGroupDetail(mini_program_platform_id,qm_id)
    const url = '"https://new-media-fx.qimao.com/api/charge-configure/panel-group/detail';
    // 请求参数
    const params = new URLSearchParams({
        env: '',
        id:"1",
        // t: Date.now()  // 当前时间戳
        t:"1746009119073"
    });

    let param_list = qm_id.split(',')
    let app_external_id = param_list[1]
    let target_id = param_list[0]
    // 请求头
    const dy_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',
        'app-external-id': `${app_external_id}`,
        'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SUQiOjU0NDA1NjQxNjM3MTI4MjExMSwiQWNjb3VudE5hbWUiOiJ6aHVveXVlIiwiVGltZVN0YW1wIjoxNzQ2MDA4MDM3LCJDbGllbnRJUCI6IjEyMS4zMy4yMTcuMjE4IiwiQnVmZmVyVGltZSI6MCwiZXhwIjoxNzQ2MDk0NDM3LCJpc3MiOiJxbV9uZXdfbWVkaWFfZngiLCJuYmYiOjE3NDYwMDgwMzcsIkVudiI6InJlbGVhc2UiLCJJc1NpbXVsYXRpb25Mb2dpbiI6ZmFsc2V9._TsiA0wcWU_g7baeeg2Khc1IFZ7JvUDmDV-wsYXHUZA',
        'project': 'reader_paid_dyminiapp',
        'signature': '404c548f1a3c610ec1202b5eb02c78f32bdf4cbbc2e240b38c0318426114e478',
        'target-id': ``,
        
        'cookie': 'sensorsdata2015jssdkcross=%7B%22%24device_id%22%3A%22193bdc124645e2-0cbeaee172d4ce8-4c657b58-921600-193bdc12465567%22%7D; sa_jssdk_2015_new-media-fx_qimao_com=%7B%22distinct_id%22%3A%22193bdc124645e2-0cbeaee172d4ce8-4c657b58-921600-193bdc12465567%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E5%BC%95%E8%8D%90%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%2C%22%24latest_referrer%22%3A%22http%3A%2F%2F120.79.128.142%3A4999%2F%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTkzYmRjMTI0NjQ1ZTItMGNiZWFlZTE3MmQ0Y2U4LTRjNjU3YjU4LTkyMTYwMC0xOTNiZGMxMjQ2NTU2NyJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%7D; acw_tc=0a47329d17393406161785226e003325543a1cc53c490ed7b4e24f2bfb2387',
        'Referer': `https://new-media-fx.qimao.com/backend/recharge-configuration/index?projectId=reader_paid_dyminiapp&appId=${app_external_id}&accountId=${target_id}`
    };

    const wx_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",
        'app-external-id': `${app_external_id}`,
        "authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBY2NvdW50SUQiOjU0NDA1NjQxNjM3MTI4MjExMSwiQWNjb3VudE5hbWUiOiJ6aHVveXVlIiwiVGltZVN0YW1wIjoxNzQ2MDA4MDM3LCJDbGllbnRJUCI6IjEyMS4zMy4yMTcuMjE4IiwiQnVmZmVyVGltZSI6MCwiZXhwIjoxNzQ2MDk0NDM3LCJpc3MiOiJxbV9uZXdfbWVkaWFfZngiLCJuYmYiOjE3NDYwMDgwMzcsIkVudiI6InJlbGVhc2UiLCJJc1NpbXVsYXRpb25Mb2dpbiI6ZmFsc2V9._TsiA0wcWU_g7baeeg2Khc1IFZ7JvUDmDV-wsYXHUZA",
        "project": "reader_paid_wxminiapp",
        "sec-ch-ua": "\"Microsoft Edge\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
        "sec-ch-ua-mobile": "?1",
        "sec-ch-ua-platform": "\"Android\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "signature": "194eb06913ef6d5b2cd45d5658f0ca2464d8ea67158ee81ab66b17992446a24e",
        "target-id": "",
        "cookie": "sensorsdata2015jssdkcross=%7B%22%24device_id%22%3A%22193bdc124645e2-0cbeaee172d4ce8-4c657b58-921600-193bdc12465567%22%7D; sa_jssdk_2015_new-media-fx_qimao_com=%7B%22distinct_id%22%3A%22193bdc124645e2-0cbeaee172d4ce8-4c657b58-921600-193bdc12465567%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E5%BC%95%E8%8D%90%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%2C%22%24latest_referrer%22%3A%22http%3A%2F%2F120.79.128.142%3A4999%2F%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTkzYmRjMTI0NjQ1ZTItMGNiZWFlZTE3MmQ0Y2U4LTRjNjU3YjU4LTkyMTYwMC0xOTNiZGMxMjQ2NTU2NyJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%7D; acw_tc=0aef832217460080378292172e00524a7f76928c9ddbb68a937b2c3f32083d",
        "Referer": "https://new-media-fx.qimao.com/backend/minapp-configuration/recharge?projectId=reader_paid_wxminiapp&appId=9a2737aabb8f11ef93f90293e6ac97a2&accountId=0",
        "Referrer-Policy": "strict-origin-when-cross-origin"
    };
    let headers = ""
    if(mini_program_platform_id==config.wx){
        headers = wx_headers
    }else if(mini_program_platform_id==config.dy){
        headers = dy_headers
    }
    // headers['authorization'] = await tools.getQMToken()
    try {
        url = `${url}?${params}`
        console.log("url:",url)
        const response = await fetch(url, {
            method: 'GET',
            headers: headers
        });

        const data = await response.json();

        if(data.code!=200){
            throw data
        }
        
        console.log('响应状态:', response.status);
        console.log('响应数据:', data);
        return data.data;
    } catch (error) {
        console.error('请求错误:', error);
        throw error;
    }
}

// Node.js 18及以上版本可以直接运行
// Node.js 18以下版本需要先安装 node-fetch:
// npm install node-fetch@2

module.exports = CMD;