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

const axios = require('axios');
async function fetchImage(image,file_name) {
    try {
        // 1. 先获取新的session
        const prehandleResponse = await axios({
            url: 'https://turing.captcha.qcloud.com/cap_union_prehandle',
            method: 'GET',
            params: {
                aid: '2026859470',
                protocol: 'https',
                accver: '1',
                showtype: 'popup',
                ua: 'TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzEzMi4wLjAuMCBTYWZhcmkvNTM3LjM2',
                callback: '_aq_88765'
            }
        });

        // 2. 解析JSONP响应获取新session
        const jsonpData = prehandleResponse.data;
        const jsonStr = jsonpData.replace(/^_aq_88765\((.*)\)$/, '$1');
        const data = JSON.parse(jsonStr);
        const newSess = data.sess;

        console.log('New session:', newSess);

        // 3. 使用新session请求图片
        const response = await axios({
            url: `https://turing.captcha.qcloud.com/cap_union_new_getcapbysig`,
            method: 'GET',
            params: {
                img_index: file_name,
                image: image,
                sess: newSess
            },
            responseType: 'arraybuffer',
            headers: {
                'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
                'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
                'Referer': 'https://turing.captcha.gtimg.com/',
                'Origin': 'https://turing.captcha.gtimg.com',
                'Connection': 'keep-alive',
                'Cache-Control': 'no-cache'
            },
            timeout: 5000,
            maxRedirects: 5,
            validateStatus: function (status) {
                return status >= 200 && status < 300;
            }
        });

        console.log('Response status:', response.status);
        console.log('Response headers:', response.headers);
        console.log('Data length:', response.data.length);

        if (response.data.length === 0) {
            throw new Error('Empty response received');
        }

        // 保存图片
        // await fs.writeFile('captcha.png', response.data);
        console.log('Image saved successfully',response.data);
        const imgPath = `${folder}/${file_name}.png`;
        fs.writeFileSync(imgPath, response.data);
        return response.data;

    } catch (error) {
        console.error('Error:', error);
        if (error.response) {
            console.error('Response status:', error.response.status);
            console.error('Response headers:', error.response.headers);
        }
        throw error;
    }
}


CMD.get_captcha = async function(){
    let response = await fetch("https://turing.captcha.qcloud.com/cap_union_prehandle?aid=2026859470&protocol=https&accver=1&showtype=popup&ua=TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzEzMi4wLjAuMCBTYWZhcmkvNTM3LjM2IEVkZy8xMzIuMC4wLjA%3D&noheader=1&fb=1&aged=0&enableAged=0&enableDarkMode=0&grayscale=1&clientype=2&cap_cd=&uid=&lang=zh-cn&entry_url=https%3A%2F%2Fopen.yuewen.com%2F&elder_captcha=0&js=%2Ftcaptcha-frame.c055d939.js&login_appid=&wb=1&subsid=5&callback=_aq_88765&sess=", {
      "headers": {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "sec-ch-ua": "\"Not A(Brand\";v=\"8\", \"Chromium\";v=\"132\", \"Microsoft Edge\";v=\"132\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "script",
        "sec-fetch-mode": "no-cors",
        "sec-fetch-site": "cross-site",
        "Referer": "https://open.yuewen.com/",
        "Referrer-Policy": "strict-origin-when-cross-origin"
      },
      "body": null,
      "method": "GET"
    });
    // 获取响应文本
    const text = await response.text();
    console.log("response.data:",text)
    let img_config = helper.parseJsonP(text)
    fetchImage(img_config.img_url_0,0)
    fetchImage(img_config.img_url_1,1)
    console.log("img_config:",img_config)
}
CMD.yw_login = async function() {
  try{
      let OPENSESSID = await redis_help.getKeyValue("OPENSESSID")
      let response = await fetch("https://open.yuewen.com/api/account/login", {
        "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;charset=UTF-8",
          "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",
          "x-csrf-token": "vEQbWeNTNVpt2aruM6_NwIpT",
          "cookie": `Hm_lvt_990f9ab9737a266517417cc2949bb3f4=1736394515; csrfToken=vEQbWeNTNVpt2aruM6_NwIpT; is_read_notice=6785cfb62a9ac; sidebarStatus=1; OPENSESSID=${OPENSESSID}`,
          "Referer": "https://open.yuewen.com/",
          "Referrer-Policy": "strict-origin-when-cross-origin"
        },
        "body": "{\"account\":\"zywz2024013@163.com\",\"verifyTicket\":\"tr03Rw2aTt3euItO1WvEU_aUhviMBXhMXfblige5c1XDKqyTOucVQHSJv7W_87606d9HvJvGim7l4WAGXY-b0C4eueAquXQlUvM5c3k8Jfxet8oS0I-vjKfVGsZCYzTuVVIf\",\"randStr\":\"@NQ6\",\"password\":\"Huang888888\"}",
        "method": "POST"
      });



      console.log('-'.repeat(50));
      response.headers.forEach((value, key) => {
          console.log(`${key}: ${value}`);
      });
      let cookie = response.headers.get('set-cookie')
      console.log("cookie:",cookie)

      const match = cookie.match(/OPENSESSID=([^;]+)/);
      if (match && match[1]) {
          OPENSESSID = match[1]
          console.log('OPENSESSID值:', match[1]);
          // redis_help.setKeyValue("OPENSESSID",OPENSESSID)
      }
      const data = await response.json();
      console.log('响应状态:', response.status);
      console.log('响应数据:', data);
  }catch(e){

  }
}

module.exports = CMD;