/**
 * 判断数据是否为 type, 或返回 type
 * @param {*} data
 * @param {*} type
 * @returns
 */
function isType(data, type = undefined) {
  const dataType = Object.prototype.toString
    .call(data)
    .match(/\s(.+)]/)[1]
    .toLowerCase()
  return type ? dataType === type.toLowerCase() : dataType
}

/**
  autoList 参考示例
  [
    {
      time: 1000 * 5, // 循环调用时间
      fn: this.currentTime, // 要调用的函数
    }
  ]
**/
function autoVueFn(autoList = [], opt) {
  if (!opt) {
    opt = {
      vm: this,
    }
  } else if (opt.$attrs) {
    opt = {
      vm: opt,
    }
  }
  const { vm, batEnd } = opt
  let end = 0
  vm.timer_ = []
  autoList.forEach(async (item) => {
    const fn = async () => {
      await item.fn.call(vm)
      end = end + 1
      if (end >= autoList.length) {
        batEnd && batEnd.call(vm)
      }
    }
    fn()
    const timer = setInterval(fn, item.time)
    vm.timer_.push(timer)
  })
  vm.$options.beforeDestroy = [
    ...(vm.$options.beforeDestroy || []),
    function () {
      vm.timer_.forEach((item) => {
        console.log(`卸载`, item)
        clearInterval(item)
      })
    },
  ]
}

/**
 * 根据区域 code 获取区域 id
 * @param {} vm
 * @param {*} code
 * @returns
 */
async function code2base(vm, code) {
  const list = (await vm.$http.get(`/api/base`)) || []

  console.log(list, code.slice(0, 2))
  const item =
    list.find((item) => String(item.名称).includes(String(code.slice(0, 2)))) ||
    list[0] ||
    {}

  return item
}

export default {
  code2base,
  autoVueFn,
  isType,
}
