import store from '@/store/index.js'
import wx from 'weixin-js-sdk'

// 不含icon提示框
export const toast = str => {
  return new Promise((resolve, reject) => {
    if (str.length < 20) {
      uni.showToast({
        title: str,
        icon: 'none',
        duration: 1500,
        success: () => {
          setTimeout(() => {
            resolve
          }, 1500)
        }
      })
    } else {
      uni.showModal({
        title: '提示',
        content: String(str),
        showCancel: false,
        confirmText: '我知道了',
        success(res) {
          if (res.confirm) {
            resolve(res)
          } else {
            reject()
          }
        }
      })
    }
  })
}

// 成功提示框
export const successToast = str => {
  return new Promise((resolve, reject) => {
    uni.showToast({
      title: str || '请求成功',
      icon: 'success',
      duration: 1500,
      success: () => {
        setTimeout(() => {
          resolve()
        }, 1500)
      }
    })
  })
}

// loading
export const showLoading = () => {
  return new Promise((resolve, reject) => {
    uni.showLoading({
      success: () => {
        resolve()
      }
    })
  })
}

// 提示loading
export const tipLoading = str => {
  return new Promise((resolve, reject) => {
    uni.showLoading({
      title: str,
      success: () => {
        resolve()
      }
    })
  })
}

// 隐藏loading
export const hideLoading = () => {
  return new Promise((resolve, reject) => {
    uni.hideLoading({
      success: () => {
        resolve()
      }
    })
  })
}

// 模态弹窗
export const modal = (options = {}) => {
  if (!options) return
  const { title, content, showCancel, cancelText, cancelColor, confirmText, confirmColor } = Object.assign(
    {},
    options.content
      ? options
      : {
          content: options
        }
  )
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: title || '提示',
      content: String(content),
      showCancel: typeof showCancel == 'boolean' ? showCancel : true,
      cancelText: cancelText || '取消',
      cancelColor: cancelColor || '#323233',
      confirmText: confirmText || '确定',
      confirmColor: confirmColor || '#3D8FFD',
      complete(res) {
        if (res.confirm) {
          resolve(res)
        } else {
          reject()
        }
      }
    })
  })
}

// 弹窗提示
export const tips = text => {
  modal({
    content: text,
    showCancel: false
  })
    .then(() => {})
    .catch(() => {})
}

/**
 * 跳转页面 navigateTo
 * 保留当前页面，跳转到应用内的某个页面
 * @param {String} url 需要跳转的页面
 * @param {Boolean} isAuth 是否需要鉴权
 * @returns
 */
export const navPage = (url, isAuth = 0) => {
  if ((isAuth && store.state.token) || !isAuth) {
    this.$navToPage({
      url,
      fail: err => {
        console.log('页面跳转失败', url, err)
      }
    })
  } else {
    this.$navToPage({
      url: '/pages/login/index'
    })
  }
}

/**
 * 跳转页面 redirectTo
 * 关闭当前页面，跳转到应用内的某个页面
 * @param {String} url 需要跳转的页面
 * @param {Boolean} isAuth 是否需要鉴权
 * @returns
 */
export const redPage = (url, isAuth = 0) => {
  if ((isAuth && store.state.token) || !isAuth) {
    uni.redirectTo({
      url,
      fail: err => {
        console.log('页面跳转失败', url, err)
      }
    })
  } else {
    this.$navToPage({
      url: '/pages/login/index'
    })
  }
}

/**
 * 返回页面
 * @param {Number} num 返回的页面数
 * @param {Number} time 延时返回
 * @returns
 */
export const backPage = (num = 1, time = 0) => {
  if (!num) return false
  setTimeout(() => {
    uni.navigateBack({
      delta: num
    })
  }, time)
}

/**
 * 拨打电话
 * @param {String} phone 用户隐私号
 * @param {String} orderId 服务单id，如果需要请求记录接口
 */
export const callPhone = phone => {
  if (!phone)
    return modal({
      content: '手机号码不存在',
      showCancel: false
    })
      .then(() => {})
      .catch(() => {})
  uni.makePhoneCall({
    phoneNumber: phone,
    success: () => {
      // logCallPhone(orderId);
    }
  })
}

/**
 * 复制
 * @param {String} val 复制内容
 */
export const copy = val => {
  uni.setClipboardData({
    data: val,
    success: () => {
      successToast('复制成功')
    }
  })
}

/**
 * 打开导航
 */
export const openLocation = (options = {}) => {
  if (!options) return
  const { lat, lng, name, address } = options
  wx.openLocation({
    latitude: Number(lat),
    longitude: Number(lng),
    name,
    address,
    success: () => {
      console.log('success')
    }
  })
}

// 获取当前定位
export const getLocation = async function () {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      geocode: true,
      success: res => {
        resolve(res)
      },
      fail: err => {
        resolve({})
        // reject('获取当前定位失败')
        // modal({
        //   title: '提示',
        //   content: '获取当前定位失败',
        //   showCancel: false
        // }).then(() => {})
      }
    })
  })
}

// 获取地址
export const getAddress = async function () {
  const location = await getLocation()
  if (!location) {
    return tips('获取定位失败，请检查是否开启手机位置信息权限')
  }
  return new Promise((resolve, reject) => {
    if (location.longitude && location.latitude) {
      uni.request({
        url: 'https://restapi.amap.com/v3/geocode/regeo',
        method: 'GET',
        data: {
          location: location.longitude + ',' + location.latitude,
          key: '428a7111e02ea8367a3b34804eaa025b'
        },
        success: res => {
          resolve({
            longitude: location.longitude,
            latitude: location.latitude,
            address: res.data.regeocode.formatted_address,
            province: res.data.regeocode.addressComponent.province,
            city: res.data.regeocode.addressComponent.city,
            area: res.data.regeocode.addressComponent.district,
            street: res.data.regeocode.addressComponent.township
          })
        },
        fail: function (err) {
          console.log('地址解析失败' + err)
        }
      })
    } else {
      resolve({
        longitude: '',
        latitude: '',
        address: '',
        province: '',
        city: '',
        area: '',
        street: ''
      })
    }
  })
}

// 判断微信环境
export function isWeixin() {
  if (navigator && navigator.userAgent) {
    var ua = navigator.userAgent.toLowerCase()
    if (ua.indexOf('micromessenger') != -1) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
}

// 解析地址栏参数
export function getQueryVariable(variable) {
  // 从?开始获取后面的所有数据
  var query = window.location.search.substring(1)
  // 从字符串&开始分隔成数组split
  var vars = query.split('&')
  // 遍历该数组
  for (var i = 0; i < vars.length; i++) {
    // 从等号部分分割成字符
    var pair = vars[i].split('=')
    // 如果第一个元素等于 传进来的参的话 就输出第二个元素
    if (pair[0] == variable) {
      return pair[1]
    }
  }
  return undefined
}

export const getZero = num => {
  // 个位数前补0
  if (parseInt(num) < 10) {
    num = '0' + num
  }
  return num
}

export const getNowDate = () => {
  const date = new Date()
  let Y = getZero(date.getFullYear())
  let M = getZero(date.getMonth() + 1)
  let D = getZero(date.getDate())
  return `${Y}-${M}-${D}`
}

export const getNowDatetime = () => {
  const date = new Date()
  let Y = getZero(date.getFullYear())
  let M = getZero(date.getMonth() + 1)
  let D = getZero(date.getDate())
  let h = getZero(date.getHours())
  let m = getZero(date.getMinutes())
  let s = getZero(date.getSeconds())
  return `${Y}-${M}-${D} ${h}:${m}:${s}`
}

export default {
  toast,
  successToast,
  showLoading,
  tipLoading,
  hideLoading,
  modal,
  tips,
  navPage,
  redPage,
  backPage,
  callPhone,
  copy,
  openLocation,
  getLocation,
  getAddress,
  getNowDate,
  getNowDatetime,
  getZero
}
