import api from '@/common/http/'
import wx from 'weixin-js-sdk'
import { axios } from '@/common/http/'
import { isWeixin } from './common.js'
import store from '@/store/index.js'

import axios2 from 'axios'

import { setStorage, getStorage, removeStorage } from '@/common/utils/storage.js'

export const mini_env = function (cb) {
  if (isWeixin()) {
    wx.miniProgram.getEnv(res => {
      if (res.miniprogram) {
        cb(true)
      } else {
        cb(false)
      }
    })
  } else {
    cb(false)
  }
}

// 获取用户信息
export const getUserInfo = () => {
  return new Promise((resolve, reject) => {
    api
      .get('/user/user/detail', {
        userId: store.state.user.userId
      })
      .then(response => {
        const { data } = response
        setStorage('user', data)
        resolve(data)
      })
      .catch(error => {
        reject(error)
      })
  })
}

export async function redirection() {
  const appid = getQueryVariable('appid') || getQueryVariable('appId')
  const goHome = [
    '/packageWorkorder/pages/orderList',
    '/packageMaterial/pages/stock/index',
    '/packageMaterial/pages/sale/index',
    '/packageMaterial/pages/newSale/index'
  ]
  const goMycon = [
    '/packageMine/pages/collection',
    '/packageMine/pages/profit/list',
    '/packageMine/pages/salesProfit/index',
    '/packageMine/pages/ranking/list',
    '/packageMine/pages/myWebsit'
  ]
  var userInfo = await getUserInfo()
  if (userInfo) {
    if (userInfo.type === 'GENERAL') {
      if (goHome.find(url => !!~window.location.href.split('?')[0].indexOf(url))) {
        uni.showModal({
          title: '提示',
          content: '您的账号没有权限！',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              window.history.go(-(window.history.length - 1))
              window.location.href = `${process.env.VUE_APP_HREF}/pages/index/index?appid=${appid}`
            }
          }
        })
        return
      }
      if (goMycon.find(url => !!~window.location.href.split('?')[0].indexOf(url))) {
        uni.showModal({
          title: '提示',
          content: '您的账号没有权限！',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              window.history.go(-(window.history.length - 1))
              window.location.href = `${process.env.VUE_APP_HREF}/pages/mine/index?appid=${appid}`
            }
          }
        })
        return
      }
    } else if (userInfo.type === 'SERVICE') {
    } else if (userInfo.type === 'WORKER') {
    }
  }
}

// 解析地址栏参数
export const getQueryVariable = variable => {
  if (!window) {
    return undefined
  }
  // 从?开始获取后面的所有数据
  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 function compareUrls(url1, url2) {
  // 创建 URL 对象来解析地址
  const parsedUrl1 = new URL(url1)
  const parsedUrl2 = new URL(url2)

  // 比较主要部分（不包括查询参数）
  const mainPartUrl1 = parsedUrl1.origin + parsedUrl1.pathname
  const mainPartUrl2 = parsedUrl2.origin + parsedUrl2.pathname

  return mainPartUrl1 === mainPartUrl2
}

export function removePreviousHistory() {
  // 获取当前页面的url
  const currentUrl = window.location.href
  if (compareUrls(getStorage('CurrentHrefUrlAddress') || '', currentUrl)) {
    removeStorage('CurrentHrefUrlAddress')
    // 使用 history 对象的 go 方法跳转到上一个历史记录
    window.history.go(-1)
    // 使用 history.replaceState
    window.history.replaceState(null, '', currentUrl)
    // 刷新页面
    window.location.reload()
  }
}

// 删除 url 上的参数
function removeUrlParams(key) {
  let href = location.href
  const e = eval(`/&?${key}=[^&#]*/g`)
  href = href.replace(e, '')
  history.replaceState('', '', href)
  return href
}

function setStore(data = {}) {
  store.commit('user/set_userId', data.userId)
  store.commit('user/set_openId', data.openId)
  store.commit('user/set_name', data.nickName)
  store.commit('user/set_avatar', data.avatar)
  store.commit('user/set_mobile', data.mobile)
  store.commit('user/set_token', data.token)
}

export function truePath() {
  var currentURL = window.location.href
  var url = new URL(currentURL)
  var path = url.pathname
  var partToRemove = (function () {
    var hrefUrl = new URL(process.env.VUE_APP_HREF)
    if (hrefUrl.pathname && hrefUrl.pathname === '/') {
      return ''
    }
    return url.pathname
  })()
  if (path.startsWith(partToRemove)) {
    path = path.slice(partToRemove.length)
  }

  return path
}

export function rompamUrl() {
  // 获取当前页面的 URL
  var currentURL = window.location.href
  // 创建 URL 对象
  var url = new URL(currentURL)
  return url.origin + url.pathname
}

export function isEncoded(url) {
  return !!~url.indexOf('%3A%2F%2F') ? url : encodeURIComponent(url)
}

// 微信鉴权登入
export function webLogin(bool = false) {
  return new Promise(async (resolve, reject) => {
    // 获取地址栏appid信息
    const appid = getQueryVariable('appid') || getQueryVariable('appId')
    // 判断是否微信环境下
    if (isWeixin() && appid) {
      // code是由授权后重定向返回携带
      const code = getQueryVariable('code')
      // isAuthorization用于强制重新获取授权token
      const isAuthorization = getQueryVariable('isAuthorization')
      // 获取当前地址
      var url = location.href
      // 获取记录的时间
      const isAuthorizationTime = getStorage('isAuthorizationTime')
      // 获取历史code
      const previousCode = getStorage('previousCode')
      if (code) {
        url = removeUrlParams('code')
        url = removeUrlParams('state')
      }
      // 是否强制授权
      if (isAuthorization && (!isAuthorizationTime || isAuthorizationTime < new Date().getTime())) {
        // 设置时间
        setStorage('isAuthorizationTime', new Date().getTime() + 2 * 60 * 60 * 1000)
        // 删除本地缓存
        setStore()
        url = removeUrlParams('x-token')
        // 去获取授权
        setTimeout(function () {
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${isEncoded(
            url
          )}&response_type=code&scope=snsapi_userinfo#wechat_redirect`
        }, 50)
      } else if (bool) {
        // 删除本地缓存
        setStore()
        // url = `${rompamUrl()}?appid=${appid}`
        url = removeUrlParams('x-token')
        // 去获取授权
        setTimeout(function () {
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${isEncoded(
            url
          )}&response_type=code&scope=snsapi_userinfo#wechat_redirect`
        }, 50)
      }
      // 判断是否有token有则不需要授权执行
      else if (code && code !== previousCode) {
        // 设置时间
        setStorage('previousCode', code)
        // 有token表示授权回来则执行code静默登入
        api
          .post('/user/auth2', {
            code: code
          })
          .then(async res => {
            setStore(res.data)
            resolve({})
          })
          .catch(reject)
      } else {
        resolve({})
      }
    } else {
      resolve({})
    }
  })
}

// 获取配置信息
export const getConfigInfo = () => {
  return new Promise((resolve, reject) => {
    api
      .get('/common/config/get')
      .then(response => {
        const { data } = response
        resolve(data)
      })
      .catch(error => {
        reject(error)
      })
  })
}

// 获取模版信息
export const getTemplateInfo = () => {
  return new Promise((resolve, reject) => {
    api
      .get('/renovation/detail')
      .then(response => {
        const { data } = response
        resolve(data)
      })
      .catch(error => {
        reject(error)
      })
  })
}

// 获取未读消息数量
export const getNoticeNum = () => {
  return new Promise((resolve, reject) => {
    api
      .get('/notice/list/count', {
        readFlag: 'NO',
        noticeType: ''
      })
      .then(res => {
        if (res.data && res.data > 0) {
          uni.setTabBarBadge({
            index: 3,
            text: String(res.data)
          })
        } else {
          uni.removeTabBarBadge({
            index: 3
          })
        }
        resolve(res.data)
      })
      .catch(error => {
        resolve(0)
      })
  })
}

// 获取代办工单数量
export const getOrderNum = async () => {
  const userInfo = await getUserInfo()
  return new Promise((resolve, reject) => {
    if (userInfo.type == 'WORKER') {
      api
        .post('/pg/order/base/status/count')
        .then(res => {
          if (res.data && res.data.djd + res.data.fwz > 0) {
            uni.setTabBarBadge({
              index: 1,
              text: String(res.data.djd + res.data.fwz)
            })
          } else {
            uni.removeTabBarBadge({
              index: 1
            })
          }
          resolve(res.data.djd + res.data.fwz)
        })
        .catch(error => {
          resolve(0)
        })
    } else {
      resolve(0)
    }
  })
}

const getUUID = function () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16)
  })
}

const createName = function (name, s = '.') {
  const date = Date.now()
  const uuid = getUUID()
  const fileSuffix = name.substring(name.lastIndexOf(s) + 1)
  return `${date}${uuid}.${fileSuffix}`
}

const blobToFile = function (blobUrl) {
  return new Promise((r, j) => {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', blobUrl, true)
    xhr.responseType = 'blob'
    xhr.onload = function () {
      if (xhr.status === 200) {
        const blobData = xhr.response
        const file = new File([blobData], createName(blobData.type, '/'), {
          type: blobData.type
        })
        r(file)
      } else {
        j(xhr.statusText)
      }
    }
    xhr.send()
  })
}

// 全链接图片上传
export const uploadImgFull = async function (file) {
  console.log(file)
  uni.showLoading({
    mask: true
  })

  //  #ifdef H5
  let formData = new FormData()
  formData.append('file', await blobToFile(file))
  // #endif

  return new Promise((resolve, reject) => {
    //  #ifdef H5
    axios2
      .post(process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + '/common/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'x-token': store.state.user.token
        }
      })
      .then(res => {
        uni.hideLoading()
        resolve(res.data.data)
      })
    // #endif

    // #ifdef MP-WEIXIN
    uni.uploadFile({
      url: process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + '/common/upload',
      header: {
        'Content-Type': 'multipart/form-data',
        'x-token': store.state.user.token
      },
      name: 'file',
      filePath: file,
      success(res) {
        uni.hideLoading()
        resolve(JSON.parse(res.data).data)
      },
      fail(err) {
        reject(err)
      },
      complete(res) {
        uni.hideLoading()
      }
    })
    // #endif
  })
}

// 图片上传
export const uploadImg = async function (file) {
  console.log(file)
  uni.showLoading({
    mask: true
  })

  // 获取oss配置
  const par = await axios({
    url: '/common/oss/config',
    method: 'get'
  })
    .then(res => {
      return res.data
    })
    .catch(err => {
      uni.hideLoading()
    })

  const fileKey = par.dir + createName(file.name)

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: par.host,
      // header: {
      // 	"Content-Type": 'multipart/form-data',
      // },
      name: 'file',
      formData: {
        ...par,
        name: file.name,
        key: fileKey
      },
      filePath: file.path,
      success(res) {
        resolve({
          url: fileKey
        })
      },
      fail(err) {
        reject(err)
      },
      complete(res) {
        uni.hideLoading()
      }
    })
  })
}

// 图片上传
export const uploadBlobImg = async function (file) {
  console.log(file)
  uni.showLoading({
    mask: true
  })

  // 获取oss配置
  const par = await axios({
    url: '/common/oss/config',
    method: 'get'
  })
    .then(res => {
      return res.data
    })
    .catch(err => {
      uni.hideLoading()
    })

  const fileKey = par.dir + createName(file.name)

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: par.host,
      // header: {
      // 	"Content-Type": 'multipart/form-data',
      // },
      name: 'file',
      formData: {
        ...par,
        name: file.name,
        key: fileKey
      },
      filePath: file.url,
      success(res) {
        resolve({
          url: fileKey
        })
      },
      fail(err) {
        reject(err)
      },
      complete(res) {
        uni.hideLoading()
      }
    })
  })
}

export const getArea = function (str) {
  let area = {}
  let index11 = 0
  let index1 = str.indexOf('省')
  if (index1 == -1) {
    index11 = str.indexOf('自治区')
    if (index11 != -1) {
      area.Province = str.substring(0, index11 + 3)
    } else {
      area.Province = str.substring(0, 0)
    }
  } else {
    area.Province = str.substring(0, index1 + 1)
  }

  let index2 = str.indexOf('市')
  if (index11 == -1) {
    area.City = str.substring(index11 + 1, index2 + 1)
  } else {
    if (index11 == 0) {
      area.City = str.substring(index1 + 1, index2 + 1)
    } else {
      area.City = str.substring(index11 + 3, index2 + 1)
    }
  }

  let index3 = str.lastIndexOf('区')
  if (index3 == -1) {
    index3 = str.indexOf('县')
    area.Country = str.substring(index2 + 1, index3 + 1)
  } else {
    area.Country = str.substring(index2 + 1, index3 + 1)
  }
  return area
}

// 图片上传
export const uploadImgs = async function (file) {
  uni.showLoading({
    title: '上传中',
    mask: true
  })

  // 获取oss配置
  const par = await axios({
    url: '/common/oss/config',
    method: 'get'
  })
    .then(res => {
      return res.data
    })
    .catch(err => {
      uni.hideLoading()
    })

  const fileKey = par.dir + createName(file.name)

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: par.host,
      // header: {
      // 	"Content-Type": 'multipart/form-data',
      // },
      name: 'file',
      formData: {
        ...par,
        name: file.name,
        key: fileKey
      },
      filePath: file.path,
      success(res) {
        resolve({
          url: fileKey
        })
      },
      fail(err) {
        reject(err)
      },
      complete(res) {
        uni.hideLoading()
      }
    })
  })
}

export const matchFileSuffixType = function (fileName) {
  // 后缀获取
  var suffix = ''
  // 获取类型结果
  var result = ''
  try {
    var flieArr = fileName.split('.')
    suffix = flieArr[flieArr.length - 1]
  } catch (err) {
    suffix = ''
  }
  // fileName无后缀返回 false
  if (!suffix) {
    result = false
    return result
  }
  // 图片格式
  var imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp']
  // 进行图片匹配
  result = imglist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'image'
    return result
  }
  // 匹配txt
  var txtlist = ['txt']
  result = txtlist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'txt'
    return result
  }
  // 匹配 excel
  var excelist = ['xls', 'xlsx']
  result = excelist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'excel'
    return result
  }
  // 匹配 word
  var wordlist = ['doc', 'docx']
  result = wordlist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'word'
    return result
  }
  // 匹配 pdf
  var pdflist = ['pdf']
  result = pdflist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'pdf'
    return result
  }
  // 匹配 ppt
  var pptlist = ['ppt', 'pptx']
  result = pptlist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'ppt'
    return result
  }
  // 匹配 视频
  var videolist = ['mp4', 'm2v', 'mkv']
  result = videolist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'video'
    return result
  }
  // 匹配 音频
  var radiolist = ['mp3', 'wav', 'wmv']
  result = radiolist.some(function (item) {
    return item == suffix
  })
  if (result) {
    result = 'radio'
    return result
  }
  // 其他 文件类型
  result = 'other'
  return result
}

// 时间格式化
export const formatterDate = (date, fmt) => {
  let nowDate = {
    yyyy: date.getFullYear(), // 年
    MM: date.getMonth() + 1, // 月份
    dd: date.getDate() //日
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in nowDate) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? nowDate[k] : ('00' + nowDate[k]).substr(('' + nowDate[k]).length)
      )
    }
  }
  return fmt
}

/**
 * 比较时间是否在范围内
 * @param {Object} stime
 * @param {Object} etime
 * @return {Boolean}
 */
export const compareTime = function (stime, etime) {
  function tranDate(time) {
    return new Date(time.replace(/-/g, '/')).getTime()
  }
  let startTime = tranDate(stime)
  let endTime = tranDate(etime)
  let nowTime = new Date().getTime()

  if (nowTime < startTime || nowTime > endTime) {
    return false
  }
  return true
}

/*
 *时间戳转化日期方法
 *@params val 时间戳,必传;
 *@params type 转化类型,非必传,默认返回年月日加时间,等于ymd时,返回年月日,等于hms返回时间
 */
export const timeToDate = function (val, type) {
  if (!val) {
    throw new Error('val ')
  }
  var date = new Date(val * 1000),
    Y = date.getFullYear(),
    M = date.getMonth() + 1,
    D = date.getDate(),
    H = date.getHours(),
    m = date.getMinutes(),
    s = date.getSeconds()
  M = M < 10 ? '0' + M : M
  D = D < 10 ? '0' + D : D
  H = H < 10 ? '0' + H : H
  m = m < 10 ? '0' + m : m
  s = s < 10 ? '0' + s : s
  if (!type) {
    return `${Y}-${M}-${D} ${H}:${m}:${s}`
  } else if (type === 'ymd') {
    return `${Y}-${M}-${D}`
  } else if (type === 'hms') {
    return `${H}:${m}:${s}`
  }
}

var appModuleJsonGuding = null
export const selectionChange = async function () {
  var index
  try {
    ;['pages/index/index', 'pages/workorder/index', 'pages/goods/index', 'pages/mine/index'].map((item, index_) => {
      if (!!~window.location.href.indexOf(item)) {
        index = index_
        throw new Error(``)
      }
    })
  } catch (err) {
    var doc = document.getElementsByClassName('uni-tabbar-bottom')
    if (doc && doc.length) {
      if (!appModuleJsonGuding) {
        try {
          doc[0].innerHTML = ''
          var { appModuleJson } = (await getUserInfo()) || {}
          if (appModuleJson) {
            appModuleJsonGuding = JSON.parse(appModuleJson)
          } else {
            appModuleJsonGuding = [
              { type: 'home', name: '首页', sort: 0 },
              { type: 'order', name: '工单', sort: 1 },
              { type: 'shop', name: '商城', sort: 2 },
              { type: 'my', name: '我的', sort: 3 }
            ]
          }
        } catch (error) {
          console.log(error)
        }
      }
      doc[0].innerHTML = (function () {
        var tabs = {
          home(item) {
            return `<div class="uni-tabbar__item" onclick="(function(){navToPage({url: '/pages/index/index'+window.location.search})})()">
              <div class="uni-tabbar__bd" style="height: 50px;">
                <div class="uni-tabbar__icon" style="width: 24px; height: 24px;">
                  <img src="${process.env.VUE_APP_BASE_PATH}static/tabBar/icon_1${index == 0 ? '_cur' : ''}.png">
                </div>
                <div class="uni-tabbar__label" style="color: ${
                  index == 0 ? 'rgb(61, 143, 253)' : 'rgb(122, 126, 131)'
                }; font-size: 10px; line-height: normal; margin-top: 3px;">
                  ${item.name}
                </div>
              </div>
            </div>`
          },
          order(item) {
            return `<div class="uni-tabbar__item" onclick="(function(){navToPage({url: '/pages/workorder/index'+window.location.search+'&type=0&isWb=0'})})()">
              <div class="uni-tabbar__bd" style="height: 50px;">
                <div class="uni-tabbar__icon" style="width: 24px; height: 24px;">
                  <img src="${process.env.VUE_APP_BASE_PATH}static/tabBar/icon_2${index == 1 ? '_cur' : ''}.png">
                </div>
                <div class="uni-tabbar__label" style="color: ${
                  index == 1 ? 'rgb(61, 143, 253)' : 'rgb(122, 126, 131)'
                }; font-size: 10px; line-height: normal; margin-top: 3px;">
                  ${item.name}
                </div>
              </div>
            </div>`
          },
          // shop(item) {
          //   return `<div class="uni-tabbar__item" onclick="(function(){navToPage({url: '/pages/goods/index'+window.location.search})})()">
          //     <div class="uni-tabbar__bd" style="height: 50px;">
          //       <div class="uni-tabbar__icon" style="width: 24px; height: 24px;">
          //         <img src="${process.env.VUE_APP_BASE_PATH}static/tabBar/icon_3${index == 2 ? '_cur' : ''}.png">
          //       </div>
          //       <div class="uni-tabbar__label" style="color: ${
          //         index == 2 ? 'rgb(61, 143, 253)' : 'rgb(122, 126, 131)'
          //       }; font-size: 10px; line-height: normal; margin-top: 3px;">
          //         ${item.name}
          //       </div>
          //     </div>
          //   </div>`
          // },
          my(item) {
            return `<div class="uni-tabbar__item" onclick="(function(){navToPage({url: '/pages/mine/index'+window.location.search})})()">
              <div class="uni-tabbar__bd" style="height: 50px;">
                <div class="uni-tabbar__icon" style="width: 24px; height: 24px;">
                  <img src="${process.env.VUE_APP_BASE_PATH}static/tabBar/icon_4${index == 3 ? '_cur' : ''}.png">
                </div>
                <div class="uni-tabbar__label" style="color: ${
                  index == 3 ? 'rgb(61, 143, 253)' : 'rgb(122, 126, 131)'
                }; font-size: 10px; line-height: normal; margin-top: 3px;">
                  ${item.name}
                </div>
              </div>
            </div>`
          }
        }
        return `<div class="uni-tabbar" style="background-color: rgb(255, 255, 255); backdrop-filter: none;">
          <div class="uni-tabbar-border" style="background-color: rgba(0, 0, 0, 0.33);"></div>
          ${(appModuleJsonGuding || [])
            .sort((a, b) => a.sort - b.sort)
            .map(item => {
              return tabs?.[item.type]?.(item) || ''
            })
            .join('')}
        </div>
        <div class="uni-placeholder" style="height: 50px;"></div>`
      })()
    }
  }
}

// 微信支付直调
export const onBridgeReady = function (data, successful, cancel, failure) {
  WeixinJSBridge.invoke(
    'getBrandWCPayRequest',
    {
      // 以下6个支付参数通过蓝兔支付的jsapi接口获取
      // **************************
      appId: store.state.user.appId, //公众号appid
      timeStamp: data.timeStamp, //时间戳
      nonceStr: data.nonceStr, //随机字符串
      package: data.payPackage || data.package, //订单详情扩展字符串
      signType: 'MD5', //签名方式
      paySign: data.paySign
    },
    function (res) {
      console.log(JSON.stringify(res))
      // 支付成功
      if (res.err_msg == 'get_brand_wcpay_request:ok') {
        successful(res)
      }
      // 支付过程中用户取消
      if (res.err_msg == 'get_brand_wcpay_request:cancel') {
        cancel(res)
      }
      // 支付失败
      if (res.err_msg == 'get_brand_wcpay_request:fail') {
        failure(res)
      }
      /**
       * 其它
       * 1、请检查预支付会话标识prepay_id是否已失效
       * 2、请求的appid与下单接口的appid是否一致
       * */
      if (res.err_msg == '调用支付JSAPI缺少参数：total_fee') {
        failure(res)
      }
    }
  )
}

// 判断是否符合微信环境支付
export const weixinPay = function (data, successful, cancel, failure) {
  if (typeof WeixinJSBridge == 'undefined') {
    if (document.addEventListener) {
      document.addEventListener(
        'WeixinJSBridgeReady',
        function () {
          onBridgeReady(data, successful, cancel, failure)
        },
        false
      )
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', function () {
        onBridgeReady(data, successful, cancel, failure)
      })
      document.attachEvent('onWeixinJSBridgeReady', function () {
        onBridgeReady(data, successful, cancel, failure)
      })
    }
  } else {
    onBridgeReady(data, successful, cancel, failure)
  }
}

// 微信授权验证配置
export const wxConfig = function (configInfo, userInfo, cb) {
  let url = ''
  const systemInfo = uni.getSystemInfoSync()
  if (systemInfo.platform === 'android') {
    // 安卓平台
    url = window.location.href.split('#')[0] //获取到的url是当前页面的域名
  } else if (systemInfo.platform === 'ios') {
    // iOS平台
    url = getStorage('realAuthUrl')
  }
  api
    .post('/user/jsapi/sign', {
      url
    })
    .then(res => {
      const data = res.data
      if (data) {
        wx.config({
          debug: false, // 开启调试模式
          appId: data.appId, // 必填，企业号的唯一标识
          timestamp: data.timestamp, // 必填，生成签名的时间戳
          nonceStr: data.nonceStr, // 必填，生成签名的随机串
          signature: data.signature, // 必填，签名
          beta: true,
          jsApiList: [
            // 必填，需要使用的JS接口列表
            'scanQRCode',
            'checkJsApi',
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'chooseInvoiceTitle',
            'getLocation',
            'openLocation'
          ]
        })

        wx.checkJsApi({
          jsApiList: ['getLocation'],
          success: function (res) {
            if (res.checkResult.getLocation == false) {
              alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！')
              return
            }
          },
          fail: function (res) {
            console.log('checkJsApi fail=' + JSON.stringify(res))
          }
        })

        wx.ready(() => {
          cb?.()
          if (configInfo && userInfo) {
            wxShare({
              configInfo,
              userInfo
            })
          }
        })

        wx.error(function (res) {
          cb?.()
          // alert('出错了：' + res.errMsg) //wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
        })
      } else {
        // alert('获取配置信息返回为空')
      }
    })
}

// 微信扫码
export const wxScanCode = function (scanType = ['qrCode', 'barCode']) {
  return new Promise((resolve, reject) => {
    wx.scanQRCode({
      needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
      scanType: scanType,
      success: res => {
        console.log(res)
        var result = res.resultStr // 当 needResult 为 1 时，扫码返回的结果
        var resultArr = result.split(',') // 扫描结果以逗号分割数组
        var codeVal = resultArr[resultArr.length - 1] // 获取数组最后一个元素，也就是最终的内容
        resolve(codeVal)
      },
      fail: res => {
        reject('')
        alert('wx.scanQRCode失败')
      }
    })
  })
}

export const wxShare = function (options = {}) {
  if (!options) return
  const { configInfo, userInfo, title, desc, link, imgUrl } = options

  var appid = getQueryVariable('appid') || getQueryVariable('appId')
  wx.updateAppMessageShareData({
    title: title || `${userInfo.nickName}向你推荐了「${configInfo.minAppName}」`, // 分享标题
    desc: desc || '点击查看', // 分享描述
    link:
      link ||
      `${process.env.VUE_APP_HREF}/pages/index/index?appid=${appid}&serviceId=${userInfo.userId}&isAuthorization=1`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
    imgUrl: imgUrl || `${configInfo.minLogo3}`, // 分享图标
    success: function () {
      // 设置成功
    },
    fail: function (err) {
      // alert(JSON.stringify(err))
    }
  })
  wx.updateTimelineShareData({
    title: title || `${userInfo.nickName}向你推荐了「${configInfo.minAppName}」`, // 分享标题
    desc: desc || '点击查看', // 分享描述
    link:
      link ||
      `${process.env.VUE_APP_HREF}/pages/index/index?appid=${appid}&serviceId=${userInfo.userId}&isAuthorization=1`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
    imgUrl: imgUrl || `${configInfo.minLogo3}`, // 分享图标
    success: function () {
      // 设置成功
    },
    fail: function (err) {
      // alert(JSON.stringify(err))
    }
  })
}

export default {
  getQueryVariable,
  webLogin,
  getUserInfo,
  getConfigInfo,
  getTemplateInfo,
  getNoticeNum,
  getOrderNum,
  uploadImgFull,
  uploadImg,
  getArea,
  uploadImgs,
  matchFileSuffixType,
  formatterDate,
  compareTime,
  timeToDate,
  selectionChange,
  weixinPay,
  wxConfig,
  wxScanCode,
  wxShare
}
