const app = getApp()
//金额最多保留6位小数
const decimal = num => {
  let numStr = num.toString()
  if (numStr.indexOf('.') > -1) {
    let intNum = numStr.split('.')[0]
    let decimal = numStr.split('.')[1]
    if (decimal.length > 6) {
      decimal = decimal.substring(0, 6)
    }
    return Number(intNum + '.' + decimal)
  } else {
    return num
  }
}
//数组去重
const unique = arr => {
  return [...new Set(arr)]
}
//打开文档
const openDoc = link => {
  wx.showLoading({
    title: '文档加载中...'
  })
  wx.downloadFile({
    url: link,
    success: res => {
      const filePath = res.tempFilePath
      wx.openDocument({
        filePath: filePath,
        success: res => {
          wx.hideLoading()
        }
      })
    }
  })
}
//退出登录
const loginOut = () => {
  wx.clearStorage()
  toLogin()
}
//选择图片
const chooseImage = params => {
  return new Promise((resolve, reject) => {
    let count = 1
    let sizeType = ['original', 'compressed']
    let sourceType = ['album', 'camera']
    if (params) {
      if (params.count) {
        count = params.count
      }
      if (params.sizeType) {
        sizeType = params.sizeType
      }
      if (params.sourceType) {
        sourceType = params.sourceType
      }
    }
    wx.chooseImage({
      count: count,
      sizeType: sizeType,
      sourceType: sourceType,
      success: res => {
        if (params.sendBefore) {
          params.sendBefore()
        }
        resolve(res)
      },
      fail: err => {
        reject(err)
      },
      complete: () => {
        if (params.complete) {
          params.complete()
        }
      }
    })
  })
}
//上传单个文件
const uploadFile = params => {
  if (!params.filePath) {
    toast('未获取到文件临时路径，请重试')
    return
  }
  let token = wx.getStorageSync('token')
  let header = {
    'content-type': 'multipart/form-data'
  }
  if (token) {
    header.token = token
  }
  return new Promise((resolve, reject) => {
    if (params.sendBefore) {
      params.sendBefore()
    }
    wx.uploadFile({
      url: app.globalData.globalUrl + params.url,
      filePath: params.filePath,
      name: params.name ? params.name : 'file',
      header: header,
      formData: params.formData ? params.formData : {},
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
      },
      complete: () => {
        if (params.complete) {
          params.complete()
        }
      }
    })
  })
}
//获取当前用户登录角色(1是企业，2是服务商，3是运营商，99是未知)
const getInfo = () => {
  let userInfo = wx.getStorageSync('userInfo')
  return userInfo
}
const getCurrEntInfo=()=>{
  let entInfo = wx.getStorageSync('company')
  return entInfo
}

//当前登录账号的默认企业
// const getCompany = params => {
//   return new Promise((resolve, reject) => {
//     let params = {
//       mobile: wx.getStorageSync('userInfo').mobile
//     }
//     axios({
//       method: 'get',
//       url: '/auth/comm/user/findDefaultChoose',
//       data: params,
//       success: res => {
//         resolve(res)
//       },
//       sendBefore: () => {
//         if (params.sendBefore) {
//           params.sendBefore()
//         }
//       },
//       error: res => {
//         if (params.error) {
//           params.error(res)
//         }
//       },
//       complete: () => {
//         if (params.complete) {
//           params.complete()
//         }
//       },
//       noLogin: res => {
//         if (params.noLogin) {
//           params.noLogin()
//         } else {
//           toLogin()
//         }
//       }
//     })
//   })
// }
//服务商用户
const getIsp = () => {
  return new Promise((resolve, reject) => {
    let params = {
      mobile: wx.getStorageSync('userInfo').mobile
    }
    axios({
      method: 'get',
      url: '/auth/isp/info/findByMobile',
      data: params,
      success: res => {
        resolve(res)
      },
      sendBefore: () => {
        if (params.sendBefore) {
          params.sendBefore()
        }
      },
      error: res => {
        if (params.error) {
          params.error(res)
        }
      },
      complete: () => {
        if (params.complete) {
          params.complete()
        }
      },
      noLogin: res => {
        if (params.noLogin) {
          params.noLogin()
        } else {
          toLogin()
        }
      }
    })
  })
}
//运营商用户
const getOper = () => {
  return new Promise((resolve, reject) => {
    let params = {
      mobile: wx.getStorageSync('userInfo').mobile
    }
    axios({
      method: 'get',
      url: '/auth/oper/user/findManageInfoByMobile',
      data: params,
      success: res => {
        resolve(res)
      },
      sendBefore: () => {
        if (params.sendBefore) {
          params.sendBefore()
        }
      },
      error: res => {
        if (params.error) {
          params.error(res)
        }
      },
      complete: () => {
        if (params.complete) {
          params.complete()
        }
      },
      noLogin: res => {
        if (params.noLogin) {
          params.noLogin()
        } else {
          toLogin()
        }
      }
    })
  })
}
//获取个人信息
const getUser = params => {
  return new Promise((resolve, reject) => {
    let userInfo = wx.getStorageSync('userInfo')
    let iparams = {
      mobile: userInfo.mobile
    }
    axios({
      method: 'get',
      url: '/auth/comm/user/personalInfo/find',
      data: iparams,
      success: res => {
        resolve(res)
      },
      sendBefore: () => {
        if (params.sendBefore) {
          params.sendBefore()
        }
      },
      error: res => {
        if (params.error) {
          params.error(res)
        }
      },
      complete: () => {
        if (params.complete) {
          params.complete()
        }
      },
      noLogin: res => {
        if (params.noLogin) {
          params.noLogin()
        } else {
          toLogin()
        }
      }
    })
  })
}
//跳转登录页
const toLogin = () => {
  wx.navigateTo({
    url: '/pages/login/login'
  })
}
//获取图片信息
const getImgInfo = url => {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: url,
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}
//执行上一页的函数
const funPrev = callback => {
  let pages = getCurrentPages()
  let prevPage = pages[pages.length - 2]
  callback(prevPage)
}
//格式化时间
const formatTime = (date, type = 1) => {
  if (!(date instanceof Date)) {
    date = new Date(date)
  }
  const curDate = new Date()
  const curYear = curDate.getFullYear()
  const curMonth = curDate.getMonth() + 1
  const curDay = curDate.getDate()
  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()
  if (type === 1) {
    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 getShortTime = timeStamp => {
  let result = ''
  let minute = 1000 * 60
  let hour = minute * 60
  let day = hour * 24
  let halfamonth = day * 15
  let month = day * 30
  let now = new Date().getTime()
  let diffValue = now - timeStamp
  if (diffValue < 0) {
    return
  }
  let monthC = diffValue / month
  let weekC = diffValue / (7 * day)
  let dayC = diffValue / day
  let hourC = diffValue / hour
  let minC = diffValue / minute
  if (monthC >= 1) {
    result = '' + parseInt(monthC) + '月前'
  } else if (weekC >= 1) {
    result = '' + parseInt(weekC) + '周前'
  } else if (dayC >= 1) {
    result = '' + parseInt(dayC) + '天前'
  } else if (hourC >= 1) {
    result = '' + parseInt(hourC) + '小时前'
  } else if (minC >= 1) {
    result = '' + parseInt(minC) + '分钟前'
  } else
    result = '刚刚'
  return result
}
//获取系统信息
const getSystemInfo = () => {
  return new Promise((resolve, reject) => {
    wx.getSystemInfo({
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}
//去掉所有空格
const trimAll = text => {
  text = text + ''
  return text.replace(/\s/ig, '')
}
//验证手机号码是否正确
const testMobile = mobile => {
  mobile = trimAll(mobile)
  if (!(/^1\d{10}$/.test(mobile))) {
    return false
  } else {
    return true
  }
}
//验证邮箱是否正确
const testEmail = email => {
  email = trimAll(email)
  if (!(/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(email))) {
    return false
  } else {
    return true
  }
}
//错误提示
const toast = text => {
  setTimeout(() => {
    wx.showToast({
      title: text,
      icon: 'none',
      duration: 2500
    })
  }, 10)
}
//获取登录态login的code
const getLoginCode = () => {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '参数获取中...',
      mask: true
    })
    wx.login({
      success: res => {
        if (res.code) {
          resolve(res)
        } else {
          reject(res)
        }
      },
      fail: err => {
        reject(err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  })
}
// 获取当前时间
const getNowDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month,day].map(formatNumber).join('-')
}
//字典
const code = {
  '0': '请求成功',
  '10000': '系统服务异常，请联系管理员',
  '10001': '传入数据错误',
  '10002': '账号不存在',
  '10003': '密码不正确',
  '10004': '账号已被锁定,请联系管理员',
  '10005': '60秒内不能重复发送短信',
  '10006': '调用接口获取短信验证码失败',
  '10007': '手机号码验证错误',
  '10008': '手机短信验证码校验错误',
  '10009': '手机短信校验超时',
  '10010': '请求第三方接口错误',
  '10011': '数据库操作失败',
  '10012': '未知渠道，请检查渠道相关参数',
  '10013': '注册用户类型错误',
  '10014': '对应的用户已经存在',
  '10015': '系统参数配置错误',
  '10016': '修改命令状态未找到对应数据记录',
  '10017': '未知命令执行状态',
  '10018': '超级管理员及角色不允许修改',
  '10019': '新增角色名已存在',
  '10020': '两次输入密码不一致',
  '10021': '对应的管理人员不存在',
  '10022': '注册添加用户类型与请求路径不匹配',
  '10023': '登录失败',
  '10024': '用户层级管理关系数据错误',
  '10025': '无该企业的操作权限',
  '10026': '注册管理者无法在用户管理模块删除',
  '10027': '该产品需绑定在对应的企业',
  '10028': '企业下产品编码重复',
  '10029': '客户编码重复',
  '10030': '未找到对应的开票企业信息',
  '10031': '该发票类型或状态不允许红冲',
  '10032': '未找到企业对应的服务商',
  '10033': 'MQ消息未找到对应的指令',
  '10034': '根据指令id 未找到对应的开票信息',
  '10035': 'MQ返回结果发票请求流水号和本地流水号不一致',
  '10036': 'MQ 返回结果解析为空',
  '10037': '根据指令id 未找到对应的红冲信息',
  '10038': 'MQ推送指令消息失败',
  '10039': '设置默认选定项没有对应的数据'
}
//保存到相册
const savePhoto = tempUrl => {
  wx.saveImageToPhotosAlbum({
    filePath: tempUrl,
    success: res => {
      wx.hideLoading()
      toast('保存成功，快去相册查看吧')
    },
    fail: err => {
      if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
        wx.showModal({
          title: '提示',
          content: '需要您授权保存相册',
          showCancel: false,
          success: () => {
            wx.openSetting({
              success: settingdata => {
                if (settingdata.authSetting['scope.writePhotosAlbum']) {
                  wx.showModal({
                    title: '提示',
                    content: '获取权限成功,请再次尝试将二维码保存到相册',
                    showCancel: false
                  })
                } else {
                  wx.showModal({
                    title: '提示',
                    content: '获取权限失败，将无法保存二维码到相册哦',
                    showCancel: false
                  })
                }
              }
            })
          }
        })
      }
    },
    complete: () => {
      wx.hideLoading()
    }
  })
}
//网络请求
const axios = params => {
  let token = ''
  if (wx.getStorageSync('token')) {
    token = wx.getStorageSync('token')
  }
  if (!params.method) {
    params.method = 'get'
  }
  if (params.sendBefore) {
    params.sendBefore()
  }
  if (!params.responseType) {
    params.responseType = 'text'
  }
  if (!params.header) {
    params.header = {
      'content-type': 'application/json'
    }
  }
  if (token) {
    params.header.token = token
  }
  wx.request({
    method: params.method,
    url: app.globalData.globalUrl + params.url,
    data: params.data,
    responseType: params.responseType,
    header: params.header,
    success: res => {
      let result = res.data
      console.log('params.url=>' + params.url, params.data, res.data)
      if (result.code === 0) { //code为0，说明请求成功
        if (params.success) {
          params.success(result)
        } else {
          console.log(params.url + '接口请求成功=>请求结果为=>', res)
        }
      } else { //code不为0，说明请求失败
        if (result.status === 403 || result.status==401) { //status为403，说明未登录或者登录态失效，则跳转登录
          if (params.noLogin) {
            params.noLogin()
          } else {
            toLogin()
          }
        } else { //status不为403，则表示有错误，弹出错误
          if (params.error) {
            params.error(result)
          } else {
            if (result.msg) {
              toast(result.msg)
            }
            console.log(params.url + '接口请求错误=>请求结果为=>', result)
          }
        }
      }
    },
    complete: res => {
      if (params.complete) {
        params.complete(res)
      } else {
        console.log(params.url + '=>complete=>', res)
      }
    },
    fail: res => {
      if (params.fail) {
        params.fail(res)
      } else {
        console.log(params.url + '-fail', res)
      }
    }
  })
}
module.exports = {
  decimal,
  unique,
  openDoc,
  loginOut,
  uploadFile,
  chooseImage,
  getInfo,
  getCurrEntInfo,
  // getCompany,
  getIsp,
  getOper,
  getUser,
  toLogin,
  getImgInfo,
  funPrev,
  formatTime,
  getShortTime,
  getSystemInfo,
  trimAll,
  testMobile,
  testEmail,
  toast,
  getLoginCode,
  savePhoto,
  axios,
  getNowDate
}