// 字母列标
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||el.value||'') : 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,canEdit=false) {

  let cellMenu = [
    { label: "根据表格中日期选择指标值", key: "choose-target" },
    // { label: "插入指标值", key: "insert-value" },
    { label: "导入系统日期", key: "insert-sys-date" },
    { label: "导入指标日期", key: "insert-edb-date" },
    { label: "指标计算",
      key: "insert-edb-calculate",
      children: [
        { label: '累计值转月/季值',source: 1,fromEdbKey:5 },
        { label: '同比值',source: 3,fromEdbKey:6 },
        { label: '同差值',source: 4,fromEdbKey:7 },
        { label: 'N数值移动平均计算',source: 5,fromEdbKey:8 },
        { label: 'N数值环比值',source: 6,fromEdbKey:12 },
        { label: 'N数值环差值',source: 7,fromEdbKey:13 },
        { label: '升频',source: 8,fromEdbKey:14 },
        { label: '时间移位',source: 10,fromEdbKey:22 },
        { label: '超季节性',source: 11,fromEdbKey:35 },
        { label: '年化',source: 12,fromEdbKey:52 },
        { label: '降频',source: 9,fromEdbKey:51 },
        { label: '累计值',source: 13,fromEdbKey:62 },
        { label: '指数修匀',source: 15,fromEdbKey:'alpha' },
        { label: '日均值',source: 16,fromEdbKey:75 },
      ]
    },
    { label: "清空", key: "reset" },
  ]

  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': canEdit 
      ? [{ label: '编辑',key: 'cell-edit' },...cellMenu]
      : cellMenu
  }

  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])$/;

  //也支持年-月
  const dateMonthRegex = /^(?:(?:19|20)\d\d)([-])(0[1-9]|1[0-2])$/;
  
  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 if(dateMonthRegex.test(str)){
    return str
  } else {
    return false
  }
}

/* 根据key找到格子 设置格子样式 */
export function setRelationStyle(query,classname="td-relation") {
  const { key } = query;

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

//根据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
}

/* 清空插入单元格重置关联样式 */
export function resetRelationStyle() {
  let table = document.querySelector('.table');
  table.querySelectorAll(".td-relation").forEach(el => {
    el.classList.remove('td-relation')
  })
}

/* 重置右键选择指标时的单元格标识样式 弹窗消失样式就消失 */
export function resetDialogCellStyle() {
  let table = document.querySelector('.table');
  table.querySelectorAll(".td-choose-insert-target").forEach(el => {
    el.classList.remove('td-choose-insert-target')
  })
}


// 根据行头列头位置找key
export function findCellKeyByFactor(str) {
  let newStr = splitString(toUpperCase(str));

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

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