let totalChart = 'abcdefghijklmiopqrstuvwxyzABCDEFGHIJKLMIOPQRSTUVWXYZ'

export default {
  getRandomStr(length) {
    return new Array(length).fill('').map(i => totalChart[parseInt(Math.random() * totalChart.length)]).join('')
  },
  underline2camel(obj) {
    return Object.keys(obj).reduce((r, i) => {
      let newKey = i.replace(/_([\w])/g, ($, $1) => $1 ? $1.toUpperCase() : $1);
      r[newKey] = obj[i];
      return r
    }, {})
  },
  camel2underline(obj) {
    return Object.keys(obj).reduce((r, i) => {
      let newKey = i.replace(/[A-Z]/g, $ => '_' + $.toLowerCase());
      r[newKey] = obj[i];
      return r
    }, {})
  },
  treeAddProp(tree, childName, key, valueMap) {
    let set = (obj, dep) => {
      obj[key] = valueMap[dep]
      if (Array.isArray(obj[childName])) {
        dep += 1
        obj[childName].forEach(i => {
          set(i, dep)
        })
      }
    }
    set(tree, 0)
    return tree
  },
  treePlat(tree, childName) {
    let res = []
    let plat = node => {
      res.push(node)
      if (Array.isArray(node[childName])) {
        node[childName].forEach(plat)
      }
    }
    plat(tree)
    return res
  },
  dateFormat(date, fmt = "YYYY-mm-dd HH:MM:SS") {
    let ret;
    const opt = {
      "Y+": date.getFullYear().toString(), // 年
      "m+": (date.getMonth() + 1).toString(), // 月
      "d+": date.getDate().toString(), // 日
      "H+": date.getHours().toString(), // 时
      "M+": date.getMinutes().toString(), // 分
      "S+": date.getSeconds().toString() // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
    };
    return fmt;
  },
  // 数组按某值分组为二维数组
  arrGroup2arr(arr, key) {
    return Object.values(this.arrGroup2obj(arr, key))
  },
  // 数组按某值分组为对象
  arrGroup2obj(arr, key) {
    return arr.reduce((r, i) => {
      let now = r[i[key]]
      if (!now) {
        r[i[key]] = now = []
      }
      now.push(i)
      return r
    }, {})
  },
  // 数组对象更换key
  arrReplaceKeys(arr, keyMap, columnList = []) {
    let numberDataFormatOperator = {
      '1': 'divide',
      '2': 'multiply',
      '3': 'add',
      '4': 'subtract'
    }
    let keyArr = Object.entries(keyMap)
    return arr.map(item => {
      keyArr.forEach(([old, now]) => {
        let columnListFind = columnList.find(v => v.columnTitle === now)
        if (columnList.length > 0 && columnListFind) {
          let numberFormatFormula = columnListFind.extJson
          item[now] = XEUtils[numberDataFormatOperator[numberFormatFormula.numberDataFormatOperator]](item[old], `${numberFormatFormula.numberDataFormatNum}`).toFixed(`${numberFormatFormula.numberDataFormatToFixed}`)
        } else {
          item[now] = item[old]
        }
        delete item[old]
      })
      return item
    })
  },
  // 数组过滤出想要的属性
  filterFields(arr, fields) {
    return arr.map(item => fields.reduce((r, i) => ({
      ...r,
      [i]: item[i]
    }), {}))
  },
  // 日期选择器常用快捷选项
  datePickers: [{
    text: "今日",
    onClick(picker) {
      const start = new Date();
      const end = new Date();
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "昨日",
    onClick(picker) {
      const start = new Date();
      start.setDate(start.getDate() - 1)
      const end = new Date();
      end.setDate(end.getDate() - 1)
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "本周",
    onClick(picker) {
      const start = new Date();
      let day = start.getDay()
      let delay = day == 0 ? 6 : day - 1
      start.setDate(start.getDate() - delay)
      const end = new Date();
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "上周",
    onClick(picker) {
      const start = new Date();
      let day = start.getDay()
      let delay = day == 0 ? 6 : day - 1
      start.setDate(start.getDate() - delay - 7)
      const end = new Date();
      end.setDate(start.getDate() + 6)
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "本月",
    onClick(picker) {
      const start = new Date();
      start.setDate(1)
      const end = new Date();
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "上月",
    onClick(picker) {
      const start = new Date();
      start.setDate(1)
      start.setMonth(start.getMonth() - 1)
      const end = new Date();
      end.setDate(0)
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "近7日",
    onClick(picker) {
      const start = new Date();
      start.setDate(start.getDate() - 6)
      const end = new Date();
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "过去7日",
    onClick(picker) {
      const start = new Date();
      start.setDate(start.getDate() - 7)
      const end = new Date();
      end.setDate(end.getDate() - 1)
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "近30日",
    onClick(picker) {
      const start = new Date();
      start.setDate(start.getDate() - 29)
      const end = new Date();
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "过去30日",
    onClick(picker) {
      const start = new Date();
      start.setDate(start.getDate() - 30)
      const end = new Date();
      end.setDate(end.getDate() - 1)
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "近90日",
    onClick(picker) {
      const start = new Date();
      start.setDate(start.getDate() - 89)
      const end = new Date();
      picker.$emit("pick", [start, end]);
    },
  }, {
    text: "过去90日",
    onClick(picker) {
      const start = new Date();
      start.setDate(start.getDate() - 90)
      const end = new Date();
      end.setDate(end.getDate() - 1)
      picker.$emit("pick", [start, end]);
    },
  }],
  // 取a~b间n个均匀数的数组
  getBalanceNumbers(a, b, n) {
    let step = Math.ceil((b - a) / n)
    return new Array(n).fill('').map((_, i) => a + (i + 1) * step)
  },
  // 从对象中取某值对应的键
  getKeyByValue(obj, value) {
    return Object.entries(obj).find(([k, v]) => v == value)[0]
  },
  // 数组按某值去重
  arrayNoReplaceByKey(arr, key) {
    return Object.values(arr.reduce((r, i) => ({
      ...r,
      [i[key]]: i
    }), {}))
  },
  // 按长度循环补全数组
  completeArr(arr, num) {
    let arrNum = Math.ceil(num / arr.length)
    let stepArr = new Array(arrNum).fill('').reduce((r) => {
      return r.concat(arr)
    }, [])
    return stepArr.slice(0, num)
  },
  completeColorMiddle(deep, light, length) {
    let deepArr = deep.split(/\D+/g).filter(i => i).map(i => parseInt(i))
    let lightArr = light.split(/\D+/g).filter(i => i).map(i => parseInt(i))
    let step1 = parseInt((lightArr[0] - deepArr[0]) / (length - 1))
    let step2 = parseInt((lightArr[1] - deepArr[1]) / (length - 1))
    let step3 = parseInt((lightArr[2] - deepArr[2]) / (length - 1))
    let arr = [deepArr]
    for (let i = 1; i < length; i++) {
      arr.push([arr[i - 1][0] + step1, arr[i - 1][1] + step2, arr[i - 1][2] + step3, ])
    }
    return arr.map(i => `rgb(${i[0]},${i[1]},${i[2]})`)
  },
  fangdou(fn, delay) {
    let timer = null
    return function () {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        fn.call(this, arguments)
      }, delay)
    }
  },
  // 查询字符串转对象
  query2obj(str = '') {
    return str.replace(/\?|\//g, '').split('&').reduce((r, i) => {
      let [k, v] = i.split('=')
      if (k !== '') r[k] = v
      return r
    }, {})
  },
  // 对象转查询字符串
  obj2query(obj = {}) {
    return Object.keys(obj).reduce((r, k) => r + '&' + k + '=' + obj[k], '').replace(/^&/, '?')
  },
  addThousandPoint(num) {
    let result = []
    let counter = 0
    num = parseFloat(num)
    if (!num) return 0
    let flag = num > 0
    num = Math.abs(num)
    num = '' + num
    let point = num.split('.')[1]
    num = num.split('.')[0].split('')
    for (let i = num.length - 1; i >= 0; i--) {
      counter++;
      result.unshift(num[i]);
      if (!(counter % 3) && i != 0) {
        result.unshift(',');
      }
    }
    if (result[0] == '-') {
      result.shift()
    }
    if (!flag) {
      result.unshift('-')
    }
    if (point && point.length) {
      result.push('.' + point)
    }
    result = result.join('');
    return result;
  }
}
