// 字母列标
export function getColumnHeaderCode(len) {
  let tag_arr = [];
  for(let i=0;i<len;i++) tag_arr.push(String.fromCharCode(65+i));
  return tag_arr;
}

// 行标
export function getRowHeaderCode(len) {
  let tag_arr = [];
  for(let i=0;i<len;i++) tag_arr.push(String(1+i));
  return tag_arr;
}

//过滤输入空格
export function filterInput(input) {
  return input.replace(/\s+/g, '');
}

//从公式中提取因数
export function extractFactorsFromFormula(str) {
  let pattern = /[A-Za-z]+\d+/g;
  let factors = str.match(pattern);

  // 提取括号内的内容作为因数
  let parenthesesPattern = /\([^()]+\)/g;  // 匹配括号内的内容
  let parenthesesMatches = str.match(parenthesesPattern);
  if (parenthesesMatches) {
    for (let i = 0; i < parenthesesMatches.length; i++) {
      let parenthesesContent = parenthesesMatches[i].slice(1, -1);  // 去除括号
      let subFactors = extractFactorsFromFormula(parenthesesContent);
      factors = factors.concat(subFactors);
    }
  }
  return factors.filter ((value, index, self) => self.indexOf(value) === index);
}

//根据因数找元素值
export function findCellByFactor (str) {
  let newStr = splitString(toUpperCase(str));

  let table = document.querySelector('.table');
  let el = table.querySelector("td span[data-rindex='" + newStr[1] + "'][data-cindex='" + newStr[0] + "']") || table.querySelector("td input[data-rindex='" + newStr[1] + "'][data-cindex='" + newStr[0] + "']");

  return el ? (el.innerText||'') : null;
}

//转大写
export function toUpperCase(str) {
  let uppercaseStr = str.toUpperCase();
  return uppercaseStr;
}

//拆分A1为['A','1']
export function splitString(str) {
  let letter = str.match(/[A-Z]+/)[0];
  let number = str.match(/\d+/)[0];
  return [letter, number];
}

//选中整行整列样式
export function selectMoreCellStyle(e,type=null) {
  let table = document.querySelector('.table');
  resetStyle();

  if($(e.target).hasClass('th-col')) { //点击列
    // 指标列 日期列显示显示有所区分
    const columnIndex = Array.from(e.target.parentNode.children).indexOf(e.target);
    table.rows.forEach((cell,index)=> {

      if(index !==0) {
        if(type === 1) index === 2 ? $(cell.children[columnIndex-1]).addClass('td-col-select') : $(cell.children[columnIndex]).addClass('td-col-select');

        if(type === 2) index === 1 ? $(cell.children[columnIndex-1]).addClass('td-col-select') : $(cell.children[columnIndex]).addClass('td-col-select');

        if(!type) $(cell.children[columnIndex]).addClass('td-col-select');
      }
    })
  }else if($(e.target).hasClass('th-row')) { //点击行
    e.target.parentNode.children.forEach((cell,index)=> {
      if(index !==0) {
        index === 2 ? $(cell).addClass('td-row-select') : $(cell).addClass('td-row-select');
      }
    })
  }


}

// 选中格子样式
export function selectCellStyle(e) {
  let table = document.querySelector('.table');
  resetStyle();

  if (table.querySelectorAll(".td-chose").length == 0) {
      e.target.nodeName==='TD' && $(e.target).addClass("td-chose")     

      e.target.parentNode.nodeName==='TD' && $(e.target.parentNode).addClass("td-chose")

      e.target.parentNode.parentNode.nodeName==='TD' && $(e.target.parentNode.parentNode).addClass("td-chose")

      e.target.parentNode.parentNode.parentNode.nodeName==='TD' && $(e.target.parentNode.parentNode.parentNode).addClass("td-chose")
  }
}

export function resetStyle() {
  let table = document.querySelector('.table');
  table.querySelectorAll(".td-chose").forEach(el => {
    el.classList.remove('td-chose')
  })
  table.querySelectorAll(".td-col-select").forEach(el => {
    el.classList.remove('td-col-select')
  })
  table.querySelectorAll(".td-row-select").forEach(el => {
    el.classList.remove('td-row-select')
  })
  table.querySelectorAll(".td-relation").forEach(el => {
    el.classList.remove('td-relation')
  })
}

//单击聚焦
export function setFocus(e) {
  if(e.target.nodeName==='TD') {
    let input = e.target.querySelector('input');
    input && input.focus();
  }
}

// 插入值或公式有插值后设置背景色
export function setCellBg(e) {

  e.target.parentNode.nodeName==='TD' && $(e.target.parentNode).addClass("insert")

  e.target.parentNode.parentNode.nodeName==='TD' && $(e.target.parentNode.parentNode).addClass("insert")
}

//右键菜单
export function getRightClickMenu(pos) {
  const menuMap = {
    'col': [
      { label: "向左插入列", key: "insert-col-left" },
      { label: "向右插入列", key: "insert-col-right" },
      { label: "删除", key: "del" },
    ],
    'row': [
      { label: "向上插入行", key: "insert-row-up" },
      { label: "向下插入行", key: "insert-row-down" },
      { label: "删除", key: "del" },
    ],
    'cell': [
      { label: "插入指标值", key: "insert-value" },
    ]
  }

  return menuMap[pos];
}

//日期格式识别转换
export function checkDateFormat(str) {
  const dateRegex = /^(?:(?:19|20)\d\d)([-/.])(0?[1-9]|1[0-2])\1(0?[1-9]|[12][0-9]|3[01])$/;
  
  if(dateRegex.test(str)) {
    const date = new Date(str);
    if (!isNaN(date.getTime())) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    } else {
      return false;
    }
  }else {
    return false
  }
}

/* 根据key找到关联格子 设置关联格子样式 */
export function setRelationStyle(query) {
  const { key } = query;

  let table = document.querySelector('.table');
  let el = table.querySelector("td[data-key='" + key + "']");
  
  el.nodeName==='TD' && $(el).addClass("td-relation")
}

//根据cell key找到cell数据
export function findCellByKey(arr,key) {
  let cell = null;
  for (let i = arr.length - 1; i >= 0; i--) {
    if(!cell) {
      for(let j = arr[i].length-1;j>=0;j--) {
        if(arr[i][j].Uid===key) {
          cell = arr[i][j];
          break
        }
      }
    }
  }
  // console.log(cell)
  return cell
}

