kk-helper

个人开发常用帮助脚本

当前为 2023-09-06 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         kk-helper
// @namespace    https://greasyfork.org
// @homepage    https://greasyfork.org
// @version      0.9.3
// @description  个人开发常用帮助脚本
// @author       #stephenykk
// @match        https://juejin.cn/post/*
// @match        https://blog.csdn.net/*/article/details/*
// @match        https://www.jianshu.com/p/*
// @match        https://segmentfault.com/a/*
// @match        https://mp.weixin.qq.com/s*
// @match        https://zhuanlan.zhihu.com/p/*
// @match        https://sspai.com/post/*
// @match        *://www.news.cn/*/**/*.htm*
// @match        *://*.people.com.cn/*/**/*.htm*
// @icon         https://res.wx.qq.com/a/fed_upload/9300e7ac-cec5-4454-b75c-f92260dd5b47/logo-mp.ico
// @grant        none
// @license MIT
// ==/UserScript==

(function () {
  "use strict";
  function log(...args) {
    console.log("[KKCopy]", ...args);
  }

  function checkEnable() {
    if (/qq\.com/.test(location.host)) {
      return false;
    }
    return true;
  }

  if (!checkEnable()) return;

  const autoClick = (ele, callback, seconds = 2) => {
    console.log('try auto click ele:', ele);
    ele.click()
    callback && setTimeout(callback, seconds * 1000)
  }

  function autoClickPrereleaseBtn() {
    if (
      location.href.includes(
        "https://devops-cloud.bgy.com.cn/ext/@console-plugin/cd/5e787768cc788/deploy/host-deploy"
      )
    ) {

      const autoClickNextBtn2 = () => {
        const btn = document.querySelector('.grid-card .steps + .btn')
        autoClick(btn, autoCheck2)
      }

      const autoClickNextBtn3 = () => {
        const btn = document.querySelector('.grid-card .steps + .btn')
        autoClick(btn, autoClickNextBtn4)
      }

      const autoClickNextBtn4 = () => {
        const btn = document.querySelector('.grid-card .steps + .btn')
        autoClick(btn)
      }

      const autoClickNextBtn = () => {
        const btn = document.querySelector('.grid-card .steps + .btn')
        autoClick(btn, autoClickNextBtn2)
      }

      const autoCheck1 = () => {
        const labelEle = document.querySelector('.cluster-info label')
        autoClick(labelEle, autoClickNextBtn, 1)
      }

      const autoCheck2 = () => {
        const labelEle = document.querySelector('.package-grid .ui-checkbox')
        autoClick(labelEle, autoClickNextBtn3, 1)
      }

      setTimeout(() => {
        const btnEle = document.querySelector(".cluster-type-btn-group .btn:nth-of-type(2)");
        btnEle && btnEle.textContent.includes('预发布') && autoClick(btnEle, autoCheck1)
      }, 3000);
    }
  }

  autoClickPrereleaseBtn()

  function autoClickHostDeploy() {
    if (
      // location.href.includes(
      //   "https://devops-cloud.bgy.com.cn/ext/@console-plugin/cd/5e787768cc788/deploy"
      // )
      location.href === 'https://devops-cloud.bgy.com.cn/ext/@console-plugin/cd/5e787768cc788/deploy'
    ) {
      setTimeout(() => {
        const cardEle = document.querySelector(".manual-card-container .card:first-child");
        cardEle && autoClick(cardEle, autoClickPrereleaseBtn, 3)
      }, 3000);
    }
  }


  function createBtn(text, listener, style='') {
    //   if (this.mybtn) return;
    const btn = document.createElement("button");
    btn.textContent = text || "Submit";
    btn.className = "mybtn";
    btn.setAttribute('data-txt', text);
    btn.style =
      "position: fixed; right: 520px; font-size: 30px; z-index: 100000; top: 0; border: 0; background: aliceblue; color: coral; padding: 0 20px; border-radius: 5px; cursor: pointer;" + style;
    document.body.appendChild(btn);
    btn.addEventListener('click', listener)
     console.log('createBtn: btn=', btn);
    //   this.mybtn = btn;
    return btn;
  }

  function addAutoDeployBtn(times) {
    if (times < 1) return;
    setTimeout(() => {

      if (location.href === 'https://devops-cloud.bgy.com.cn/ext/@console-plugin/cd/5e787768cc788/deploy') {
        createBtn('autoDeploy', autoClickHostDeploy)
      } else {
          addAutoDeployBtn(times - 1)
      }
    }, 1000)
  }

  addAutoDeployBtn(5)

  // autoClickHostDeploy()

  function autoClickLogin() {
    if (
      location.href.includes(
        "/auth/realms/bgy/protocol/openid-connect/auth?client_id"
      )
    ) {
      setTimeout(() => {
        const link = document.querySelector("#zocial-bgy");
        link && link.click();
      }, 2000);
    }


    // if(location.href.includes('https://loginuat.countrygarden.com.cn/idp/authcenter/ActionAuthChain')) {
    //   setTimeout(() => {
    //     const btn = document.querySelector(".loginBt");
    //     btn && btn.click();
    //   }, 4000);
    // }
  }

  autoClickLogin();

  function checkCopyEnable() {
    const disable = ["countrygarden", "localhost"].some((kw) =>
      location.href.includes(kw)
    );
    return !disable;
  }

  function mycopy(text) {
    if (!checkCopyEnable()) return;

    let input = document.querySelector("#myInputEle");
    if (!input) {
      const inpEle = document.createElement("input");
      inpEle.type = "text";
      document.body.insertBefore(inpEle, null);
      inpEle.style = "position: fixed; top: -100px; right: 0; z-index: 10000;";
      inpEle.setAttribute("id", "myInputEle");
      input = inpEle;

      const btn = document.createElement("button");
      btn.id = "myCpBtn";
      // document.body.insertBefore(btn, inpEle)
      // btn.style = 'position: fixed; top: 0; left: 0; z-index: 1000'
      // btn.textContent = 'copy url'
      const doCopy = function () {
        input.select();
        input.setSelectionRange(0, input.value.length);
        document.execCommand("copy");
        log("copy done");
      };

      document.body.addEventListener("dblclick", doCopy);
    }

    input.value = text;
  }

  // eslint-disable-next-line
  mycopy(`[${document.title}](${location.href})`);

  function closeNoticeDialog(times = 1) {
    const maxtimes = 100;
    const button = document.querySelector(".notice_content + .footer button");
    if (button) {
      button.click();
    } else {
      setTimeout(closeNoticeDialog.bind(null, times + 1), 1000);
    }
  }

  closeNoticeDialog();

  function $(selector) {
    return document.querySelector(selector);
  }

  class DevopsBuild {
    constructor(sysName, isProd) {
      const srmBuildUrl =
        "https://devops-cloud.bgy.com.cn/next/ci/project/5f6c900f4251e/build";
      const gysSrmBuildUrl =
        "https://devops-cloud.bgy.com.cn/next/ci/project/5f70e768c3590/build";
      const ispBuildUrl =
        "https://devops-cloud.bgy.com.cn/next/ci/project/5de90b7183a5b/build";
      const intBuildUrl = "https://devops-cloud.bgy.com.cn/next/ci/project/5f6a0872bfc2b/build"
      const urls = {
        srm: srmBuildUrl,
        isp: ispBuildUrl,
        int: intBuildUrl,
        'gys-srm': gysSrmBuildUrl,
      };

      const buildUrl = urls[sysName];
      if (!buildUrl) {
        alert("sysName not valid");
      }

      this.isProd = isProd;
      this.sysName = sysName;
      this.buildUrl = buildUrl;
    }

    start() {
      if (
        location.href.startsWith("https://devops-cloud.bgy.com.cn/") === false
      )
        return;

      this.btn = this.createBtn();
      this.checkShouldShowBtn();
      this.decoratePushState();
      this.listenClickBtn();

      this.constructor.prototype.pushStateCallbackList =
        this.constructor.prototype.pushStateCallbackList || [];

      this.pushStateCallbackList.push(this.pushStateCallback.bind(this));
    }

    listenClickBtn() {
      this.btn.addEventListener("click", () => {
        this.send();
      });
    }

    createBtn() {
      if (this.btn) return;
      const btn = document.createElement("button");
      btn.textContent = this.sysName + ` build ${this.isProd ? 'prod' : 'uat'}`;
      btn.className = `build-${this.isProd ? 'prod' : 'uat'}-btn-` + this.sysName;
      const right = this.isProd ? '700px' : '250px';
      btn.style =
        `position: fixed; right: ${right}; font-size: 30px; z-index: 100; top: 0; border: 0; background: aliceblue; color: coral; padding: 0 20px; border-radius: 5px; cursor: pointer;`;
      document.body.appendChild(btn);
      return btn;
    }

    pushStateCallback() {
      this.checkShouldShowBtn();
    }

    decoratePushState() {
      if (!history.pushState.isMy) {
        const pushState = history.pushState;

        // eslint-disable-next-line
        const self = this;
        history.pushState = function myPushState(...args) {
          // console.log('=====> pushState call', args, self.pushStateCallbackList)
          self.pushStateCallbackList.forEach((cb) => cb());
          pushState.apply(history, args);
        };
        history.pushState.isMy = true;
      }
    }

    checkShouldShowBtn() {
      setTimeout(() => {
        const shouldShow = location.href.startsWith(this.buildUrl);
        this.btn.style.display = shouldShow ? "inline-block" : "none";

        if (shouldShow) {
          setTimeout(() => this.clickFirstRow(), 3000);
        }
      }, 2000);
    }

    sendForSRM() {
      fetch(
        "https://devops-cloud.bgy.com.cn/next/api/gateway/pipeline.pipeline.Execute/api/pipeline/v1/projects/5f6c900f4251e/pipelines/5f6c903b924f0/execute",
        {
          headers: {
            accept: "*/*",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "content-type": "application/json",
            lang: "zh",
            pragma: "no-cache",
            "sec-ch-ua":
              '"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
          },
          referrer:
            "https://devops-cloud.bgy.com.cn/next/ci/project/5f6c900f4251e/build",
          referrerPolicy: "strict-origin-when-cross-origin",
          body: `{"inputs":[{"name":"env_param","value":"${this.isProd ? 'prod' : 'uat'}"}],"branch":"${this.isProd ? 'prod' : 'uat'}"}`,
          method: "POST",
          mode: "cors",
          credentials: "include",
        }
      );
      const isBuildingDetail = /build\/\w+$/.test(location.href);
      setTimeout(() => {
        let buildListUrl = "";
        if (!isBuildingDetail) {
          buildListUrl = location.href;
        } else {
          buildListUrl = location.href.replace(/build\/\w+$/, "build");
        }
        location.href = buildListUrl + "?clickfirst=1";
      }, 1000);
    }
    sendForINT() {
      fetch("https://devops-cloud.bgy.com.cn/next/api/gateway/pipeline.pipeline.Execute/api/pipeline/v1/projects/5f6a0872bfc2b/pipelines/5f6a08ea27a78/execute", {
        "headers": {
          "accept": "*/*",
          "accept-language": "zh-CN,zh;q=0.9",
          "content-type": "application/json",
          "lang": "zh",
          "sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"",
          "sec-ch-ua-mobile": "?0",
          "sec-ch-ua-platform": "\"Windows\"",
          "sec-fetch-dest": "empty",
          "sec-fetch-mode": "cors",
          "sec-fetch-site": "same-origin"
        },
        "referrer": "https://devops-cloud.bgy.com.cn/next/ci/project/5f6a0872bfc2b/build",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": "{\"inputs\":[{\"name\":\"env_param\",\"value\":\"uat\"}],\"branch\":\"uat\"}",
        "method": "POST",
        "mode": "cors",
        "credentials": "include"
      });
      
      const isBuildingDetail = /build\/\w+$/.test(location.href);
      setTimeout(() => {
        let buildListUrl = "";
        if (!isBuildingDetail) {
          buildListUrl = location.href;
        } else {
          buildListUrl = location.href.replace(/build\/\w+$/, "build");
        }
        location.href = buildListUrl + "?clickfirst=1";
      }, 1000);
    }

    clickFirstRow() {
      const uparams = new URLSearchParams(location.search.replace(/^\?/, ""));
      if (!uparams.get("clickfirst")) return;
      const link = document.querySelector(
        ".ant-table-tbody tr:nth-child(2) a:first-child"
      );
      if (!link) {
        console.log("not found first row link");
        return;
      }
      link.click();
    }

    sendForISP() {
      fetch(
        "https://devops-cloud.bgy.com.cn/next/api/gateway/pipeline.pipeline.Execute/api/pipeline/v1/projects/5de90b7183a5b/pipelines/5f1f7ed6f1977/execute",
        {
          headers: {
            accept: "*/*",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "content-type": "application/json",
            lang: "zh",
            pragma: "no-cache",
            "sec-ch-ua":
              '"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
          },
          referrer:
            "https://devops-cloud.bgy.com.cn/next/ci/project/5de90b7183a5b/build",
          referrerPolicy: "strict-origin-when-cross-origin",
          body: '{"inputs":[{"name":"env_param","value":"uat"}],"branch":"uat"}',
          method: "POST",
          mode: "cors",
          credentials: "include",
        }
      );

      const isBuildingDetail = /build\/\w+$/.test(location.href);
      setTimeout(() => {
        let buildListUrl = "";
        if (!isBuildingDetail) {
          buildListUrl = location.href;
        } else {
          buildListUrl = location.href.replace(/build\/\w+$/, "build");
        }
        location.href = buildListUrl + "?clickfirst=1";
      }, 1000);
    }

    sendForGysSrm() {
      fetch("https://devops-cloud.bgy.com.cn/next/api/gateway/pipeline.pipeline.Execute/api/pipeline/v1/projects/5f70e768c3590/pipelines/5f70e769f11f9/execute", {
        "headers": {
          "accept": "*/*",
          "accept-language": "zh-CN,zh;q=0.9",
          "cache-control": "no-cache",
          "content-type": "application/json",
          "lang": "zh",
          "pragma": "no-cache",
          "sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"",
          "sec-ch-ua-mobile": "?0",
          "sec-ch-ua-platform": "\"Windows\"",
          "sec-fetch-dest": "empty",
          "sec-fetch-mode": "cors",
          "sec-fetch-site": "same-origin"
        },
        "referrer": "https://devops-cloud.bgy.com.cn/next/ci/project/5f70e768c3590/build",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": "{\"inputs\":[{\"name\":\"env_param\",\"value\":\"uat\"}],\"branch\":\"uat\"}",
        "method": "POST",
        "mode": "cors",
        "credentials": "include"
      });

      const isBuildingDetail = /build\/\w+$/.test(location.href);
      setTimeout(() => {
        let buildListUrl = "";
        if (!isBuildingDetail) {
          buildListUrl = location.href;
        } else {
          buildListUrl = location.href.replace(/build\/\w+$/, "build");
        }
        location.href = buildListUrl + "?clickfirst=1";
      }, 1000);
    }

    send() {
      const sends = {
        srm: this.sendForSRM,
        isp: this.sendForISP,
        int: this.sendForINT,
        'gys-srm': this.sendForGysSrm,
      };

      const send = sends[this.sysName];
      if (send) {
        send.call(this);
      }
    }
  }

  const srmBuild = new DevopsBuild("srm");
  srmBuild.start();
  const srmProdBuild = new DevopsBuild("srm", true);
  srmProdBuild.start();
  const ispBuild = new DevopsBuild("isp");
  ispBuild.start();
  const intBuild = new DevopsBuild("int");
  intBuild.start();
  const gyssrmBuild = new DevopsBuild("gys-srm");
  gyssrmBuild.start();

  // isp uat 登录自动填充
  class FormFiller {
    constructor(enableUrl, values, btn) {
      this.url = enableUrl;
      this.values = values;
      this.btn = btn;
    }

    element(selector) {
      return document.querySelector(selector);
    }

    fill() {
      const inputSelectors = Object.keys(this.values);
      const inputValues = Object.values(this.values);
      inputSelectors.forEach((inpSelctor, i) => {
        const input = this.element(inpSelctor);
        if (input) {
          input.value = inputValues[i];
        } else {
          console.log("not found element for", inpSelctor);
        }
      });
    }

    submit() {
      if (this.btn.selector) {
        const submitBtn = this.element(this.btn.selector);
        submitBtn?.click();
        return;
      }

      console.log("not found submitBtn cancel", this.btn); // debug only
    }

    createBtn() {
      //   if (this.mybtn) return;
      const btn = document.createElement("button");
      btn.textContent = this.btn.text || "Submit";
      btn.className = "mybtn";
      btn.style =
        "position: fixed; right: 250px; font-size: 30px; z-index: 100; top: 0; border: 0; background: aliceblue; color: coral; padding: 0 20px; border-radius: 5px; cursor: pointer;";
      document.body.appendChild(btn);
      //   this.mybtn = btn;
      return btn;
    }

    start() {
      if (location.href.includes(this.url) === false) return;

      this.mybtn = this.createBtn();
      this.mybtn.addEventListener("click", () => {
        this.fill();
        this.submit();
      });
    }
  }

  const ISPUatFormFiller = new FormFiller(
    "https://ssploginuat.",
    {
      "#j_username": "gys_zengzhaohua",
      "#j_password": "0Jqg0eny",
    },
    {
      selector: ".loginBt",
      text: "zengzhaohua Login",
    }
  );

  ISPUatFormFiller.start();


  const SRMUatFormFiller = new FormFiller(
    "https://loginuat.countrygarden.com.cn/idp/authcenter",
    {
      "#j_username": "penghaitao01",
      "#j_password": "password",
    },
    {
      selector: ".loginBt",
      text: "penghaitao Login",
    }
  );

  SRMUatFormFiller.start()

  const SRMProdFormFiller = new FormFiller(
    "/idp/authcenter/ActionAuth",
    {
      "#j_username": "gys_zengzhaohua",
    },
    {
      selector: ".loginBt",
      text: "zengzhaohua Login",
    }
  );
  //SRMProdFormFiller.start()

  //  选择供应商
  class SupplierSelector {
    constructor(enableUrl, values, submitBtnSelector, selectSelector) {
      this.url = enableUrl;
      this.values = values;
      this.submitBtnSelector = submitBtnSelector
      this.selectSelector = selectSelector;
    }

    element(selector) {
      return document.querySelector(selector);
    }

    fill(val) {
      this.element(this.selectSelector).value = val;
    }

    submit() {
      this.element(this.submitBtnSelector).click();
    }

    createBtns() {
      //   if (this.mybtn) return;
      const actionDiv = document.createElement("div");
      actionDiv.className = "actions";
      actionDiv.style =
        "position: fixed; left: 550px;  z-index: 100000; top: 0;";

      const btnStyle =
        "font-size: 20px; border: 0; background: aliceblue; color: coral; padding: 0 20px; border-radius: 5px; cursor: pointer; margin: 0 10px;";
      this.values.forEach((option) => {
        const btn = document.createElement("button");
        btn.className = "mybtn" + option.val;
        btn.textContent = option.text;
        btn.style = btnStyle;
        actionDiv.appendChild(btn);
        btn.addEventListener("click", () => {
          this.fill(option.val);
          this.submit();

          actionDiv.style.display = 'none'
        });
      });
      document.body.appendChild(actionDiv);
    }

    start() {
      if (typeof this.url === 'string' && location.href.includes(this.url) === false) return;
      if (this.url instanceof RegExp && this.url.test(location.href) === false) return;

      this.createBtns();
    }
  }

  const supplierAutoSelector = new SupplierSelector(
    /sispuat.countrygarden.com.cn\/[^?]*?\?access_token=/,
    [
      { val: "1566579841157664769", text: "中建三局" },
      { val: "1566700513699684354", text: "广东腾越" },
      { val: "1572034947512098817", text: "测试供应商001" },
      { val: "1566761465878519810", text: "四川建设" },
      { val: "1566723359788359681", text: "佛山科达机电" },
    ],
    ".el-message-box__btns .el-button",
    "#supplierSselect"
  );

  supplierAutoSelector.start();

  function redirectToISPUATTenderList(canTryTimes) {
    if (!canTryTimes) return
    if (location.href === 'https://sispuat.countrygarden.com.cn/#/Home') {
      setTimeout(() => {
        location.href = 'https://sispuat.countrygarden.com.cn/#/isp/tender-list'
      }, 1000)
    } else {
      setTimeout(() => redirectToISPUATTenderList(canTryTimes - 1), 1000);
    }
  }

  redirectToISPUATTenderList(100)
})();


(function () {
  function clearStorageAndCookie(isrefresh = true) {
    [sessionStorage, localStorage].forEach((storage) => storage.clear());
    clearCookies();
    console.log(document.cookie, "done!!");
    isrefresh && setTimeout(location.reload.bind(location), 1000);
  }

  function pick(data, keys) {
    return keys.reduce((ret, key) => {
      ret[key] = data[key];
      return ret;
    }, {});
  }

  function setLocalStorage(data) {
    Object.keys(data).forEach((key) => {
      localStorage[key] = data[key];
    });

    console.log("done", localStorage);
  }

  function getCookies() {
    return document.cookie.match(/[\w-]+(?=\=[^;]+)/g) || [];
  }

  function clearCookies() {
    getCookies().forEach((cname) => {
      delCookie(cname);
    });
  }

  function setCookie(cname, cvalue, exdays) {
    const d = new Date();
    d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
    const expires = "; Expires=" + d.toUTCString();
    // document.cookie = cname + "=" + cvalue + expires + "; Path=/";
    document.cookie = cname + "=" + cvalue + expires;
  }

  function delCookie(cname) {
    console.log("del cookie:", cname);
    setCookie(cname, "", -1);
  }

  function copy(str) {
    const el = document.createElement("textarea");
    el.value = str;
    el.setAttribute("readonly", "");
    el.style.position = "absolute";
    el.style.left = "-9999px";
    document.body.appendChild(el);
    el.select();
    document.execCommand("copy");
    document.body.removeChild(el);
  }

  function setDebugSwitch(key, val = 1) {
    // localStorage.debug = localStorage.debug + 'schema;domain;zxhbEdit=1'
    const debugval = localStorage.debug || ''
    const pairs = debugval.split(';').map(pair => pair.includes('=') ? pair.split('=') : (pair + '=true').split('='))
    const conf = Object.fromEntries(pairs)
    conf[key] = val
    console.log('new conf:', conf)
    const entriesVal = Object.entries(conf).map(pair => pair.join('=')).join(';')
    localStorage.debug = entriesVal
  }
  
  function debugDomainSchema() {
    setDebugSwitch('domain')
    setDebugSwitch('schema')
  }

  function copyISPSupplierInfo() {
    copy(
      `localStorage.gys_cur_supplier_info = ${JSON.stringify(
        localStorage.gys_cur_supplier_info
      )}; setTimeout(() => location.reload(), 1000);`
    );
    console.log("copy done");
  }

  function getSchema(data = {}) {
    const result = Object.keys(data)
      .sort()
      .reduce((ret, key) => {
        return ret + `${key}    ${data[key].title}\n`;
      }, "");
    console.log(result);
    copy(result);
  }

  function toUnicode(str) {
    const ls = str.split("");
    const result = ls
      .map((c) => {
        if (/\w/.test(c)) return c;

        return "\\u" + c.charCodeAt(0).toString(16).toUpperCase();
      })
      .join("");

    copy(result);
    console.log("copy done");
    return result;
  }


  function getk2Params() {
    return Object.assign({}, window.KStarForm.vmFormData.vmFormContent);
  }

  function isPlainObject(val) {
    return Object.prototype.toString.call(val).slice(8, -1) === "Object";
  }

  function getTableTypeDefines(vm) {
    const { tableData, schema } = vm.props ?? {};
    if (!tableData) {
      console.warn("not tableData found:", vm.props);
      return;
    }

    return getTypeDefines(tableData[0], schema);
  }

  function getTypeDefines(obj = {}, schema = false, level = 10) {
    // if (Array.isArray(obj)) {
    //   if (obj.length === 0) {
    //     return 'Array<any>'
    //   }
    //   return `Array<${getTypeDefines(obj[0], schema, level - 1)}>`
    // }
    if (Array.isArray(obj)) {
      obj = obj[0];
    }

    const getPrimativeType = (key, val) => {
      let type = typeof val;
      let text = "";

      if (!schema) {
        return { type, text };
      }

      const props = schema.properties ?? {};
      if (props[key]) {
        type = props[key].type;
        text = props[key].title;
      }

      return { type, text };
    };
    let ret = "{\n";
    Object.keys(obj).forEach((key) => {
      if (key.startsWith("_")) return;
      const val = obj[key];
      const isPrimative = !isPlainObject(val) && !Array.isArray(val);
      let title = "";
      let valType;
      if (isPrimative) {
        const { type, text } = getPrimativeType(key, val);
        valType = type;
        title = text;
      } else {
        valType = getTypeDefines(val, schema);
      }

      const keyDefine = `${key}: ${valType};${title ? " // " + title : ""}\n`;
      ret += keyDefine;
    });
    ret += "\n}";

    copy(ret);
    console.log("copy done!");
    return ret;
  }

  window.my = {
    getTableTypeDefines,
    getk2Params,
    toUnicode,
    getSchema,
    copyISPSupplierInfo,
    setLocalStorage,
    pick,
    clearStorageAndCookie,
    setDebugSwitch,
    debugDomainSchema,
  }
})();