// ==UserScript==
// @name         DexScreen-GetTopTrader
// @namespace    http://tampermonkey.net/
// @version      2024-10-19
// @description  try to take over the world!
// @author       You
// @match        https://dexscreener.com/solana/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=dexscreener.com
// @grant        none
// ==/UserScript==
// ==/UserScript==



function funcDownload(content, filename) {
    console.log('begin download');
    // 创建隐藏的可下载链接
    var eleLink = document.createElement('a');
    eleLink.download = filename;
    eleLink.style.display = 'none';
    // 字符内容转变成blob地址
    var blob = new Blob([content]);
    eleLink.href = URL.createObjectURL(blob);
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
}




function sleep(sleepdelay) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(sleepdelay);
        }, sleepdelay);
    })
}

var number_chars_obj = {
    "k": 3,
    "m": 6,
    "b": 9,
    "t": 12,
    "p": 15
};

var number_chars_arr = ["k", "m", "b", "t", "p"];

function get_thead_arr() {
    // let titlearr = _thead.innerText.trim().split(/\r?\n/);


    titlearr = [
        "Rank",
        "Maker",
        "Buymoney",
        "Sellmoney",
        "Earn",
        "Earnper",
        "Buycount",
        "Sellcount",
        "Buyamount",
        "Sellamount",
        "Amountper",


    ]
    return titlearr;
}


function save_resdata() {
    console.log("enter save_resdata");

    res_data.forEach((val, index, arr) => { arr[index] = val.join() + "\n" });
    let urlpathname = window.location.pathname.slice(1).split('/');
    urlpathname = urlpathname.pop()

    funcDownload(res_data.join(""), urlpathname + "_top_dexscreen_sol" + "_" + parseInt(Date.now() / 1000) + ".csv");
    res_data = [];

}


function get_tbodyarr(tbody_arr) {
    let urlpathname_arr = window.location.pathname.slice(1).split('/');
    let token_address = urlpathname_arr[1];

    for (let idx = 0; idx < tbody_arr.length; idx++) {
        let tr = tbody_arr[idx];
        let tds_arr = Array.from(tr.children);
        let td_value_obj = {
            "Rank": "0",
            "Maker": "",
            "Buymoney": 0,
            "Sellmoney": 0,
            "Earn": 0,
            "Earnper": 0,
            "Buycount": 0,
            "Sellcount": 0,
            "Buyamount": 0,
            "Sellamount": 0,
            "Amountper": 0,



        }
        let temp_innertext;
        for (let i = 0; i < tds_arr.length; i++) {
            if (i == 1 || i == 4 || i == 5 || i == 6 || i == 7) {
                continue;
            } else if (i == 0) {
                let td_innerText = tds_arr[i].innerText.trim().replace(/#/g, "");
                td_value_obj.Rank = td_innerText;

            }
            else if (i == 8) {
                td_value_obj.Maker = tds_arr[i].querySelector("a").href.split('/').pop();

            } else if (i == 2 || i == 3) {
                // 获取 Bought
                // '<$0.1\n10/1 txns'
                // '-'
                let td_innerText = tds_arr[i].innerText.trim().toLowerCase();
                let money = 0, amount = 0, count = 0;

                if (td_innerText == "-") {
                    if (i == 2) {
                        td_value_obj.Buycount = 0;
                        td_value_obj.Buymoney = 0;
                    } else {
                        td_value_obj.Sellcount = 0;
                        td_value_obj.Sellmoney = 0;
                    }
                    continue;
                }
                if (td_innerText.indexOf("$") == -1) {
                    console.log("idx=", idx, "td_innerText=", td_innerText);
                    throw ("td_innerText error");
                }

                td_innerText = td_innerText.replace(/[(\$),]/g, "");
                let td_innerText_arr = td_innerText.split(/\r?\n/);
                td_innerText_arr.forEach((val, index, arr) => {
                    arr[index] = val.trim();
                });

                // 获取buymoney / sellmoney  '<0.1' '11.5' '11.5k' '11.5m' 其他更大的数值
                if (td_innerText_arr[0].indexOf("<") != -1) {
                    // td_value_obj.Buymoney = 0.1;
                    money = 0.1;
                } else {
                    if (!isNaN(td_innerText_arr[0])) {
                        // td_value_obj.Buy
                        money = parseFloat(td_innerText_arr[0]);

                    } else {
                        for (let number_char of number_chars_arr) {
                            if (td_innerText_arr[0].indexOf(number_char) != -1) {
                                money = parseFloat(td_innerText_arr[0]) * 10 ** number_chars_obj[number_char];
                            }
                        }

                    }

                }
                let temp_td_innerText = td_innerText_arr.pop();
                let temp_td_innerText_arr = temp_td_innerText.split("/");
                td_innerText_arr = [...td_innerText_arr, ...temp_td_innerText_arr];
                td_innerText_arr.forEach((val, index, arr) => {
                    arr[index] = val.trim();
                });
                console.log("td_innerText_arr=", td_innerText_arr);

                //获取buyamount sellamount

                for (let number_char of number_chars_arr) {
                    // 如果有k , m 等 需要转化为字符串
                    if (td_innerText_arr[1].indexOf(number_char) != -1) {
                        amount = String(parseInt(parseFloat(td_innerText_arr[1])) * 1000) + '0'.repeat(number_chars_obj[number_char] - 3);
                        break;
                    }
                }
                if (amount === 0) {
                    amount = parseFloat(td_innerText_arr[1]);

                }


                // 获取buycount  1 txns
                td_innerText_arr[2] = td_innerText_arr[2].split(" ")[0].trim();
                // td_value_obj.Buy
                count = td_innerText_arr[2];

                if (i == 2) {
                    td_value_obj.Buycount = count;
                    td_value_obj.Buymoney = money;
                    td_value_obj.Buyamount = amount;
                } else if (i == 3) {
                    td_value_obj.Sellcount = count;
                    td_value_obj.Sellmoney = money;
                    td_value_obj.Sellamount = amount;
                }


            }

        }
        td_value_obj.Earn = td_value_obj.Sellmoney - td_value_obj.Buymoney;
        td_value_obj.Earnper = td_value_obj.Buymoney == 0 ? 999999 : td_value_obj.Earn / td_value_obj.Buymoney;

        if (typeof (td_value_obj.Sellamount) == 'string') {
            if (typeof (td_value_obj.Buyamount) == 'string') {
                if (td_value_obj.Sellamount.length > td_value_obj.Buyamount.length) {
                    td_value_obj.Amountper = 10;
                } else if (td_value_obj.Sellamount.length == td_value_obj.Buyamount.length) {
                    td_value_obj.Amountper = parseFloat(td_value_obj.Sellamount.slice(0, 2)) / parseFloat(td_value_obj.Buyamount.slice(0, 2));
                } else {
                    td_value_obj.Amountper = 0.1;
                }
            } else {
                td_value_obj.Amountper = 10;
            }
        } else {
            if (td_value_obj.Sellamount == 0) {
                td_value_obj.Amountper = 0;
            } else if (typeof (td_value_obj.Buyamount) == 'string') {
                td_value_obj.Amountper = 0.1;
            }
            else {
                td_value_obj.Amountper = td_value_obj.Buyamount == 0 ? 999999 : parseFloat(td_value_obj.Sellamount) / parseFloat(td_value_obj.Buyamount);

            }
        }



        let td_value_arr = Object.values(td_value_obj);

        res_data.push(td_value_arr);

    }

}
var res_data = [];
// window.addEventListener('load', () => {

(async function () {
    console.log("enter load");
    await sleep(6000);
    console.log("create button");

    var mydivbox = document.createElement("div");

    var button_tran = document.createElement("button");//创建 获取toptran一个按钮
    mydivbox.appendChild(button_tran);
    button_tran.className = "tam-mybutton-gettran"
    button_tran.textContent = "gettran"; //按钮内容
    button_tran.style.width = "90px"; //按钮宽度
    button_tran.style.height = "30px"; //按钮高度
    button_tran.style.align = "center"; //文本居中
    button_tran.style.color = "blue"; //按钮文字颜色
    button_tran.style.background = "#e33e33"; //按钮底色
    button_tran.style.border = "1px solid #e33e33"; //边框属性


    mydivbox.style.position = "fixed";
    mydivbox.style.top = "80px";
    mydivbox.style.right = "40px";
    document.body.appendChild(mydivbox);

    button_tran.addEventListener("click", clickButton); //监听按钮点击事件






    function clickButton() {
        res_data = [];

        let table_div_ep1 = document.getElementsByClassName('custom-1vjv7zm')[0];

        let div_table = table_div_ep1.getElementsByClassName('custom-1kikirr')[0];

        let titlearr = get_thead_arr();
        res_data.push(titlearr);
        let tbody_arr = Array.from(div_table.children);
        tbody_arr.shift();
        get_tbodyarr(tbody_arr);
        save_resdata();



    }



})();

