// ==UserScript==
// @name         Dune_get_history_token_holders
// @namespace    http://tampermonkey.net/
// @version      2024-11-09
// @description  try to take over the world!
// @author       You
// @match        https://dune.com/queries/4283404*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=dune.com
// @grant        none
// ==/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);
  })
}
function getCurrentTime() {
  const zeroFill = (i) => {
    if (i >= 0 && i <= 9) {
      return "0" + i;
    } else {
      return '' + i;
    }

  }
  let date = new Date();//当前时间
  let year = date.getFullYear();
  let month = zeroFill(date.getMonth() + 1);//月
  let day = zeroFill(date.getDate());//日
  let hour = zeroFill(date.getHours());//时
  let minute = zeroFill(date.getMinutes());//分
  let second = zeroFill(date.getSeconds());//秒

  //当前时间
  var curTime = year + month + day + '_' + hour + minute + second;
  return curTime;
}

async function get_thead_data() {
  let table = document.querySelectorAll('table.table_table__FDV2P')[0];
  // Get the <thead> element
  let thead = table.querySelector('thead');
  let tr_of_thead = thead.querySelectorAll('tr')[0];

  let row_th = []
  let arr_td = tr_of_thead.querySelectorAll('th');
  for (let idx_th = 0; idx_th < arr_td.length; idx_th++) {
    let td = arr_td[idx_th];
    // console.log(td.innerText);
    row_th.push(td.innerText);
  }
  res_data_get_dune_data.push(row_th);


}

async function get_tbody_data() {

  // Get the table element
  let table = document.querySelector('table.table_table__FDV2P');

  // Get the <tbody> element
  let tbody = table.querySelector('tbody');
  // Get all <tr> elements in <tbody>
  let tbodyTrs = tbody.querySelectorAll('tr');

  // Traverse the <tr> elements in <tbody> and get the data
  for (let i = 0; i < tbodyTrs.length; i++) {
    let tr = tbodyTrs[i];
    let row_tr = []
    let arr_td = tr.querySelectorAll('td');
    for (let idx_td = 0; idx_td < arr_td.length; idx_td++) {
      let td = arr_td[idx_td];
      // console.log(td.innerText);

      row_tr.push(td.innerText.split(",")[0])
    }
    res_data_get_dune_data.push(row_tr);
  }

}



async function clickButton_get_data() {
  res_data_get_dune_data = [];
  input_value = ele_input.value.trim();

  await get_thead_data();
  let ul_table_footer__Ky_k2 = document.querySelector('div.visual_vizFooter__vCe59').querySelector("ul.table_footer__Ky_k2");

  let arr_ul_children = ul_table_footer__Ky_k2.children;
  // let page_count = arr_ul_children[4].querySelectorAll("option").length;
  let str_row_num = arr_ul_children[0].innerText.replace(/[\s,a-zA-Z]/g, '');
  let number_row_num = parseInt(str_row_num);
  let page_count = Math.ceil(number_row_num / 25);

  // 获取 页数 并且不断next 页

  for (let cur_page = 1; cur_page <= page_count; cur_page++) {
    console.log('cur_page=', cur_page);
    while (true) {

      try {
        await get_tbody_data();
        break;
      } catch (e) {

        await sleep(3000);
      }

    }
    if (arr_ul_children[5] && arr_ul_children[5].querySelector("button")) {
      let button_next = arr_ul_children[5].querySelector("button");
      button_next.click();
    }
    await sleep(1500);

  }
  res_data_get_dune_data.forEach((val, index, arr) => { arr[index] = val.join() + "\n" });
  res_data_get_dune_data = res_data_get_dune_data.join('')
  let curTime = getCurrentTime();

  let query_id = window.location.pathname.slice(1).split('/').pop();

  funcDownload(res_data_get_dune_data, `${page_name}_${input_value}.csv`);


}


var res_data_get_dune_data = [];
var page_name = 'dune_holders';
var input_value = "xx_xx";
var ele_input;
(async function () {
  console.log("enter load");
  await sleep(6000);
  console.log("create button");

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

  ele_input = document.createElement("input") //创建一个input文本框
  ele_input.value = "xx_xx_xx";
  ele_input.className = "tam-myinput"
  ele_input.type = "text";
  ele_input.style.width = "90px";
  ele_input.style.height = "30px"; // 高度



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

  mydivbox.appendChild(button_);
  mydivbox.style.position = "fixed";
  mydivbox.style.top = "180px";
  mydivbox.style.right = "40px";

  mydivbox.appendChild(ele_input);
  document.body.appendChild(mydivbox);

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



})();