// const _text_styles_ = ["bold", "underline", "italic", "sup", "sub"];

/**
 * 将富文本 JSON 渲染到指定的元素中
 *
 * @param {RichTextJSON} body
 * @param {HTMLDivElement} container
 */
export function renderRichText(body, container) {
  let sections = body?.sections || [];
  let nodes = [];
  sections.forEach((section) => {
    nodes.push(renderSection(section));
  });
  if (container != undefined) {
    // container.classList.add("rich-text");
    while (container.hasChildNodes()) {
      container.removeChild(container.lastChild);
    }
    nodes.forEach((node) => {
      container.appendChild(node);
    });
  }
}

/**
 * @param {RichTextSectionJSON} section
 * @returns {HTMLDivElement} 返回根据 section 渲染好的 HTMLDivElement
 */
function renderSection(section) {
  let blocks = section.blocks || [];
  let inline = blocks.length > 1;
  let node = document.createElement("div");
  // node.style = "display: flex;";
  blocks.forEach((block) => {
    node.appendChild(renderBlock(block, inline));
  });
  return node;
}

/**
 * @param {RichTextBlockJSON} block
 * @param {Boolean} inline 图片是否以 inline 的样式展示
 * @returns {HTMLElement} 返回根据 block 渲染好的 HTMLElement
 */
function renderBlock(block, inline) {
  // let node = document.createElement('span')
  // let classList = node.classList
  let node;
  if (block.type === "text") {
    if (
      block.param &&
      ["underline", "bold", "italic"].some((item) => block.param[item])
    ) {
      let uNode, bNode, iNode;
      if (block.param.underline) {
        uNode = document.createElement("u");
      }
      if (block.param.bold) {
        bNode = document.createElement("b");
      }
      if (block.param.italic) {
        iNode = document.createElement("i");
      }
      // 将不为空的元素依次append
      node = [uNode, bNode, iNode]
        .filter((v) => v)
        .reduceRight((p, c) => {
          c.appendChild(p);
          return c;
        });

      let childNode = node;

      for (let i = 0; i < 3; i++) {
        if (childNode && childNode.hasChildNodes()) {
          childNode = childNode.childNodes[0];
        }
      }
      childNode.textContent = block.value;
    } else {
      node = document.createTextNode(block.value);
    }

    // TODO: 兼容旧版填空题答题点做的修改，后续可以删除
    if (block.param && block.param.display) {
      node.style.display = block.param.display;
    }
  } else if (block.type === "image") {
    node = document.createElement("img");
    if (inline === true) {
      node.classList.add("inline");
    }
    node.src = block.value;
    node.dataset.isImage = true;
    // 公式latex表达式
    if (block.latex) node.dataset.latex = block.latex;
    // param
    if (block.param) {
      node.style.width = block.param.width;
      node.style.height = block.param.height;
    }
  } else if (block.type === "cloze") {
    node = document.createElement("img");
    node.src = getAnswerPointImg(block.value);
    node.dataset.isAnswerPoint = true;
    node.dataset.order = block.value;
  } else if (block.type === "audio") {
    node = document.createElement("audio");
    node.className = "audio";
    node.src = block.value;
    node.controls = true;
    node.controlsList = "nodownload";
  }

  return node;
}

/**
 * @param {Array} content
 * @returns rich json
 */
export function createRichJsonFromText(content) {
  if (content && content.length) {
    const blocks = content.map((cont) => {
      return {
        type: "text",
        value: cont,
      };
    });
    return {
      sections: [
        {
          blocks,
        },
      ],
    };
  } else {
    return {
      sections: [
        {
          blocks: [],
        },
      ],
    };
  }
}

/**
 * 百以下数字转中文汉字
 * @param {Number} num 大于0的100以下数字，其他数值直接转字符串
 *
 * @returns {String}
 */
export function numberToChinese(num) {
  if (num >= 100 || num <= 0) return num + "";
  const cnNums = "一二三四五六七八九十".split("");
  if (num <= 10) return cnNums[num - 1];

  return (num + "")
    .split("")
    .map((item) => item * 1)
    .map((item, index) => {
      if (index) {
        return !item ? "" : cnNums[item - 1];
      } else {
        return item === 1 ? "" : cnNums[item - 1];
      }
    })
    .join("十");
}

/**
 *
 * @param {Number} val 数值，1到26
 */
export function numberToUpperCase(val) {
  if (val < 1 || val > 26) return;

  return String.fromCharCode(64 + val);
}

/**
 * 获取答题点序号图片base64
 * @param {number} serialNo 答题点序号
 * @returns dataUrl
 */
export function getAnswerPointImg(serialNo) {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  canvas.width = 64;
  canvas.height = 32;
  ctx.font = "bolder 30px serif";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillText(`（${serialNo}）`, 32, 16);
  return canvas.toDataURL();
}
