const util = {
// 时间戳转成0000-00-00 00:00:00
  formatTime: timeStamp => {
    const date = new Date(timeStamp)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(n => n.toString()[1] ? n.toString() : '0' + n).join('-') + ' ' + [hour, minute, second].map(n => n.toString()[1] ? n.toString() : '0' + n).join(':')
  },

  // 时间转时间戳
  dateToTimestamp: dateStr => {
    if (!dateStr) {
      return ''
    }
    const newDataStr = dateStr.replace(/-/g, '/')
    const date = new Date(newDataStr)
    return date.getTime()
  },

  checkIsVerification: (num) => {
    const regexp = /^[0-9]{8,13}$/
    return regexp.test(num)
  },

  checkIsNum: (num) => {
    const regexp = /^[0-9]+$/
    return regexp.test(num)
  },

  /**
 * 防抖
 * @param fn
 * @param t
 * @returns {Function}
 * @constructor
 */
  debounce: (fn, t) => {
    const delay = t || 300
    let timer
    return function () {
      const args = arguments
      if (timer) {
        clearTimeout(timer)
      }
      const callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, delay)
      if (callNow) fn.apply(this, args)
    }
  },
  mioIoUpload: (imgItem, fn) => {
    const params = {
      url: '/mall4cloud_biz/ua/oss/upload_minio',
      filePath: imgItem,
      name: 'file',
      callBack: res => {
        const data = JSON.parse(res).data
        const resourcesVal = '/' + data.dir + data.fileName
        fn(resourcesVal)
      }
    }
    http.upload(params)
  },
  /**
   * 根据地址返回省市区
   * @param {String} address 地址
   * @param {String} name 地名
   * @return {Array} 省市区的信息
   */
  area: async (address, name) => {
    if (!address) return
    const areaInfoArr = []
    let province, city, area // 名字
    let provinceIndex, cityIndex, areaIndex // 所处的索引
    let provinceId, cityId, areaId // areaId
    // 特殊的区域
    if (name.includes('苏滁现代产业园')) {
      province = '安徽省'
      city = '苏滁市'
      area = '苏滁现代产业园'
    } else if (name.includes('保定白沟新城')) {
      province = '河北省'
      city = '保定市'
      area = '保定白沟新城'
    } else if (name.includes('中沙群岛')) {
      province = '海南省'
      city = '三沙市'
      area = '中沙群岛的岛礁及其海域'
    } else {
      const provSuffix = ['省', '自治区', '黑龙江', '北京市', '天津市', '上海市']
      const citySuffix = ['市', '地区', '自治州', '盟']
      const areaSuffix = ['区', '市', '县', '群岛']
      let aIndex = 0
      const common = (arr) => {
        aIndex = 0
        for (let i = 0; i < arr.length; i++) {
          const index = address.indexOf(arr[i])
          if (index !== -1) {
            aIndex = index + arr[i].length
            break
          }
        }
      }
      common(provSuffix)
      if (aIndex === 0) return
      province = address.substring(0, aIndex)
      address = address.substring(aIndex)
      // 直辖市
      if (province === '北京市' || province === '天津市' || province === '上海市') {
        common(areaSuffix)
        if (aIndex === 0) return
        area = address.substring(0, aIndex)
        city = area.includes('县') ? '县' : '市辖区'
      } else {
        common(citySuffix)
        if (aIndex === 0) return
        city = address.substring(0, aIndex)
        address = address.substring(aIndex)
        common(areaSuffix)
        if (aIndex === 0) return
        area = address.substring(0, aIndex)
      }
    }
    const getListByPid = (pid) => {
      const paramsData = {}
      if (pid === 0) {
        paramsData.level = 1
      } else {
        paramsData.pid = pid
      }
      return new Promise((resolve) => {
        http.request({
          url: '/mall4cloud_order/area/list',
          method: 'GET',
          data: paramsData
        }).then(res => {
          resolve(res.data)
        })
      })
    }
    // 省
    const res1 = await getListByPid(0)
    for (let i = 0; i < res1.length; i++) {
      if (province === res1[i].areaName) {
        provinceIndex = i
        provinceId = res1[i].areaId
        break
      }
    }
    // 市
    const res2 = await getListByPid(provinceId)
    for (let i = 0; i < res2.length; i++) {
      if (city === res2[i].areaName) {
        cityIndex = i
        cityId = res2[i].areaId
        break
      }
    }
    // 区
    const res3 = await getListByPid(cityId)
    for (let i = 0; i < res3.length; i++) {
      if (area === res3[i].areaName) {
        areaIndex = i
        areaId = res3[i].areaId
        break
      }
    }
    areaInfoArr.push({
      name: province,
      index: provinceIndex,
      areaId: provinceId
    })
    areaInfoArr.push({
      name: city,
      index: cityIndex,
      areaId: cityId
    })
    areaInfoArr.push({
      name: area,
      index: areaIndex,
      areaId
    })
    areaInfoArr.push(res1) // 省数组
    areaInfoArr.push(res2) // 市数组
    areaInfoArr.push(res3) // 区数组
    return areaInfoArr
  },
  awsUpload (ossList, files) {
    return new Promise((resolve) => {
      ossList.forEach((item, index) => {
        // #ifdef APP-PLUS
        util.getArrayBuffer(files[index].path).then((buffer) => {
          const params = {
            url: item.preSignUrl,
            method: 'put',
            data: buffer
          }
          http.request(params).then(() => {
            uni.hideLoading()
            resolve()
          })
        })
        // #endif

        // #ifdef H5
        uni.request({
          url: files[index].path,
          method: 'GET',
          responseType: 'arraybuffer',
          success: function (requestRes) {
            uni.request({
              url: item.preSignUrl,
              method: 'put',
              data: requestRes.data
            }).then(() => {
              uni.hideLoading()
              resolve()
            })
          }
        })
        // #endif
      })
    })
  },
  getArrayBuffer: (filePath) => {
    return new Promise((resolve) => {
      plus.io.resolveLocalFileSystemURL(filePath, async function (entry) {
        entry.file(function (file) { // 读取文件
          const reader = new plus.io.FileReader()
          reader.readAsDataURL(file) // 以URL格式读取文件
          reader.onload = function () {
            const base64 = this.result.split(',')[1] // 获取base64字符串
            const buffer = uni.base64ToArrayBuffer(base64) // 转换为arrayBuffer格式
            resolve(buffer)
          }
        })
      })
    })
  },
  // 添加图片域名
  addDomain (path) {
    if (!path || /^https?:\/\//.test(path)) {
      return path
    } else {
      return import.meta.env.VITE_APP_RESOURCES_URL + path
    }
  }
}

export default util
