import _ from 'lodash'
import config from './config'

/**
 * 字段处理: 把object形式变成array形式
 * @param {object|array} data
 * @returns {array}
 */
export function fieldsManager(fields) {
  if (Array.isArray(fields)) {
    return fields.map(item => {
      if (item.children) {
        item.children = fieldsManager(item.children)
      }
      return item
    })
  }
  return Object.keys(fields).map(key => {
    const item = fields[key]
    if (typeof item === 'string') {
      return {
        prop: key,
        label: item
      }
    } else {
      if (item.children) {
        item.children = fieldsManager(item.children)
      }
      return {
        prop: key,
        ...item
      }
    }
  })
}

export function diffGetExcelInfo(fields) {
  const titles = []
  const items = []
  const rowMerge = []
  const colMergeObj = {}
  // 递归获取title 和 显示的字段
  const diffArr = (arr = [], diffNum = 0, startIndex = 0) => {
    if (!titles[diffNum]) titles[diffNum] = []
    const diffCount = startIndex - titles[diffNum].length
    if (diffCount > 0) {
      // 计算合并列
      for (var i = titles[diffNum].length; i < startIndex; i++) {
        const col = convertNum(i + 1)
        console.log(col)
        if (!colMergeObj[col]) colMergeObj[col] = { end: diffNum + 1 }
        if (diffNum + 1 > colMergeObj[col].end) colMergeObj[col].end = diffNum + 1
        if (titles[diffNum - 1][i]) colMergeObj[col].start = diffNum
      }
      // 如果当前行的长度小于startIndex则在后面补上空串
      titles[diffNum].push(...new Array(diffCount).fill(''))
    }
    arr.forEach((item) => {
      titles[diffNum].push(item.label)
      for (var i = diffNum; i >= 0; i--) { // 如果前几行对应位置没有值, 赋予空串
        const curIndex = titles[diffNum].length - 1
        // eslint-disable-next-line eqeqeq
        if (!titles[i][curIndex] && i != diffNum) titles[i][curIndex] = ''
      }
      if (item.children && item.children.length) { // 如果有children则递归, 并在递归结束后给出合并行
        const localArr = []
        const prevLen = titles[diffNum].length
        localArr.push(convertNum(prevLen) + (diffNum + 1))
        diffArr(item.children, diffNum + 1, titles[diffNum].length - 1)
        const nextLen = titles[diffNum].length
        localArr.push(convertNum(nextLen) + (diffNum + 1))
        if (nextLen - prevLen) rowMerge.push(localArr.join(':'))
      } else {
        items.push(item)
      }
    })
  }
  diffArr(fields)
  // 处理标题长度
  const titleWidth = titles[0].length
  titles.forEach((item, index) => {
    if (item.length < titleWidth) {
      // 计算合并列
      for (var i = item.length; i < titleWidth; i++) {
        const col = convertNum(i + 1)
        console.log(col)
        if (!colMergeObj[col]) colMergeObj[col] = { end: index + 1 }
        if (index + 1 > colMergeObj[col].end) colMergeObj[col].end = index + 1
        if (titles[index - 1][i]) colMergeObj[col].start = index
      }
      item.push(...new Array(titleWidth - item.length).fill(''))
    }
  })
  const colMerge = Object.keys(colMergeObj).map(key => `${key}${colMergeObj[key].start}:${key}${colMergeObj[key].end}`)
  return {
    titles,
    items,
    titleWidth,
    titleHeight: titles.length,
    merges: [...rowMerge, ...colMerge]
  }
}

/**
 *
 * @param {array} fields 字段列表
 * @param {array} list 数据列表
 * @param {function} format 数据格式化函数
 * @param {object} optional 导出Excel的其他参数
 */
export async function exportExcel(fields, list, optional = {}, format = formatJson) {
  const excel = await import('@/vendor/Export2Excel')
  const { titles: header, items: filterVal, merges } = diffGetExcelInfo(fields)
  // const merges = []
  const data = format(filterVal, list)
  excel.export_json_to_excel({
    header,
    merges,
    data,
    ...optional
  })
}

export function formatJson(filterVal, jsonData, emptyFill) {
  return jsonData.map(v => filterVal.map(j => {
    let value = _.result(v, j.prop, emptyFill || config.exportEmptyFill)
    if (j.filter) {
      value = j.filter(value, v)
    }
    return value
  }))
}

export function convertNum(num) {
  var str = ''
  while (num > 0) {
    var m = num % 26
    if (m === 0) {
      m = 26
    }
    str = String.fromCharCode(m + 64) + str
    num = (num - m) / 36
  }
  return str
}

export function optionsFilter(value, options = [], emptyFill = '', valueKey = 'value', returnKey = 'label') {
  const item = options.find(it => it[valueKey] === value)
  if (item) {
    return item[returnKey]
  } else {
    return emptyFill
  }
}

/**
 * 对对象里的 空串值 赋值为 undefined (目前用在listQuery)
 * @param {object} obj 对象
 * @returns {object}
 */
export function objEmitFieldManager(obj = {}) {
  return Object.keys(obj).reduce((prev, key) => {
    prev[key] = obj[key] === '' ? undefined : obj[key]
    return prev
  }, {})
}
