/**
 * 审批中心角标更新测试 - draft(草稿)角标专项
 * 
 * 在浏览器控制台运行:
 *   复制粘贴后回车，自动执行
 * 
 * draft 角标位于 options[3].children[0].tag
 */
(async function testDraftBadge() {
  'use strict';
  const ROUNDS = 5;
  const origLog = console.log;

  // ---- 前置检查 ----
  const menuEl = document.querySelector('.approval-tree-menu');
  if (!menuEl) {
    console.error('❌ 未找到 .approval-tree-menu 组件'); return;
  }

  let baseDraft = null;
  let baseInbox = null;
  let round = 0;

  // ---- 篡改函数 ----
  function tamper(json) {
    if (!(json && json.data && Array.isArray(json.data.options))) return null;
    var opts = json.data.options;
    // inbox = opts[0]
    if (opts[0] && opts[0].hasOwnProperty('tag')) {
      if (baseInbox === null) baseInbox = opts[0].tag;
      opts[0].tag = baseInbox + round;
    }
    // draft = opts[3].children[0]
    if (opts[3] && opts[3].children && opts[3].children[0]) {
      if (baseDraft === null) baseDraft = opts[3].children[0].tag || 0;
      opts[3].children[0].tag = baseDraft + round;
    }
    return json;
  }

  // ---- XHR 拦截 ----
  const XHR = XMLHttpRequest.prototype;
  const _open = XHR.open, _send = XHR.send;
  const _rtDesc = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  const _rDesc = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'response');
  const urlMap = new WeakMap();

  XHR.open = function(m, u) { urlMap.set(this, String(u)); return _open.apply(this, arguments); };
  XHR.send = function() {
    var url = urlMap.get(this);
    if (url && url.includes('/workflow/nav')) {
      var xhr = this, done = false, txt = null;
      Object.defineProperty(xhr, 'responseText', {
        get: function() {
          var real = _rtDesc.get.call(this);
          if (this.readyState === 4 && !done && real) {
            done = true;
            try { var j = JSON.parse(real); if (tamper(j)) txt = JSON.stringify(j); } catch(e) {}
          }
          return txt || real;
        }, configurable: true
      });
      Object.defineProperty(xhr, 'response', {
        get: function() {
          var t = xhr.responseText;
          if (xhr.responseType === '' || xhr.responseType === 'text') return t;
          if (xhr.responseType === 'json' && txt) try { return JSON.parse(txt); } catch(e) {}
          return _rDesc.get.call(this);
        }, configurable: true
      });
    }
    return _send.apply(this, arguments);
  };

  // ---- fetch 拦截 ----
  const _fetch = window.fetch;
  window.fetch = async function(...a) {
    var r = await _fetch.apply(this, a);
    var u = typeof a[0] === 'string' ? a[0] : (a[0] && a[0].url) || '';
    if (u.includes('/workflow/nav')) {
      try {
        var c = r.clone(), j = await c.json();
        if (tamper(j)) return new Response(JSON.stringify(j), { status: r.status, headers: r.headers });
      } catch(e) {}
    }
    return r;
  };

  // ---- DOM 读取 ----
  function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }

  function getAllBadges() {
    return menuEl.querySelectorAll('.ant-badge-count');
  }

  function findBadgeByLabel(label) {
    const nodes = menuEl.querySelectorAll('.ant-tree-treenode');
    for (const node of nodes) {
      const labelEl = node.querySelector('.approval-tree-menu__label');
      if (labelEl && labelEl.textContent.includes(label)) {
        const badge = node.querySelector('.ant-badge-count');
        if (badge) return parseInt(badge.textContent.trim(), 10);
      }
    }
    return null;
  }

  // ---- 初始化 ----
  origLog.call(console, '%c=== Draft 角标测试 ===', 'color:blue;font-size:14px;font-weight:bold');
  round = 0;
  window.postMessage({ type: "approval-tree-menu:reload" }, "*");
  await sleep(4000);

  if (baseDraft === null) {
    console.error('未能获取基准 draft 值，API 未被拦截');
    window.fetch = _fetch; XHR.open = _open; XHR.send = _send; return;
  }
  origLog.call(console, '基准值: inbox=' + baseInbox + ', draft=' + baseDraft);

  // ---- 测试轮 ----
  var results = [];
  for (var i = 1; i <= ROUNDS; i++) {
    round = i;
    var expInbox = baseInbox + i;
    var expDraft = baseDraft + i;
    origLog.call(console, '--- 第' + i + '轮: 期望 inbox=' + expInbox + ', draft=' + expDraft);

    window.postMessage({ type: "approval-tree-menu:reload" }, "*");
    await sleep(3000);

    var domInbox = getAllBadges()[0] ? parseInt(getAllBadges()[0].textContent.trim(), 10) : null;
    var domDraft = findBadgeByLabel('草稿') || findBadgeByLabel('Draft') || findBadgeByLabel('draft');

    var inboxOk = domInbox === expInbox;
    var draftOk = domDraft === expDraft;
    results.push({ round: i, expInbox, domInbox, inboxOk, expDraft, domDraft, draftOk, pass: inboxOk && draftOk });

    var icon = (inboxOk && draftOk) ? '✅' : '❌';
    origLog.call(console, icon + ' inbox:' + domInbox + '/' + expInbox + (inboxOk?' OK':' FAIL') +
      ' | draft:' + domDraft + '/' + expDraft + (draftOk?' OK':' FAIL'));

    if (!(inboxOk && draftOk)) {
      origLog.call(console, '全部badges:', Array.from(getAllBadges()).map(e => e.textContent.trim()));
      break;
    }
    await sleep(500);
  }

  // ---- 恢复 ----
  window.fetch = _fetch; XHR.open = _open; XHR.send = _send;

  // ---- 报告 ----
  var p = results.filter(r => r.pass).length;
  origLog.call(console, '%c=== 结果: ' + p + '/' + results.length + ' 通过 ===',
    p === results.length ? 'color:green;font-size:14px' : 'color:red;font-size:14px');
  console.table(results);
})();
