const axios = require('axios');
const cheerio = require('cheerio') // 类似jq，在node环境下操作dom
const qs = require('qs');

// const puppeteer = require('puppeteer')
// puppeteer chrome团队开发的一个node库，可以通过api来控制浏览器的行为(模拟浏览器)
const tranlate = async function(event, params) {
    const content = encodeURIComponent(params.content);
    const type = params.tranlateType || 'google';
    // const type = params.tranlateType || 'baidu';
    let result = '';
    switch (type) {
        case 'google':
            result = await googleSpider(content);
            break;
        case 'baidu':
            result = await baiduSpider(content);
            break;
        default:
            result = await googleSpider(content);
            break;
    }

    return result;
}

const googleSpider = async (content) => {
    try {
        const url = `https://translate.google.cn/m?sl=auto&tl=zh-CN&hl=zh-CN&q=${content}`;
        console.time("axios");
        const { data } = await axios.get(url, {
            headers: {
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.36'
            }
        })
        const $ = cheerio.load(data);
        console.timeEnd("axios");
        return $('.result-container').text()
    } catch (error) {
        console.log(error)
        return '无结果';
    }
}
// window.page
const baiduCommon = {
    token: "c53d5d394b4e8dbb2f9c217237e76da6",
    gtk: "320305.131321201"
}
// "c53d5d394b4e8dbb2f9c217237e76da6"
const baiduSign = (r) => {
    let i = null;
    function n(r, o) {
        for (var t = 0; t < o.length - 2; t += 3) {
            var e = o.charAt(t + 2);
            e = e >= "a" ? e.charCodeAt(0) - 87 : Number(e),
            e = "+" === o.charAt(t + 1) ? r >>> e : r << e,
            r = "+" === o.charAt(t) ? r + e & 4294967295 : r ^ e
        }
        return r
    }
    function a(r) {
        var t = r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
        if (null === t) {
            var a = r.length;
            a > 30 && (r = "" + r.substr(0, 10) + r.substr(Math.floor(a / 2) - 5, 10) + r.substr(-10, 10))
        } else {
            for (var C = r.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), h = 0, f = C.length, u = []; f > h; h++)
                "" !== C[h] && u.push.apply(u, e(C[h].split(""))),
                h !== f - 1 && u.push(t[h]);
            var g = u.length;
            g > 30 && (r = u.slice(0, 10).join("") + u.slice(Math.floor(g / 2) - 5, Math.floor(g / 2) + 5).join("") + u.slice(-10).join(""))
        }
        var l = void 0
        , d = "" + String.fromCharCode(103) + String.fromCharCode(116) + String.fromCharCode(107);
        l = null !== i ? i : (i = baiduCommon.gtk || "") || "";
        for (var m = l.split("."), S = Number(m[0]) || 0, s = Number(m[1]) || 0, c = [], v = 0, F = 0; F < r.length; F++) {
            var p = r.charCodeAt(F);
            128 > p ? c[v++] = p : (2048 > p ? c[v++] = p >> 6 | 192 : (55296 === (64512 & p) && F + 1 < r.length && 56320 === (64512 & r.charCodeAt(F + 1)) ? (p = 65536 + ((1023 & p) << 10) + (1023 & r.charCodeAt(++F)),
            c[v++] = p >> 18 | 240,
            c[v++] = p >> 12 & 63 | 128) : c[v++] = p >> 12 | 224,
            c[v++] = p >> 6 & 63 | 128),
            c[v++] = 63 & p | 128)
        }
        for (var w = S, A = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(97) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(54)), b = "" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(51) + ("" + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(98)) + ("" + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(102)), D = 0; D < c.length; D++)
            w += c[D],
            w = n(w, A);
        return w = n(w, b),
        w ^= s,
        0 > w && (w = (2147483647 & w) + 2147483648),
        w %= 1e6,
        w.toString() + "." + (w ^ S)
    }

    return a(r)
}

const getBaiduCookie = async (url) => {
    console.time("baiduSpiderCookie");
    const {data, ...res} = await axios.get('https://fanyi.baidu.com/', {
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
    });
    console.log(res)
    let cookie = res.headers['set-cookie'];
    console.timeEnd("baiduSpiderCookie");
    if(Array.isArray(cookie)) {
        return cookie.join(';')
    } else {
        return '';
    }
}

const baiduSpider = async (content, cookie) => {
    try {
         const url = 'https://fanyi.baidu.com/v2transapi?from=zh&to=en';
        // const url = 'https://fanyi.baidu.com/basetrans';
        // const data = {
        //     query: content,
        //     from: 'zh',
        //     to: 'en',
        //     token: baiduCommon.token,
        //     sign: baiduSign(content),

        // }

        const data = {
            from: 'zh',
            to: 'en',
            query: content,
            transtype: 'translang',
            simple_means_flag: '3',
            sign: baiduSign(content),
            token: baiduCommon.token,
            domain: 'common'
        }
        let Cookie = ''
        if(cookie) {
            Cookie = cookie;
        } else {
            Cookie = await getBaiduCookie(data, url);
        }

        if(!Cookie) {
            return '无结果';
        }



        console.time("baiduSpider");

        const result = await axios.post(url, qs.stringify(data), {
            headers: {
                // 'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
                'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
                Cookie
            }
        })
        console.log(result)
        let transRes = '无结果'

        if(Array.isArray(result.data.trans) ) {
            transRes = result.data.trans[0].dst || ''
        }

        // if(result.data.errno === 998) {
        //     return await baiduSpider(content, Cookie)
        // }

        console.timeEnd("baiduSpider");
        return transRes;
    } catch (error) {
        console.timeEnd("baiduSpider");
        console.log(error)
        return '无结果';
    }
}

// const tranlate = async function(event, params) {
// console.time("puppeteer");
    // if(!browser) {
    //     browser = await puppeteer.launch({
    //         // headless: false
    //         args: [
    //             '-disable-gpu', // GPU硬件加速
    //             '-disable-dev-shm-usage', // 创建临时文件共享内存
    //             '-disable-setuid-sandbox', // uid沙盒
    //             '-no-first-run', // 没有设置首页。在启动的时候，就会打开一个空白页面。
    //             '-no-sandbox', // 沙盒模式
    //             '-no-zygote',
    //             '-single-process' // 单进程运行
    //         ]
    //     });
    // }

    // const page = await browser.newPage();
    // await page.goto(url);
    // const container = await page.$('.result-container');
    // const html = await page.$eval('.result-container', e => e.outerText);
    // console.log("container===============")
    // console.log(html)
    // console.timeEnd("puppeteer");
    // await browser.close();
    // let url = `https://translate.google.cn/?sl=auto&tl=zh-CN&text=${content}&op=translate`;
// }


module.exports = tranlate;