import { fhCreateUrl } from '../api/remote/index'

const formatTime = date => {
  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(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const getFileNameUUID = () => {
  function rx() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return `${+new Date()}_${rx()}${rx()}`
}

const queryStyles = select =>
  new Promise((resolve, reject) => {
    if (!select || typeof select !== 'string')
      reject(Error(`传参错误，select：${select}`))
    wx.createSelectorQuery()
      .select(select)
      .boundingClientRect(function (rect) {
        if (rect && rect.height > 0) {
          resolve(rect)
        } else {
          reject(Error(`没有找到dom`))
        }
      })
      .exec()
  })

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

// 对比版本号
function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

// 中文原始长度
const charString = str => {
  let leng = 0
  for (let i = 0; i < str.length; i += 1) {
    if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
      leng += 2
    } else {
      leng += 1
    }
  }
  return leng
}

wx.$queryStyles = queryStyles

wx.$setGlobalData = (key, value) => (getApp().globalData[key] = value)
wx.$getGlobalData = key => getApp().globalData[key]

wx.$urlEncode = value => encodeURIComponent(JSON.stringify(value))
wx.$urlDecode = value => JSON.parse(decodeURIComponent(value))

/**
 * 切分字符串为数组
 * @param {string} string 需要切分的字符串
 * @param {splitStr} splitStr 分隔符
 */
const splitStrToArray = (string = '', splitStr = ',') => {
  return string && string.length > 0
    ? string.includes(splitStr)
      ? string.split(splitStr)
      : [string]
    : []
}

// 计算年龄
const computedAge = birthday => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const [bYear, bMonth, bDay] = birthday.split('-')
  let diff = year - +bYear
  if (month < +bMonth || (month === +bMonth && day < +bDay)) {
    diff -= 1
  }
  return diff
}

// 解析URL链接或二维码中的参数
const sceneDecode = str => {
  let result = {}
  const tempObj = str.split('_')
  tempObj.forEach(i => {
    const temp = i.split('-')
    if (temp?.[0]) result[temp[0]] = temp[1]
  })
  return result
}
const sceneEncode = obj => {
  let result = []
  for (let i in obj) {
    const value = obj[i]
    result.push(`${i}-${value}`)
  }
  return result.join('_')
}

// 创建进入 Url
const creatUrl = async (path, params) => {
  try {
    const query = sceneEncode(params)
    const { results } = await fhCreateUrl({
      path,
      query: `scene=${query}`
    })
    return results
  } catch (e) {
    console.log('debug axios', e)
  }
}



module.exports = {
  parseTime,
  formatTime,
  getFileNameUUID,
  Hack(page) {
    var hack = {}

    for (let i in page.data)
      if (i[0] != '_')
        hack[i] = {
          get: () => page.data[i],
          set: val =>
            page.setData({
              [i]: val
            })
        }

    Object.defineProperties(page, hack)
  },
  RichText(raw) {
    var pre =
      'style="display:block !important;max-width:100% !important;margin: 0 !important;padding: 0 !important;line-height: 0 !important; width: 690rpx !important;'
    var imgs = raw.match(/<img[^>]*>/g)
    imgs &&
      imgs.forEach(
        i =>
          (raw = raw.replace(i, i =>
            /style="/.test(i)
              ? i.replace('style="', pre)
              : i.replace('<img', `<img ${pre}"`)
          ))
      )
    return `<div style="font-size:14px;text-align:justify;">${raw}</div>`
  },
  Tips(title, option = {}) {
    wx.showToast(
      Object.assign(
        {
          title,
          mask: true,
          icon: 'none',
          duration: 2000
        },
        option
      )
    )
  },
  Alert(content, option = {}) {
    wx.showModal(
      Object.assign(
        {
          content,
          showCancel: false
        },
        option
      )
    )
  },
  SliceArray(raw, length) {
    var data = []
    var temp = []

    raw.forEach((n, i) => {
      temp.push(n)
      if ((i && (i + 1) % length == 0) || i == raw.length - 1) {
        data.push(temp)
        temp = []
      }
    })

    return data
  },
  FormatNum(num) {
    return num > 9 ? num : '0' + num
  },
  FormatTime(raw, format) {
    raw = new Date(raw)
    return format
      .replace('y', raw.getFullYear())
      .replace('M', this.FormatNum(raw.getMonth() + 1))
      .replace('d', this.FormatNum(raw.getDate()))
      .replace('h', this.FormatNum(raw.getHours()))
      .replace('m', this.FormatNum(raw.getMinutes()))
      .replace('s', this.FormatNum(raw.getSeconds()))
  },
  NumberK(raw) {
    return (+raw).toLocaleString()
  },
  PreLoad(pre) {
    var load = 0
    return () => ++load == pre && wx.hideLoading()
  },
  QueryStyle(id, fn) {
    wx.createSelectorQuery()
      .select(id)
      .boundingClientRect(function (rect) {
        if (rect && rect.height > 0) {
          var navbarInitTop = parseInt(rect.height)
          fn && fn(navbarInitTop)
        }
      })
      .exec()
  },
  ToShare() {
    wx.navigateTo({
      url: '/pages/share/share'
    })
  },
  queryStyles,
  compareVersion,
  charString,
  computedAge,
  splitStrToArray,
  sceneEncode,
  sceneDecode,
  creatUrl
}
