import Ajax from './ajax'
import api from './api'
import wechatConfig from '@/config/index'
const toolClass = {
  dateFormat: (timestamp, fmt) => {
    if (!fmt) {
      fmt = 'yyyy-MM-dd hh:mm'
    }

    let date = new Date(timestamp)
    var o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      'S': date.getMilliseconds()
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
    }
    return fmt
  },
  UrlSearch: (urls) => {
    let url = urls // 获取url中"?"符后的字串
    let theRequest = {}
    if (url.indexOf('?') !== -1) {
      let str = url.substr(1)
      let strs = str.split('&')
      for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
      }
    }
    return theRequest
  },
  getCode: (appid) => {
    let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=${wechatConfig.response_type}&scope=${wechatConfig.scope}&state=${wechatConfig.state}#wechat_redirect`
    window.location.href = url
  },

  /**
   * caculate the great circle distance
   * 经纬度计算距离
   */
  getGreatCircleDistance: (lat1, lng1, lat2, lng2) => {
    if (lat1 === lat2 && lng1 === lng2) {
      return 0
    }
    var EARTH_RADIUS = 6378137.0//单位M
    var PI = Math.PI
    var radLat1 = lat1 * PI / 180.0
    var radLat2 = lat2 * PI / 180.0
    var a = radLat1 - radLat2
    var b = lng1 * PI / 180.0 - lng2 * PI / 180.0
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
    s = s * EARTH_RADIUS
    s = Math.round(s * 10000) / 10000.0
    console.log(s)
    return s
  },
  upload (item) {
    return new Promise((resolve, reject) => {
      Ajax({
        ...api.file.image,
        data: { file: item.file },
      }).then((res) => {
        let result = {
          result: res
        }
        if (item.onSuccess) {
          item.onSuccess(result, item.file)
        }
        // console.log(result)
        resolve(result)
      }).catch(reject)
    })
  },
  uploadBase64 (base64) {
    return new Promise((resolve, reject) => {
      Ajax({
        ...api.file.base64,
        queryData: {
          namestr: base64.namestr
        },
        data: { base64str: base64.base64str },
      }).then((res) => {
        let result = {
          result: res
        }
        resolve(result)
      }).catch(reject)
    })
  }
}

export default toolClass
