import log4js from 'log4js'
import {bl, genUuid, ht, ie, Ol, randint, se} from "./utils.js"
import axios from "axios";
import {PxEnv} from './px.js'
import {MongoClient} from "mongodb";
import * as fs from "fs";

const plt = process.platform;
let ENVS = JSON.parse(fs.readFileSync('./env.json', 'utf-8').toString())
let keys = Object.keys(ENVS);
// const uri = "mongodb://lcc-spider:JIUsfhiad&^@54.183.159.9:27017/?authSource=admin&directConnection=true";
const uri = 'mongodb://root:123456@192.168.50.110:27017/'
const client = new MongoClient(uri);

log4js.levels.INFO.colour = 'white';
// console.log(log4js.levels.INFO.colour);
log4js.configure({
    appenders: {
        out: {
            type: 'stdout', layout: {
                colored: true,
                type: 'pattern',
                pattern: '%[%d{yyyy-MM-dd hh:mm:ss.SSS}] [%l:%C:%M] [%p] %c - %m',
            }
        },
    },
    categories: {
        default: {appenders: ['out'], level: "trace", enableCallStack: true}
    }

});

async function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

class PxBypass {
    tag = "v8.9.6"
    ft = "330"

    get ua() {
        return this._ua;
    }

    set ua(v) {
        this._ua = v;
        let regexs = / Chrome\/(\d+)\.\d+\./g.exec(v);
        if (regexs != null) {
            this.secua = `\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"${regexs[1]}\", \"Google Chrome\";v=\"${regexs[1]}\"`
        }
        // console.log(regexs)
    }

    constructor(is_local = false) {
        this._ua = '';
        this.is_local = is_local;
        this.flag = false
        this.awaitTime = 3000
        this.appId = "PXVb73hTEg"
        this.ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
        // ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4 Mobile/15E148 Safari/604.1'

        this.pxUrl = `https://collector-${this.appId}.px-cloud.net/api/v2/collector`
        this.log = log4js.getLogger('px')
        this.px_11547_env = {
            "PX11352": "6c0049fd610b970526aca9d130f6a56b",
            "PX12292": "WebKit",
            "PX12032": "WebGL 1.0 (OpenGL ES 2.0 Chromium)",
            "PX11477": "126.8696939282454",
            "PX12491": "7523bf6e5dcadcffdae6b3063827e345",
            "PX11386": ["webdriver"],
            "PX11842": [],
            "PX11309": "d41d8cd98f00b204e9800998ecf8427e",
            "PX12149": ["[1, 1]", "[1, 511]", 8, "yes", 8, 24, 8, 16, 32, 16384, 1024, 16384, 16, 16384, 30, 16, 16, 1024, "[16384, 16384]", "no_fp", 23, 127, 127, 23, 127, 127, 23, 127, 127, 23, 127, 127, 23, 127, 127, 23, 127, 127, 23, 127, 127, 23, 127, 127, 23, 127, 127, 23, 127, 127, 23, 127, 127, 23, 127, 127],
            "PX11534": "WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)",
            "PX12439": ["PDF Viewer::Portable Document Format::application/pdf~pdf::text/pdf~pdf", "Chrome PDF Viewer::Portable Document Format::application/pdf~pdf::text/pdf~pdf", "Chromium PDF Viewer::Portable Document Format::application/pdf~pdf::text/pdf~pdf", "Microsoft Edge PDF Viewer::Portable Document Format::application/pdf~pdf::text/pdf~pdf", "WebKit built-in PDF::Portable Document Format::application/pdf~pdf::text/pdf~pdf"],
            "PX11811": [],
            "PX12503": "2da772f3cf778a9e4ec2e04676071789",
            "PX12109": "b908567e93d9ed24c036da7986349e97",
            "PX12299": true,
            "PX11455": "ANGLE (Apple, ANGLE Metal Renderer: Apple M1 Max, Unspecified Version)",
            "PX12502": "9b6e8aa24c9c891c0ac12b35eec64b6a",
            "PX12362": "b12f6f6ef824e6fa2e4e686a6b3919f1",
            "PX12427": ["$n", "$r", "_a", "$d", "$t", "_e", "$e", "_n", "_t", "_d", "_", "_l", "$s", "$o", "_u", "$u"],
            "PX11536": ["ANGLE_instanced_arrays", "EXT_blend_minmax", "EXT_color_buffer_half_float", "EXT_disjoint_timer_query", "EXT_float_blend", "EXT_frag_depth", "EXT_shader_texture_lod", "EXT_texture_compression_bptc", "EXT_texture_compression_rgtc", "EXT_texture_filter_anisotropic", "EXT_sRGB", "KHR_parallel_shader_compile", "OES_element_index_uint", "OES_fbo_render_mipmap", "OES_standard_derivatives", "OES_texture_float", "OES_texture_float_linear", "OES_texture_half_float", "OES_texture_half_float_linear", "OES_vertex_array_object", "WEBGL_color_buffer_float", "WEBGL_compressed_texture_astc", "WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_etc1", "WEBGL_compressed_texture_pvrtc", "WEBGL_compressed_texture_s3tc", "WEBGL_compressed_texture_s3tc_srgb", "WEBGL_debug_renderer_info", "WEBGL_debug_shaders", "WEBGL_depth_texture", "WEBGL_draw_buffers", "WEBGL_lose_context", "WEBGL_multi_draw"],
            "PX11927": "13ad77bdb5a7c270e9b902a6d693e6d3",
            "PX12354": "a800fce5b959a226aecf6a05b8bf928d",
            "PX12622": "016beb17dd57a6e446b36265284c0c9c",
            "PX11316": false,
            "PX12288": true,
            "PX12446": 33,
            "PX12586": 2,
            "PX12572": "a2de04d410d8297071522cb17af2ccdd",
            "PX11948": 1,
            "PX11448": true,
            "PX11551": "fd7149bbfb316699ef918fa7bb7510a8",
            "PX12130": ["$n", "$r", "_a", "$d", "$t", "_e", "$e", "_n", "_t", "_d", "_", "_l", "$s", "$o", "_u", "$u"],
            "PX12526": "c9a6cb64a9c6b14c5c489fd18fc4c35d",
            "PX11986": true,
            "PX12492": "c505c10e26a1b7a7741437db9f82916b",
            "PX12570": "78f763eab3a2082c63c66cf47f9e05a0",
            "PX11567": "WebKit WebGL",
            "PX12352": "Google Inc. (Apple)",
            "PX12525": "b1199c2b7aa9aa43f16fc345099c3f04",
            "PX12331": false,
            "PX12196": "missing",
            "PX12236": "fd7149bbfb316699ef918fa7bb7510a8"
        }
        // let env = fs.readFileSync('./env.json', 'utf-8')
        // env = JSON.parse(env);
        // let keys = Object.keys(env)
        // let selectId = keys[randint(0, keys.length - 1)]
        // selectId = 'd3e94c1cb84038031357a52f'
        // this.log.info('select env', selectId)
        // this.env = env[selectId]

        // this.ua = this.env.navigatorparams.useragent

        this.prox = `http://user-uni001-region-us-sessid-${randint(1000, 5000)}-sesstime-5-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600`
        // prox = `http://uni00001_custom_zone_US_sid_${randint(67336718, 67336728)}_time_5:q39CEBTs5A@us.foxyip.com:7778`
        // prox = `http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:${randint(10000, 13500)}`
        this.tlsUrl = 'http://52.52.23.116/tls/forward'
        if (this.is_local) {
            this.tlsUrl = 'http://127.0.0.1:58000/tls/forward'
            // this.tlsUrl = 'http://192.168.50.197:58000/tls/forward'
            // this.tlsUrl = 'http://52.52.23.116/tls/forward'

            this.prox = 'http://127.0.0.1:7890'
            // this.prox = 'http://brd-customer-hl_70986309-zone-web_unlocker1-country-us:4dn0oh24j9mp@brd.superproxy.io:22225'
            // this.prox = `http://brd-customer-hl_70986309-zone-isp-session-${Math.random()}:ozfawewfxj8y@brd.superproxy.io:22225`

        }

        this.pxHeaders = {
            "authority": "collector-PXVb73hTEg.px-cloud.net",
            "accept": "*/*",
            "accept-language": "en-US,en;q=0.9",
            "cache-control": "no-cache",
            "content-type": "application/x-www-form-urlencoded",
            "origin": "https://www.flyfrontier.com",
            "pragma": "no-cache",
            "user-agent": this.ua
        }


        this.url = 'https://www.flyfrontier.com/'
        this.log.level = 'debug'
        this.uuid = '';
        this.ts = '';
        this.cs = ''
        // # PX15454 o111oooo
        this.num1 = 0
        // # PX11701 111o1o
        this.num2 = ''
        // # PX11701 111o1o
        this.str1 = ''
        this.vid = ''
        this.sid = ''
        this.cts = ''

        this.seq = 0
        this.rsc = 1;
        this.cookies = {}


    }

    async initMongo() {
        this.log.info("init mongo 获取环境数据")
        const database = client.db("env");
        const movies = database.collection("env_shape");
        // Query for a movie that has the title 'The Room'
        const query = {
            'env.funcs': {$ne: null},
            'env.navigatorparams.platform': 'MacIntel',
            // 'env.navigatorparams.platform': 'Win32',
            "env.navigatorparams.vendor": "Google Inc.",
            // 'env.useragentdata.highvalue.uafullversion':{$ne:null},
            'env.useragentdata.highvalue.uafullversion': {$ne: ""}
        };

        // Execute query
        const movie = await movies.aggregate([
            {$match: query},
            {
                $project: {
                    'env.windowparams': 1,
                    'env.screenparams': 1,
                    'env.navigatorparams': 1,
                    'env.featurepolicy': 1,
                    'env.plugins': 1,
                    'env.mimetypes': 1,
                    'env.glres': 1,
                    'env.jpg': 1,
                    'env.jpg2': 1,
                    'env.useragentdata': 1,
                    'env.consoleprops': 1,
                    'env.webglprops': 1,
                    'env.windowprops': 1,
                    'env.locationprops': 1,
                    'env.mathprops': 1,
                    'env.funcs': 1,
                    'env.funcs2': 1,
                    'env.documentfunc': 1,
                    'env.bodyfunc': 1,
                    'env.navigatorfunc': 1
                }
            },
            {$sample: {size: 1}}
        ])
        let res = await movie.toArray()
        this.env = res[0].env

        this.envid = res[0]._id.toString()


        // this.env = ENVS[keys[randint(0, keys.length - 1)]]
        this.ua = this.env.navigatorparams.useragent

        this.log.info('ua', this.ua)
        if (!this.is_local) {
            let proxyRes = await axios({
                method: 'post',
                url: 'http://ymx-lcc.unififi.com/proxy/get-proxy',
                headers: {
                    'Content-Type': 'application/json'
                },
                data: JSON.stringify({
                    'name': 'F9',
                    'type': 'shopping'
                })
            })
            this.prox = proxyRes.data.url;
        }

        this.log.info(`proxy ${this.prox}`)

    }

    async initMongo2() {
        this.log.info("init mongo 获取环境数据")
        const database = client.db("env");
        const movies = database.collection("px_env");
        // Query for a movie that has the title 'The Room'
        const query = {
            // 'env.funcs': {$ne: null},
            // 'env.navigatorparams.platform': 'MacIntel',
            // // 'env.navigatorparams.platform': 'Win32',
            // "env.navigatorparams.vendor": "Google Inc.",
            // // 'env.useragentdata.highvalue.uafullversion':{$ne:null},
            // 'env.useragentdata.highvalue.uafullversion': {$ne: ""}
        };

        // Execute query
        const movie = await movies.aggregate([
            // {$match: query},
            {$sample: {size: 1}}
        ])
        let res = await movie.toArray()
        this.env2 = res[0]
        console.log('env2.ua', this.env2.px11590.PX11754)
        delete this.env2.px11590.PX12023
        delete this.env2.px11590.PX11840
        this.envid2 = res[0]._id.toString()


        // this.env = ENVS[keys[randint(0, keys.length - 1)]]
        // this.ua = this.env.navigatorparams.useragent
        this.ua = this.env2.px11590.PX11754;
        this.env2.px11547.PX11849 = this.env2.px11590.PX11849
        delete this.env2.px11547.PX12427
        delete this.env2.px11547.PX12130
        delete this.env2.px11547.PX11993
        this.env.navigatorparams.platform = this.env2.px11590.PX12458
        this.env.navigatorparams.useragent = this.ua;
        this.log.info('ua', this.ua)

    }

    async add_headers(headers) {
        // this.prox = `http://user-uni001-region-us-sessid-${randint(1000, 5000)}-sesstime-5-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600`
        // this.prox = `http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:${randint(10000, 13500)}`
        let cks = Object.keys(this.cookies).map((v, k) => `${v}=${this.cookies[v]}`).join('; ')
        this.log.info('cookie', cks)

        let res = await axios.post('http://ymx-lcc.unififi.com/header/add', JSON.stringify({
            'brush_fromto': 'LAS-BOS',
            'brush_fromdate': '2023-05-26',
            'brush_header': headers,
            'brush_proxy': this.prox,
            'brush_mode': 'shopping',
            'brush_name': 'js0',
            'brush_type': 'cookieF9',
        }));
        this.log.debug(res.data)

    }

    async do_collector(data) {
        try {
            for (let i = 0; i < data.length; i++) {
                let n = data[i];
                n.d['PX11645'] = this.url;
                n.d["PX11379"] = false;
            }
            if (plt === 'darwin') console.log(JSON.stringify(data))

            // if (typeof data === 'object') {
            //     data = ht(data)
            // }
            // this.log.info(data)
            // let payload = encodePayload(data, this.uuid, this.ts)
            // let pc = genPc(data, `${this.uuid}:${this.tag}:${this.ft}`)
            // let body = {
            //     "appId": this.appId,
            //     "tag": this.tag,
            //     "uuid": this.uuid,
            //     "ft": this.ft,
            //     "seq": this.seq,
            //     "en": "NTA",
            //     "pc": pc,
            //     "rsc": this.rsc,
            //     "payload": payload,
            // }
            // body = this.updateBody(body);


            let body = this.getPayload(data)
            body.push(`seq=${this.seq}`)
            body.push(`rsc=${this.rsc}`)
            let res = await axios.post(this.tlsUrl, JSON.stringify({
                url: this.pxUrl,
                method: "POST",
                // data: qs.stringify(body),
                data: body.join('&'),
                headers: this.pxHeaders,
                allow_redirects: true,
                debug: true,
                proxy: this.prox,
                id: (new Date().getTime()) + '',
                random_tls: false,
            }), {
                timeout: 5000,
            });
            let inRes = JSON.parse(res.data.text)
            // this.log.info(inRes)
            this.parseRes(inRes)
        } catch (err) {
            console.error(err.data);
            throw err;
        }

    };


    updateBody(body) {
        if (this.vid !== "") {
            body.vid = this.vid
        }
        if (this.cs !== "") {
            body.cs = this.cs
        }
        if (this.cts !== "") {
            body.cts = this.cts
        }
        if (this.sid !== "") {
            body.sid = this.sid
        }
        return body
    }

    getPayload(data) {

        let vh = null;
        // console.log('now', le(), JSON.stringify(t))

        // console.log('now', JSON.stringify(data))
        // var A = $u();
        let uuid = this.uuid
        var pc = se(ht(data), function (t, e) {
            return [uuid, t, e]['join'](":");
        }(this.tag, this.ft));
        var b = {
            "vid": this.vid,
            "tag": this.tag,
            "appID": this.appId,
            "cu": this.uuid,
            "cs": this.cs,
            "pc": pc,
            "en": "NTA"
        };
        var w = bl(data, b, this.ts);
        // console.log("ts", fl())
        // console.log('res', w)
        var E = ["payload=" + w, "appId=" + this.appId, "tag=" + this.tag, "uuid=" + this.uuid, "ft=" + this.ft, "en=" + "NTA"];
        var T = null;
        T && E["push"]('xuuid=' + T);
        this.cs && E["push"]('cs=' + this.cs);
        pc && E["push"]('pc=' + pc);
        var O = this.sid;
        var U = Ol(this.ts);
        (O || U) && E["push"]('sid=' + (O || this.sid) + U);
        var I = [];
        this.vid && E["push"]('vid=' + this.vid);
        // mu && E["push"]('jcs=' + mu);
        var S = this.ci;
        S && E["push"]('ci=' + S);
        // Ru || (Ru = Df(cu));
        var C = this.pxhd;
        C && E["push"]('pxhd=' + C);
        let Qf = this.cts;
        Qf && E["push"]('cts=' + Qf);
        I["length"] >= 0 && E["push"]["apply"](E, I);
        return E;
    }

    parseRes(inRes) {
        let result = void 0;
        if (inRes['ob']) {
            let cks = ie(atob(inRes.ob), this.version()).split('~~~~')
            if (plt === 'darwin') this.log.info(cks.length, JSON.stringify(cks, null, '\t'))
            for (var ck of cks) {
                let tmp = ck.split('|');

                // if (tmp[0] === 'o11o1ooo') {
                //     this.log.fatal('result', tmp[1] === '0')
                //     result = tmp[1] === '0'
                // }
                if (tmp[0] === 'o11o11o1') {
                    this.ts = tmp[1]

                }
                if (tmp[0] === '11oo1o') {
                    this.ci = tmp[2]
                    this.token = tmp[4].split('_')[0]
                    this.token2 = tmp[4].split('_')[1]
                }
                if (tmp[0] === 'o1oo11') {
                    this.hash = tmp[2]
                    this.hash2 = tmp[3]
                    this.hashv = tmp[4]
                }

                if (tmp[0] === 'o11o11oo') {
                    this.num1 = tmp[1]

                }
                if (tmp[0] === '1o111o') {
                    this.num2 = tmp[1]
                }

                if (tmp[0] === '11o1o1') {
                    this.str1 = tmp[1]

                }
                if (tmp[0] === 'ooo11o') {
                    this.vid = tmp[1]
                    this.cookies['_pxvid'] = this.vid
                }


                if (tmp[0] === 'oo1111') {
                    this.sid = tmp[1]
                }

                if (tmp[0] === '1ooo11') {
                    this.cs = tmp[1]
                }

                if (tmp[0] === 'o11o1ooo') {
                    this.cts = tmp[1]
                    this.cookies['pxcts'] = this.cts
                }


                if (tmp.includes('zpxde')) {
                    this.cookies['pxde'] = tmp[3]
                }
                if (tmp.includes('_px2')) {
                    this.cookies['_px2'] = tmp[3]
                    this.log.debug(`px2_decode ${atob(this.cookies['_px2'])}`)
                    let parsePx2 = JSON.parse(atob(this.cookies['_px2']))
                    // if (!parsePx2.t.toString().startsWith('6202')) {
                    //     this.flag = true
                    //     this.awaitTime = parsePx2.t - Date.now()
                    // } else {
                    //     this.flag = false;
                    // }
                }
                if (tmp[1] === 'score') {
                    if (tmp[2] === '0') {
                        this.flag = true
                    } else {
                        this.flag = false;
                    }
                }

            }
        }

        if (result) {
            this.result = result;
        }
    }

    version() {
        return parseInt(this.tag.substring(1).replaceAll('.', '')) % 128
    }

    async px12095() {
        if (plt === 'darwin') this.log.info("PX12095")

        // this.log.info('setp1')
        let t1 = new Date().getTime();
        this.startTs = t1
        let t2 = t1 + randint(5, 30)
        this.startTs2 = t2
        this.performanceNow = randint(3000, 5000)
        this.px12280 = this.startTs2 + this.performanceNow

        this.uuid = genUuid()
        let data = [{
            "t": "PX12095",
            "d": {
                "PX11645": this.url, "PX12207": 0, "PX12458": this.env.navigatorparams.platform, "PX11902": 0,
                "PX11560": randint(3600, 9600), "PX12248": 3600, "PX11385": t1, "PX12280": t2,
                "PX11496": this.uuid, "PX12564": null, "PX12565": -1,
                // "PX11379": false
            }
        }]

        this.log.info(`uuid ${this.uuid}`)
        let res = await this.do_collector(data)
        this.seq++;

        this.pxenv = new PxEnv(this.px_11547_env, this.env, this.url, this.sid, this.vid, this.ts, this.num1, this.num2,
            this.str1, this.uuid,
            this.startTs, this.startTs2, this.performanceNow, this.px12280)

    }

    async px12167() {
        if (plt === 'darwin') this.log.info("PX12167")

        this.performanceNow += randint(1000, 2000)

        let data = [{"t": "PX12167", "d": {"PX11648": true, "PX11645": this.url}}]
        let res = await this.do_collector(data)

    }

    async px11590() {
        if (plt === 'darwin') this.log.info('11590')
        this.performanceNow = randint(3000, 4000)
        // let data = genPayload2(this.url, this.sid, this.vid, this.ts, this.num1, this.num2,
        //     this.str1, this.uuid,
        //     this.startTs, this.startTs2, this.performanceNow, this.px12280)
        let px11590 = this.pxenv.get_px11590();
        Object.assign(px11590.d, this.env2.px11590)
        let data = [
//             {
//     "t": "PX11659",
//     "d": {
//         "PX11762": "1718936918459",
//         "PX12076": "21685635571e582c920aa2826354243cec2dfd7ef283f2ff3d568e918868e516",
//         "PX11953": 9902,
//         "PX11902": 1,
//         "PX11560": 6096,
//         "PX12280": 1718936889321,
//         "PX11496": "e56ab730-2f75-11ef-90f0-c3105b474a7d",
//         "PX12564": null,
//         "PX12565": -1,
//         "PX11379": false
//     }
// },
            px11590]
        let res = await this.do_collector(data)

    }

    async px11951() {
        if (plt === 'darwin') this.log.info("px11951")

        this.performanceNow = randint(3000, 4000)
        // let data = genPayload2(this.url, this.sid, this.vid, this.ts, this.num1, this.num2,
        //     this.str1, this.uuid,
        //     this.startTs, this.startTs2, this.performanceNow, this.px12280)
        let data = [this.pxenv.get_PX11951()]
        let res = await this.do_collector(data)

    }

    async px11547() {
        if (plt === 'darwin') this.log.info("px11547")
        this.performanceNow = Date.now() - this.startTs;
        // let data = genPayload4(this.url, this.sid, this.vid, this.ts, this.num1, this.num2,
        //     this.str1, this.uuid,
        //     this.startTs, this.startTs2, this.performanceNow, this.px12280)
        this.pxenv.performanceNow = this.performanceNow
        let d = this.pxenv.get_px11547();
        Object.assign(d.d, this.env2.px11547)
        let data = [
            // this.pxenv.get_px11891(),
            // this.pxenv.get_px12123(),
            d]
        let res = await this.do_collector(data)
    }

    async test() {
        // this.prox = 'http://127.0.0.1:8890'
        // this.tlsUrl = 'http://127.0.0.1:58000/tls/forwardios'

        let cks = Object.keys(this.cookies).map((v, k) => `${v}=${this.cookies[v]}`).join('; ')
        this.log.info('cookie', cks)
        // let headers =  {
        //         "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        //         "accept-language": "en",
        //         "cache-control": "no-cache",
        //         "pragma": "no-cache",
        //         "priority": "u=0, i",
        //         "upgrade-insecure-requests": "1",
        //         "user-agent": this.ua,
        //         "cookie": cks
        //     }
        let headers = {
            "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6",
            "pragma": "no-cache",
            "sec-fetch-user": "?1",
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "sec-ch-ua-platform": "\"MacIntel\"",
            "cache-control": "no-cache",
            "sec-ch-ua": "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Google Chrome\";v=\"126\"",
            "sec-ch-ua-mobile": "?0",
            "sec-fetch-mode": "navigate",
            "priority": "u=0, i",
            "upgrade-insecure-requests": "1",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
            "sec-fetch-dest": "document",
            "sec-fetch-site": "same-site",
            // "cookie":                    "pxcts=3ee1648a-2fa6-11ef-9bc1-7ce24800bb12; _pxvid=3ee15079-2fa6-11ef-9bc0-0add1130ea42; _px2=eyJ1IjoiM2U2MTg1ZjAtMmZhNi0xMWVmLWFlMmItMzM5NzViZmUyNTQ2IiwidiI6IjNlZTE1MDc5LTJmYTYtMTFlZi05YmMwLTBhZGQxMTMwZWE0MiIsInQiOjYyMDIzMzg4MDAwNCwiaCI6IjhiZTJmYzc0YmRlYzNlN2RlYTIwMjc2NTRlOGEwMWI1OGVkYWFkMWU5YTFhNjMzMzNmMTNkMjU2NTViN2JmZmMifQ==",
        }
        // if (this.secua){
        //     Object.assign(headers, {
        //         "sec-ch-ua": this.secua,
        //         "sec-ch-ua-mobile": "?0",
        //         "sec-ch-ua-platform": `"${this.env.navigatorparams.platform}"`,
        //         "sec-fetch-dest": "document",
        //         "sec-fetch-mode": "navigate",
        //         "sec-fetch-site": "same-site",
        //         "sec-fetch-user": "?1",
        //     })
        // }

        if (cks !== "") headers['cookie'] = cks;
        let res = await axios.post(this.tlsUrl, JSON.stringify({
            url: 'https://booking.flyfrontier.com/Flight/InternalSelect?s=true&o1=ATL&d1=BMI&dd1=2024-07-18&dd2=0001-01-01&mon=true&adt=1',
            headers: headers,
            allow_redirects: true,
            debug: true,
            cookie: cks,
            method: "GET",
            proxy: this.prox,
            random_tls: true,

        }));
        if (res.data.status_code === 200) {
            // console.log(res.data.text)
            this.log.warn('success', res.data.status_code, res.data.text.includes('FlightData'), this.ua)
        } else {
            this.log.error('error', res.data.status_code)
        }
        await this.add_headers(headers)

    }

    async do_func(func) {
        if (plt === 'darwin') this.log.info(func.t)
        this.performanceNow += randint(1000, 2000)
        let data = [func]
        let res = await this.do_collector(data)
    }

    check() {
        if (this.cookies['_px2']) {
            let px2 = this.cookies['_px2'];
            let px2Decode = JSON.parse(atob(px2));

            if (px2Decode.t.toString().startsWith('62') && px2Decode.t.toString().endsWith('04')) {
                return true
            }
        }
        return false

    }

    async init() {
        this.log.info("init")
        let res = await axios.post(this.tlsUrl, JSON.stringify({
            url: 'https://booking.flyfrontier.com/Flight/InternalSelect?s=true&o1=DEN&d1=LAS&dd1=2024-07-31&dd2=0001-01-01&mon=true&adt=1',
            headers: {
                "Host": "booking.flyfrontier.com",
                "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:127.0) Gecko/20100101 Firefox/127.0",
                "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
                "accept-language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                "sec-gpc": "1",
                "upgrade-insecure-requests": "1",
                "sec-fetch-dest": "document",
                "sec-fetch-mode": "navigate",
                "sec-fetch-site": "same-origin",
                "sec-fetch-user": "?1",
                "priority": "u=1",
                "te": "trailers"
            },
            allow_redirects: true,
            debug: true,
            method: "GET",
            proxy: this.prox,
            random_tls: false,
        }));
        Object.assign(this.cookies, res.data.cookies)
        // console.log(res.data)
    }

    async step12419() {
        this.performanceNow += randint(1000, 2000)

        let data = [
            {
                "t": "PX12419",
                "d": {
                    "PX12040": [
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "1279,460,11577"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 125,
                            "PX12208": 0,
                            "PX11652": 2,
                            "PX11824": 1291,
                            "PX11631": 2005,
                            "PX12165": "form",
                            "PX12108": 1209,
                            "PX12414": 421,
                            "PX11699": 11607
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "1171,406,11648"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 350.875,
                            "PX12208": 75.5,
                            "PX11652": 3,
                            "PX11824": 1140,
                            "PX11631": 94,
                            "PX12165": "div",
                            "PX12108": 941,
                            "PX12414": 338,
                            "PX11699": 11705
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "941,338,11705"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 300,
                            "PX12208": 75.5,
                            "PX11652": 4,
                            "PX11824": 1140,
                            "PX11631": 49,
                            "PX12165": "div",
                            "PX12108": 786,
                            "PX12414": 297,
                            "PX11699": 11749
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 171,
                            "PX12208": 75.5,
                            "PX11652": 5,
                            "PX11824": 1140,
                            "PX11631": 1642,
                            "PX12165": "div",
                            "PX12108": 662,
                            "PX12414": 259,
                            "PX11699": 11757
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "662,259,11757"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 167,
                            "PX12208": 567.40625,
                            "PX11652": 6,
                            "PX11824": 156,
                            "PX11631": 125,
                            "PX12165": "a",
                            "PX12108": 397,
                            "PX12414": 189,
                            "PX11699": 11821
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "397,189,11821|359,181,118"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 174.5,
                            "PX12208": 255.0625,
                            "PX11652": 7,
                            "PX11824": 156,
                            "PX11631": 110,
                            "PX12165": "a",
                            "PX12108": 840,
                            "PX12414": 306,
                            "PX11699": 12066
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "840,306,12067"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 300,
                            "PX12208": 75.5,
                            "PX11652": 7,
                            "PX11824": 1140,
                            "PX11631": 49,
                            "PX12165": "div",
                            "PX12108": 1097,
                            "PX12414": 379,
                            "PX11699": 12117
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "1097,379,12118"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 350.875,
                            "PX12208": 75.5,
                            "PX11652": 7,
                            "PX11824": 1140,
                            "PX11631": 94,
                            "PX12165": "div",
                            "PX12108": 1279,
                            "PX12414": 458,
                            "PX11699": 12174
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "1279,458,12174"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 125,
                            "PX12208": 0,
                            "PX11652": 7,
                            "PX11824": 1291,
                            "PX11631": 2005,
                            "PX12165": "form",
                            "PX12108": 1301,
                            "PX12414": 472,
                            "PX11699": 12178
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "1253,689,12895"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 125,
                            "PX12208": 0,
                            "PX11652": 7,
                            "PX11824": 1291,
                            "PX11631": 2005,
                            "PX12165": "form",
                            "PX12108": 1253,
                            "PX12414": 689,
                            "PX11699": 12899
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "961,571,12953"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 568.875,
                            "PX12208": 834.84375,
                            "PX11652": 8,
                            "PX11824": 190,
                            "PX11631": 35,
                            "PX12165": "td",
                            "PX12108": 689,
                            "PX12414": 483,
                            "PX11699": 13014
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "689,483,13014"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 477.875,
                            "PX12208": 646.015625,
                            "PX11652": 9,
                            "PX11824": 188,
                            "PX11631": 24,
                            "PX12165": "div",
                            "PX12108": 622,
                            "PX12414": 464,
                            "PX11699": 13078
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "622,464,13078|632,461,116"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 171,
                            "PX12208": 75.5,
                            "PX11652": 9,
                            "PX11824": 1140,
                            "PX11631": 1642,
                            "PX12165": "div",
                            "PX12108": 836,
                            "PX12414": 506,
                            "PX11699": 13252
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "836,506,13252"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 501.875,
                            "PX12208": 835.84375,
                            "PX11652": 10,
                            "PX11824": 188,
                            "PX11631": 24,
                            "PX12165": "div",
                            "PX12108": 1136,
                            "PX12414": 562,
                            "PX11699": 13304
                        },
                        {
                            "PX12343": "mousemove",
                            "PX12270": "true",
                            "PX12301": "1136,562,13304"
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 533.875,
                            "PX12208": 1024.671875,
                            "PX11652": 11,
                            "PX11824": 190,
                            "PX11631": 35,
                            "PX12165": "td",
                            "PX12108": 1218,
                            "PX12414": 575,
                            "PX11699": 13307
                        },
                        {
                            "PX12343": "mouseout",
                            "PX12270": "true",
                            "PX11427": 125,
                            "PX12208": 0,
                            "PX11652": 11,
                            "PX11824": 1291,
                            "PX11631": 2005,
                            "PX12165": "form",
                            "PX12108": 1417,
                            "PX12414": 618,
                            "PX11699": 13367
                        }
                    ],
                    "PX12170": "60_sec_rest",
                    "PX11934": this.url,
                    "PX12160": {
                        "#flight-select-form": 1,
                        "#ibe-depart-section>DIV1>DIV6": 2,
                        "#ibe-depart-section>DIV1>DIV3": 3,
                        "#ibe-depart-section>DIV1": 4,
                        "DIV2>A4": 5,
                        "DIV1>DIV2>DIV2>A2": 6,
                        "#ibe-depart-section>DIV1>DIV7>DIV1>DIV1>TABLE>TBODY>TR2>TD4": 7,
                        "#ibe-depart-section>DIV1>DIV7>DIV1>DIV1>TABLE>THEAD>TR>TH3>DIV1>DIV1": 8,
                        "#ibe-depart-section>DIV1>DIV7>DIV1>DIV1>TABLE>THEAD>TR>TH4>DIV1>DIV2": 9,
                        "#ibe-depart-section>DIV1>DIV7>DIV1>DIV1>TABLE>TBODY>TR1>TD5": 10
                    },
                    "PX11875": this.uuid,
                    "PX11844": 0,
                    "PX12465": true,
                    "PX11393": "0,0,11577|-30,-21,11592|-40,-18,11607|-38,-15,11648|-230,-68,11705|-155,-41,11749|-124,-38,11757|-265,-70,11821|-38,-7,11881|-2,-1,11883",
                    "PX12621": "",
                    "PX12470": this.px12280,
                    "PX11698": [
                        "1279,460,21232",
                        "1209,421,21262",
                        "941,338,21357",
                        "662,259,21411",
                        "359,182,21537",
                        "359,181,21595",
                        "379,180,21651",
                        "840,306,21719",
                        "1160,401,21775",
                        "1253,689,22550",
                        "961,571,22608",
                        "622,464,22728",
                        "620,463,22787",
                        "650,462,22853",
                        "1136,562,22949"
                    ],
                    "PX11679": this.env2.px11590.PX12387,
                    "PX11902": 10,
                    "PX11560": 83465,
                    "PX12280": this.performanceNow,
                    "PX11496": this.uuid,
                    "PX12564": null,
                    "PX12565": -1,
                    "PX11379": false
                }
            }
        ]
        let res = await this.do_collector(data)
    }
}

async function run() {
    while (true) {
        try {
            // let res = await axios.get('http://ymx-lcc.unififi.com/header/task/pull/cookieF9?brush_name=test')
            // let data = res.data;
            //
            let data = {
                status: 0
            }
            console.log(data)
            // if r.json()['status'] != 0:
            //     #         logger.debug(f'不需要刷值')
            //     #         time.sleep(10)
            //     #         continue
            if (data.status === 0) {
                for (let i = 0; i < 10; i++) {

                    try {
                        let px = new PxBypass(true)

                        // await px.init()
                        await px.initMongo()

                        await px.initMongo2()
                        await px.px12095()
                        await px.px12167()
                        await sleep(2000)

                        await px.px11590()
                        await sleep(3000)
                        if (!px.flag)await px.px11951()
                        if (!px.flag) await px.do_func(px.pxenv.get_px11891())


                        // await px.step12419()
                        if (!px.flag) await sleep(3500)
                        if (!px.flag) await px.do_func(px.pxenv.get_px12123())
                        if (!px.flag) await sleep(2000)
                        if (!px.flag) await px.px11547()
                        if (!px.flag) await sleep(5000)


                        //
                        //
                        //
                        // await sleep(1500)
                        px.log.info("sleep", px.awaitTime)
                        await sleep(px.awaitTime)
                        await px.test()
                        // await px.add_headers()
                        await sleep(1000)
                    } catch (e) {
                        console.log(e.toString())
                    } finally {
                        await sleep(1000)
                    }


                }

            }
            await sleep(1000)
        } catch (e) {
            console.log(e)
        } finally {
        }
    }


    // }

}


run();
