const fetch = require('node-fetch'); // Node.js 18以下版本需要安装 node-fetch
const helper = require('../src/helper');
const config = require('../etc/config.json');
const redis_help = require('../src/use_redis');
const CMD = {}
CMD.get_promotion_id_by_name = async function(name,yw_id) {
    try {
        let OPENSESSID = await redis_help.getKeyValue("OPENSESSID")
        let timestamp = helper.getCurrentUnixTimestamp()
        await require('../src/api/yw/switchApp').switchApp(yw_id)
        const response =  await fetch(`https://open.yuewen.com/api/miniappspread/getPromotionList?recycle=0&startdate=&enddate=&name=${name}&id=&content_type=0&page=1&channeltype=1&pagename=`, {
            "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",
                "priority": "u=1, i",
                "sec-ch-ua": "\"Microsoft Edge\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"Windows\"",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-origin",
                "cookie": `Hm_lvt_990f9ab9737a266517417cc2949bb3f4=${timestamp}; csrfToken=vEQbWeNTNVpt2aruM6_NwIpT; OPENSESSID=${OPENSESSID}; yw_open_token=67dab7f35b593; is_read_notice=67dab7f35b593; sidebarStatus=1`,
                "Referer": "https://open.yuewen.com/new/library",
                "Referrer-Policy": "strict-origin-when-cross-origin"
            },
            "body": null,
            "method": "GET"
        });

        const data = await response.json();

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

CMD.test = async function() {
    // 设置请求头
    const 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",
        "content-type": "application/json",
        "priority": "u=1, i",
        "sec-ch-ua": "\"Microsoft Edge\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "cookie": "Hm_lvt_990f9ab9737a266517417cc2949bb3f4=1736394515; csrfToken=xKm-Q0k0vYm1SvdsRLP_kXsG; OPENSESSID=e055148579455596ff9d10d1b2c72024; yw_open_token=6787602677bbd; is_read_notice=6787602677bbd; sidebarStatus=0",
        "Referer": "https://open.yuewen.com/new/library",
        "Referrer-Policy": "strict-origin-when-cross-origin"
    };

    // 设置请求体
    const requestBody = {
        "cost": 0,
        "name": "ceshi2222",
        "cbid": "30554680307186706",
        "ccid": "82019595711479505",
        "page_name": "《渣男犯了错》第1章 01",
        "channel_charge_setting": {
            "id": 478,
            "name": "29.9元",
            "tenantId": 80091658,
            "create_time": 1736829123000,
            "update_time": 1736829123000,
            "creator": "zyw****4013@163.com",
            "updater": "zyw****4013@163.com",
            "details": [
                // VIP月度会员
                {
                    "vip_type": 1,
                    "origin": 4485,
                    "price": 2990,
                    "gift": 0,
                    "charge_desc": "1个月会员",
                    "gift_desc": "仅0.96元/天",
                    "bg_color": 0,
                    "tag_color": 0,
                    "tag_txt": "",
                    "tag_type": 0,
                    "tag_position": 0,
                    "pay_id": 1,
                    "first_charge": 0,
                    "vip_charge_setting": {
                        "type": 2,
                        "dprice": 96,
                        "quantity": 31,
                        "product_id": "com.miniappvip.month.31days",
                        "label_id": 0,
                        "user_filter": 0,
                        "rule_id": 0,
                        "first_period_conf": []
                    },
                    "charge_setting_type": 1
                },
                // 其他会员配置...
            ]
        },
        "backup_book_status": 2,
        "channel_type": 1,
        "force_style": "1"
    };

    // 发起请求
    let response = await fetch("https://open.yuewen.com/api/miniappspread/addH5Spread", {
        method: "POST",
        headers: headers,
        body: JSON.stringify(requestBody)
    });

    console.log("response:",response)
}
CMD.runTask = async function(t_data,main_info,PlatformInfo,call_back){
    try{
        let chapter_info = await require('../src/api/yw/get_book_tg_chapter_id').get_book_tg_chapter_id(t_data.product_id)
        console.log("main_info.yw_id:",main_info.yw_id)
        console.log("chapter_info:",chapter_info)
        await require('../src/api/yw/switchApp').switchApp(main_info.yw_id)
        let timestamp = helper.getCurrentUnixTimestamp()
        let tg_link_config = JSON.parse(main_info.tg_link_config)
        let chongzhi_id = tg_link_config['chongzhi_id']
        let chongzhi_list = JSON.parse(PlatformInfo.chongzhi)
        let channel_charge_setting = ""
 
        for (let index = 0; index < chongzhi_list.length; index++) {
            const cz_obj = chongzhi_list[index];
            if(cz_obj.id==chongzhi_id){
                channel_charge_setting = cz_obj.value
              break
            }
        }

        if(chapter_info==null){
            throw {"error_info":"get_book_tg_chapter_id error!"}
        }
        let promotion_name = `${t_data.product_name}_${timestamp}`
        let create_time = Date.now()
        // let postData = {
        //     cost:"0",
        //     name:promotion_name,
        //     cbid:t_data.product_id,
        //     ccid:chapter_info.ccid,
        //     page_name:`《${t_data.product_name}》第1章`,
        //     channel_charge_setting:channel_charge_setting,
        //     backup_book_status:"2",
        //     channel_type:"1",
        //     force_style:"1"
        // }
        let OPENSESSID = await redis_help.getKeyValue("OPENSESSID")
        console.log("OPENSESSID:",OPENSESSID)
        const 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",
            "content-type": "application/json",
            "priority": "u=1, i",
            "sec-ch-ua": "\"Chromium\";v=\"134\", \"Not:A-Brand\";v=\"24\", \"Microsoft Edge\";v=\"134\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "cookie": `Hm_lvt_990f9ab9737a266517417cc2949bb3f4=${timestamp}; csrfToken=ffZRRnqo6A4ngGbvAVP_zK5_; OPENSESSID=${OPENSESSID}; yw_open_token=67db7bcd069db; is_read_notice=67db7bcd069db; sidebarStatus=0`,
            "Referer": "https://open.yuewen.com/new/library",
            "Referrer-Policy": "strict-origin-when-cross-origin"
        };
        let postData = {
            "cost": 0,
            "name": `${promotion_name}_${main_info.id}`,
            "cbid": t_data.product_id,
            "ccid": chapter_info.ccid,
            "page_name": `《${t_data.product_name}》第1章 01`,
            "channel_charge_setting": {
                "id": channel_charge_setting.id,
                "name": channel_charge_setting.name,
                "tenantId": channel_charge_setting.tenantId,
                "create_time": create_time,
                "update_time": create_time,
                "creator": "gzz****03@163.com",
                "updater": "gzz****03@163.com",
                "details":channel_charge_setting.details
            },
            "backup_book_status": 2,
            "channel_type": 1,
            "force_style": "1"
        };
        console.log("postData:",postData)

        let response = await fetch("https://open.yuewen.com/api/miniappspread/addH5Spread", {
            method: "POST",
            headers: headers,
            body: JSON.stringify(postData)
        });

        const data = await response.json();

        if(data.code!=0){
            throw data
        }
        let promotion_info = await CMD.get_promotion_id_by_name(promotion_name,main_info.yw_id)
        let t_params = promotion_info.path.split('?')
        let start_page = t_params[0]
        let start_param = t_params[1]
        t_data.promotion_id = promotion_info.id
        t_data.start_page = start_page
        t_data.start_param = start_param
        console.log('CMD.runTask::响应状态:', response.status);
        console.log('CMD.runTask:响应数据:', data);
        console.log('t_data:',t_data)
        call_back(t_data,null)
    }catch(error){
        console.error('CMD.runTask:请求错误:', error);
        call_back(t_data,error)
        return null;
    }
}
module.exports = CMD;