const axios = require('axios');
const querystring = require('querystring');
const config = require("../../../etc/config.json")
const helper = require('../../helper');
const https = require('https');
const CMD = {}
const temp_cookie = "sid_guard=0d424ef5ee435761fbd369beeb3077b9%7C1746095725%7C5184000%7CMon%2C+30-Jun-2025+10%3A35%3A25+GMT; sessionid=0d424ef5ee435761fbd369beeb3077b9"
CMD.search_id = async function(bookId,distributorId){
    const postData = {
        distributor_id: distributorId,
        ts: helper.getCurrentUnixTimestamp(),
        sign: helper.getSign(distributorId,config.fanqie_config.secretKey),
        book_id: bookId
    };

    var url = `https://www.changdunovel.com/novelsale/openapi/content/book_meta/v1/?distributor_id=${postData.distributor_id}&ts=${postData.ts}&sign=${postData.sign}&book_id=${postData.book_id}`
    console.log("url",url)
    let response =  await axios.get(url)
    return response.data
    
}
// 设置 Cookie
CMD.search_name = function(keyword){
    // 搜索关键词
    const encodedKeyword = encodeURIComponent(keyword); // 对关键词进行 URL 编码

    // 设置正确的 Cookie 字符串
    const cookie = 'passport_csrf_token=82f80619e2d3c3eb0aa7962d7c94305e; sid_tt=c00d65a0717e75e79ad8aecaa82f4064; sessionid=c00d65a0717e75e79ad8aecaa82f4064';

    // 设置请求的 URL
    const url = `https://www.changdunovel.com/novelsale/distributor/content/book/list/v1?permission_statuses=3,4&search_type=2&query=${encodedKeyword}&page_index=0&page_size=10`;

    // 设置请求头
    const headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        'Agw-Js-Conv': 'str',
        'Appid': '546801',
        'Apptype': '1',
        'Cache-Control': 'no-cache',
        'Cookie': cookie,
        'Distributorid': '1814786227164185',
        'Pragma': 'no-cache',
        'Priority': 'u=1, i',
        'Referer': `https://www.changdunovel.com/sale/novel/list?permission_statuses=3%2C4&search_type=2&query=${encodedKeyword}&page_index=1&page_size=10`,
        'Sec-Ch-Ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
        'Sec-Ch-Ua-Mobile': '?0',
        'Sec-Ch-Ua-Platform': '"macOS"',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
        'X-Secsdk-Csrf-Token': 'DOWNGRADE'
    };

    // 执行请求
    axios.get(url, { headers })
    .then(response => {
        console.log(response.data); // 输出结果
    })
    .catch(error => {
        console.error('Error:', error.message); // 输出错误信息
    });
}

CMD.search_new_id = async function(bookId,call_back){
    const fetch = require('node-fetch');

    const url = `https://www.changdunovel.com/novelsale/distributor/content/book/list/v1?permission_statuses=3%2C4&search_type=5&query=${bookId}&page_index=0&page_size=10&msToken=Y1ycMk3xTJj-ZZNpi5dVCcNHYRw7NKehmunCGftKYr_s0if-k5jcQlON71uUe7MB2KjvNRoGYmT3xq4s82yZfH9s2gV4Fpun-grz__CT9spTPzqlrZ_y2K6wLJy7g3WR0o6hmxY5_pBG1yoAPghBO6HMNFQoJaiLMV8Mr__5LVqqpg%3D%3D&a_bogus=Ey4jDttwmZR5apAGuCktelelzSDMr0uy8-ToStJy9Oq-GqlO9YefdaGkjoKmDjFU5upZpSIHAn4MKdxcQKwiZHQpKmZfuEhRST9Vn0sL8Z7mGPJZVNbmSiSoKJiG%2F5REO%2FavxM0WltmOZd%2F1pNd%2FM5a7u%2FXomcSBRw9TfxXGE1qh6Pht78f%3D`;
    
    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',
      'agw-js-conv': 'str',
      'appid': '40013175',
      'apptype': '8',
      'distributorid': '1826185708850233',
      'priority': 'u=1, i',
      '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',
      'x-secsdk-csrf-token': '000100000001914e91f95f8129843d7ae581c2ae522b975d3994a1f71be6a7a9e478964baf7a183ba7abea3a9c09',
      'cookie': temp_cookie,
      'Referer': 'https://www.changdunovel.com/sale/novel/list?permission_statuses=3%2C4&search_type=5&query=7382805882943310874&page_index=1&page_size=10',
      'Referrer-Policy': 'strict-origin-when-cross-origin'
    };
    
    let response = await fetch(url, {
      method: 'GET',
      headers: headers
    })
    let data = await response.json()
    if(data.code==0){
        return data.data[0]
    }
    return ""
}


CMD.search_mf_new_id = async function(bookId){
  return new Promise((resolve, reject) => {
    const options = {
        hostname: 'www.changdunovel.com',
        path: '/novelsale/distributor/content/book/list/v1',
        method: 'GET',
        headers: {
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'agw-js-conv': 'str',
            'appid': '40017687',
            'apptype': '15',
            'distributorid': '1819222136130603',
            'priority': 'u=1, i',
            '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',
            'x-secsdk-csrf-token': '000100000001914e91f95f8129843d7ae581c2ae522b975d3994a1f71be6a7a9e478964baf7a183ba7abea3a9c09',
            'cookie': temp_cookie
        }
    };

    // 构建查询参数
    const params = new URLSearchParams({
        permission_statuses: '3,4',
        search_type: '6',
        query: `${bookId}`,
        page_index: '0',
        page_size: '1',
        msToken: 'QtOXD1IEPGNjuwS8Lzzew68qWnqxmVU10gPxOLcbijTXMmshIe_toySxUmiovwVBez7c8O3QcscyRES2_uC',
        a_bogus: 'mf0RheSEOx/nKpltmKsUeUHUEy2MrzuyDBTKRijyeNxpTZMaA8eeNOc9rxumZFaaeYpNZSMHUn-AznrcOcwwZ7HpKskvui7RtG9I98so8ZH3bBJg9r6MCGGoqkke/cWE85ltx9011UfO1nclk3dKMp3Jo/4qQODdRJ9zfPvax1q6640a7s8='
    });

    options.path += `?${params.toString()}`;

    const req = https.request(options, (res) => {
        let data = '';

        res.on('data', (chunk) => {
            data += chunk;
        });

        res.on('end', () => {
            try {
                const parsedData = JSON.parse(data);
                if(parsedData.code!=0){
                 resolve("");
                 return
                }
                if(parsedData.data.length<=0){
                  resolve(null);
                  return
                }
                resolve(parsedData.data[0]);
            } catch (e) {
                console.error('JSON parsing error:', e);
                reject(e);
            }
        });
    });

    req.on('error', (error) => {
        console.error('Request error:', error);
        reject(error);
    });

    // 设置请求超时
    req.setTimeout(10000, () => {
        req.destroy();
        reject(new Error('Request timeout'));
    });

    req.end();
});
}

module.exports = CMD;