const config = require('../config/index.js')

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
}

//获取图片路径 param：图片名称带扩展名
const imgName = (imgNameWithExt = 'no.jpg') => {
  return `${config.imgPath}${imgNameWithExt}`
}

function noAuthNav() {
  wx.clearStorageSync()
  const pages = getCurrentPages();
  const ctx = pages[pages.length - 1];
  if (ctx.route !== 'pages/register2/register2') {
    wx.navigateTo({
      url: '/pages/register2/register2'
    })
  }
}
//api  param:根路径后面的路由
const api = {
  get: (url, query, notShowLoad) => {
    if (!notShowLoad) {
      wx.showLoading({
        mask: true,
      })
    }
    let sessionHead = {
      "Accept-Language": "zh-CN"
    }
    sessionHead['content-type'] = 'application/x-www-form-urlencoded'
    sessionHead.token = wx.getStorageSync('user') ? wx.getStorageSync('user').token : ''
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.api}${url}`,
        // data: Object.assign({}, { userId: wx.getStorageSync('user') ? wx.getStorageSync('user').userId : '' }, query),
        data: query,
        method: 'GET',
        header: sessionHead,
        success(res) {
          if (res.statusCode == 200) {
            if (res.data.success) {
              resolve(res.data)
            } else {
              reject(res.data.message)
            }
            return
          }
          if (res.statusCode == 401) {
            reject('请登录')
            noAuthNav()
            return
          }
          reject(res.data, '请求成功')
        },
        fail(res) {
          console.error('1', res)
          reject(res.data, '请求失败')
        },
        complete() {
          if (!notShowLoad) {
            wx.hideLoading()
          }
        }
      })
    })
  },
  post: (url, body, head, notShowLoad, errData = false) => {
    if (!notShowLoad) {
      wx.showLoading({
        mask: true,
      })
    }
    let sessionHead = {
      'content-type': 'application/x-www-form-urlencoded',
      "Accept-Language": "zh-CN"
    }
    sessionHead.token = wx.getStorageSync('user') ? wx.getStorageSync('user').token : ''
    if (head) {
      sessionHead = Object.assign(sessionHead, head)
    }
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.api}${url}`,
        // data: Object.assign({}, { userId: wx.getStorageSync('user') ? wx.getStorageSync('user').userId : '' }, body),
        data: body,
        method: 'POST',
        header: sessionHead,
        success(res) {
          if (res.statusCode == 200) {
            if (res.data.success) {
              resolve(res.data)
            } else {
              reject(res.data.message)
            }
            return
          }
          if (res.statusCode == 401) {
            reject('请登录')
            noAuthNav()
            return
          }
          reject(res.data, '请求成功')
        },
        fail(res) {
          console.error('1', res)
          reject(res.data, '请求失败')
        },
        complete() {
          if (!notShowLoad) {
            wx.hideLoading()
          }
        }
      })
    })
  }
}
//mockApi 
const mockApi = {
  get: (url, query, notShowLoad) => {
    if (!notShowLoad) {
      wx.showLoading({
        mask: true,
      })
    }
    let sessionHead = {
      "Accept-Language": "zh-CN"
    }
    sessionHead['content-type'] = 'application/x-www-form-urlencoded'
    sessionHead.token = wx.getStorageSync('user') ? wx.getStorageSync('user').token : ''
    return new Promise((resolve, reject) => {
      wx.request({
        url,
        // data: Object.assign({}, { userId: wx.getStorageSync('user') ? wx.getStorageSync('user').userId : '' }, query),
        data: query,
        method: 'GET',
        header: sessionHead,
        success(res) {
          if (res.statusCode == 200) {
            if (res.data.success) {
              resolve(res.data)
            } else {
              reject(res.data.message)
            }
            return
          }
          if (res.statusCode == 401) {
            reject('请登录')
            noAuthNav()
            return
          }
          reject(res.data, '请求成功')
        },
        fail(res) {
          console.error('1', res)
          reject(res.data, '请求失败')
        },
        complete() {
          if (!notShowLoad) {
            wx.hideLoading()
          }
        }
      })
    })
  }
}
//api 站点相关api
const rapi = {
  get: (url, query, notShowLoad) => {
    if (!notShowLoad) {
      wx.showLoading({
        mask: true,
      })
    }
    let sessionHead = {
      "Accept-Language": "zh-CN"
    }
    sessionHead['content-type'] = 'application/x-www-form-urlencoded'
    sessionHead.token = wx.getStorageSync('user') ? wx.getStorageSync('user').token : ''
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.rapi}${url}`,
        // data: Object.assign({}, { userId: wx.getStorageSync('user') ? wx.getStorageSync('user').userId : '' }, query),
        data: query,
        method: 'GET',
        header: sessionHead,
        success(res) {
          if (res.statusCode == 200) {
            if (res.data.success) {
              resolve(res.data)
            } else {
              reject(res.data.message)
            }
            return
          }
          if (res.statusCode == 401) {
            reject('请登录')
            noAuthNav()
            return
          }
          reject(res.data, '请求成功')
        },
        fail(res) {
          console.error('1', res)
          reject(res.data, '请求失败')
        },
        complete() {
          if (!notShowLoad) {
            wx.hideLoading()
          }
        }
      })
    })
  },
  post: (url, body, head, notShowLoad) => {
    if (!notShowLoad) {
      wx.showLoading({
        mask: true,
      })
    }
    let sessionHead = {
      'content-type': 'application/x-www-form-urlencoded',
      "Accept-Language": "zh-CN"
    }
    sessionHead.token = wx.getStorageSync('user') ? wx.getStorageSync('user').token : ''
    if (head) {
      sessionHead = Object.assign(sessionHead, head)
    }
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.rapi}${url}`,
        // data: Object.assign({}, { userId: wx.getStorageSync('user') ? wx.getStorageSync('user').userId : '' }, body),
        data: body,
        method: 'POST',
        header: sessionHead,
        success(res) {
          console.log('1', res)
          if (res.statusCode == 200) {
            if (res.data.success) {
              resolve(res.data)
            } else {
              reject(res.data.message)
            }
            return
          }
          if (res.statusCode == 401) {
            reject('请登录')
            noAuthNav()
            return
          }
          reject(res.data, '请求成功')
        },
        fail(res) {
          console.error('1', res)
          reject(res.data, '请求失败')
        },
        complete() {
          if (!notShowLoad) {
            wx.hideLoading()
          }
        }
      })
    })
  }
}
//payApi
const payApi = {
  get: (url, query, notShowLoad) => {
    if (!notShowLoad) {
      wx.showLoading({
        mask: true,
      })
    }
    let sessionHead = {
      "Accept-Language": "zh-CN"
    }
    sessionHead['content-type'] = 'application/x-www-form-urlencoded'
    sessionHead.token = wx.getStorageSync('user') ? wx.getStorageSync('user').token : ''
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.payapi}${url}`,
        // data: Object.assign({}, { userId: wx.getStorageSync('user') ? wx.getStorageSync('user').userId : '' }, query),
        data: query,
        method: 'GET',
        header: sessionHead,
        success(res) {
          if (res.statusCode == 200) {
            if (res.data.success && res.data.message == 'SUCCESS') {
              resolve(res.data.data)
            } else {
              reject(res.data.data)
            }
            return
          }
          if (res.statusCode == 401) {
            reject('请登录')
            noAuthNav()
            return
          }
          reject(res.data, '请求成功')
        },
        fail(res) {
          console.error('1', res)
          reject(res.data, '请求失败')
        },
        complete() {
          if (!notShowLoad) {
            wx.hideLoading()
          }
        }
      })
    })
  },
  post: (url, body, head, notShowLoad) => {
    if (!notShowLoad) {
      wx.showLoading({
        mask: true,
      })
    }
    let sessionHead = {
      'content-type': 'application/x-www-form-urlencoded',
      "Accept-Language": "zh-CN"
    }
    sessionHead.token = wx.getStorageSync('user') ? wx.getStorageSync('user').token : ''
    if (head) {
      sessionHead = Object.assign(sessionHead, head)
    }
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.payapi}${url}`,
        // data: Object.assign({}, { userId: wx.getStorageSync('user') ? wx.getStorageSync('user').userId : '' }, body),
        data: body,
        method: 'POST',
        header: sessionHead,
        success(res) {
          if (res.statusCode == 200) {
            if (res.data.success && res.data.message == 'SUCCESS') {
              resolve(res.data.data)
            } else {
              reject(res.data.data)
            }
            return
          }
          if (res.statusCode == 401) {
            reject('请登录')
            noAuthNav()
            return
          }
          reject(res.data, '请求成功')
        },
        fail(res) {
          console.error('1', res)
          reject(res.data, '请求失败')
        },
        complete() {
          if (!notShowLoad) {
            wx.hideLoading()
          }
        }
      })
    })
  }
}


//获取用户权限
const getUserAuth = () => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: (authsettings) => {
        resolve(authsettings.authSetting)
      },
      fail: () => {
        reject('获取用户权限失败')
      }
    })
  })
}
//获取用户信息
const getUserInfo = () => {
  return new Promise((resolve, reject) => {
    getUserAuth()
      .then(authsettings => {
        console.log('授权信息', authsettings)
        if (authsettings['scope.userInfo'] == undefined) {
          wx.getUserInfo({
            withCredentials: true,
            lang: 'zh_CN',
            success: (userinfo) => {
              resolve(userinfo)
            },
            fail: () => {
              reject('用户信息未授权')
            }
          })
        } else if (authsettings['scope.userInfo'] == false) {
          reject('用户信息未授权')
        } else {
          wx.getUserInfo({
            withCredentials: true,
            lang: 'zh_CN',
            success: (userinfo) => {
              resolve(userinfo)
            },
            fail: () => {
              reject('用户信息获取失败')
            }
          })
        }
      })
      .catch(err => {
        reject(err)
      })
  })
}
//微信登录
const wxLogin = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        if (res.code) {
          wx.setStorageSync('loginCode', res.code)
          resolve(res.code)
        } else {
          reject('获取用户登录态失败！')
        }
      },
      fail() {
        reject('调用登录态失败！')
      }
    });
  })
}

//手动授权方法
const authAgainByUser = (msg) => {
  wx.showModal({
    title: '提示',
    content: msg,
    success(res) {
      if (res.confirm) {
        wx.openSetting()
      }
    }
  })
}
//获取定位
const userLocation = () => {
  return new Promise((resolve, reject) => {
    getUserAuth()
      .then(authsettings => {
        if (authsettings['scope.userLocation'] == undefined) {
          wx.getLocation({
            type: 'gcj02',
            success: (location) => {
              resolve(location)
            },
            fail: () => {
              console.log('用户位置未授权')
              reject('用户位置未授权')
            }
          })
        } else if (authsettings['scope.userLocation'] == false) {
          console.log('用户拒绝过授权')
          wx.showModal({
            title: '提示',
            content: '你拒绝了用户定位，请打开',
            success(res) {
              wx.openSetting({
                success: (res) => {
                  if (res.authSetting["scope.userLocation"]) {
                    wx.getLocation({
                      type: 'gcj02',
                      success: (location) => {
                        resolve(location)
                      },
                      fail: () => {
                        reject('用户位置获取失败')
                      }
                    })
                  }
                },
                fail(err) {
                  reject('用户没有授权')
                }
              })

            }
          })
        } else {
          wx.getLocation({
            type: 'gcj02',
            success: (location) => {
              console.log('location')
              resolve(location)
            },
            fail: () => {
              console.log('用户位置获取失败')
              reject('用户位置获取失败')
            }
          })
        }
      })
      .catch(err => {
        reject(err)
      })
  })
}
const msgTip = {
  '没有该车': '该设备不存在！',
  'timeout': '超时了,请重试！'
}
//错误提示 用于不常见错误定位 param：错误信息
const alertTip = (msg, cb) => {
  if (msg) {
    if (getType(msg) == 'object') {
      msg = JSON.stringify(msg)
    }
  }
  wx.showModal({
    title: '提示',
    content: msg,
    showCancel: false,
    success() {
      cb && cb()
    }
  })
}
const toastTip = (op) => {
  wx.showToast({
    title: '成功',
    icon: 'warn',
    ...op
  })
}
//确认提示 
const confirmTip = (msg, cb) => {
  msg = msg ? msg.toString() : 'timeout'
  wx.showModal({
    title: '提示',
    content: msgTip[msg] ? msgTip[msg] : msg,
    success(res) {
      if (res.confirm) {
        cb && cb()
      }
    }
  })
}
const wxscan = function() {
  return new Promise((resolve, reject) => {
    wx.scanCode({
      onlyFromCamera: true,
      success: function(res) {
        resolve(res.result)
      },
      fail: function(res) {
        reject('扫码失败，重试')
      }
    })
  })
}
const getProtocol = (id) => {
  function download(url) {
    url = encodeURI(url)
    let file = wx.getStorageSync('file')
    if (!file) {
      file = []
    }
    return new Promise((resolve, reject) => {
      wx.showLoading({
        mask: true,
      })
      wx.downloadFile({
        url,
        success: function(res) {
          console.log(res)
          let filePath = res.tempFilePath;
          file[+id] = filePath
          wx.setStorageSync('file', file)
          console.log('新文档', filePath)
          wx.hideLoading()
          wx.openDocument({
            filePath: filePath,
            success: function(res) {
              resolve('打开文档成功')
            },
            fail(err) {
              wx.hideLoading()
              reject(err)
            }
          })
        },
        fail(err) {
          console.error('2', err)
          wx.hideLoading()
          file[+id] = null
          reject(err.errMsg)
        }
      })
    })
  }
  return new Promise((resolve, reject) => {
    // 协议文档
    let file = wx.getStorageSync('file')
    // if (file && file[id]) {
    if (false) {
      wx.openDocument({
        filePath: file[id],
        success() {
          resolve('打开文档成功')
        },
        fail(err) {
          api.get('agreement/getById', {
              id
            })
            .then(({
              data
            }) => {
              download(data.url, file).then(res => {
                  resolve(res)
                })
                .catch(err => {
                  wx.hideLoading()
                  reject(err)
                })
            })
            .catch(err => {
              wx.hideLoading()
              reject(err)
            })
        }
      })
    } else {
      api.get('agreement/getById', {
          id
        })
        .then(({
          data
        }) => {
          return download(data.url).then(res => {
              resolve(res)
            })
            .catch(err => {
              wx.hideLoading()
              reject(err)
            })
        })
        .catch(err => {
          wx.hideLoading()
          reject(err)
        })
    }
  })
}
//预览图片  param：t
const previewPic = (current, urls) => {
  //图片预览
  wx.previewImage({
    current, // 当前显示图片的http链接
    urls: urls || [current] // 需要预览的图片http链接列表
  })
}
// 类型判断
const getType = function(o) {
  let s = Object.prototype.toString.call(o)
  return s.replace(/^\[object\s(.*)\]$/gi, ($0, $1) => {
    return $1.toLowerCase();
  })
}
//上传图片
const uploadResource = function(r, t) {
  wx.showLoading({
    title: `上传${t||'图片'}中`,
    mask: true,
  })
  // 数组型 资源
  if (getType(r) === 'array') {
    return Promise.all(r.map(item => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'https://zhizuxia.zhizukj.com/ydb/app/manage/file/upload.json',
          filePath: item,
          name: 'file',
          success(res) {
            resolve(JSON.parse(res.data).picUrl)
          },
          fail(err) {
            reject('图片上传失败')
          },
          complete(res) {
            wx.hideLoading()
          }
        })
      })
    }))
  } else {
    // 单个资源
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'https://zhizuxia.zhizukj.com/ydb/app/manage/file/upload.json',
        filePath: r,
        name: 'file',
        success(res) {
          resolve(JSON.parse(res.data).picUrl)
        },
        fail(err) {
          reject('图片上传失败')
        },
        complete(res) {
          wx.hideLoading()
        }
      })
    })
  }
}
//上传图片
const uploadFile = function(r, t) {
  wx.showLoading({
    title: `上传${t||'图片'}中`,
    mask: true,
  })
  let sessionHead = {
    "Accept-Language": "zh-CN"
  }
  sessionHead['content-type'] = 'application/x-www-form-urlencoded'
  sessionHead.token = wx.getStorageSync('user') ? wx.getStorageSync('user').token : ''
  // 数组型 资源
  if (getType(r) === 'array') {
    return
    return Promise.all(r.map(item => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: config.api,
          filePath: item,
          name: 'file',
          header: sessionHead,
          success(res) {
            resolve(JSON.parse(res.data).picUrl)
          },
          fail(err) {
            reject('图片上传失败')
          },
          complete(res) {
            wx.hideLoading()
          }
        })
      })
    }))
  } else {
    // 单个资源
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: config.api + 'user/updateAvatar',
        filePath: r,
        name: 'file',
        header: sessionHead,
        success(res) {
          resolve('图片上传成功')
        },
        fail(err) {
          reject('图片上传失败')
        },
        complete(res) {
          wx.hideLoading()
        }
      })
    })
  }
}
const changeTime = (mss) => {
  var days = parseInt(mss / (1000 * 60 * 60 * 24));
  var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = (mss % (1000 * 60)) / 1000;
  return `${days ? days + '天' : ''}${hours ? hours + '小时' : ''}${minutes ? minutes + '分钟' : ''}${seconds ? seconds + '秒' : ''}`
}
const getRgbColor = (sRgb, eRgb, rate) => {
  let rRgb = []
  sRgb = sRgb.split(',')
  eRgb = eRgb.split(',')
  eRgb.forEach((elt, i) => {
    rRgb[i] = parseInt(parseInt(sRgb[i]) + ((parseInt(elt) - parseInt(sRgb[i])) * Number(rate)))
  })
  return rRgb.join(',')
}
// 获取适配像素
let {
  windowWidth
} = wx.getSystemInfoSync()

function getPx(rpx) {
  return rpx * windowWidth / 750
}

function getRpx(px) {
  return px * 750 / windowWidth
}

function arrTarrs(num, arr) { // 一维数组转换为二维数组
  const iconsArr = []; // 声明数组
  arr.forEach((item, index) => {
    const page = Math.floor(index / num); // 计算该元素为第几个素组内
    if (!iconsArr[page]) { // 判断是否存在
      iconsArr[page] = [];
    }
    iconsArr[page].push(item);
  });
  return iconsArr;
}
module.exports = {
  formatTime,
  imgName,
  arrTarrs,
  api,
  getUserInfo,
  wxLogin,
  alertTip,
  authAgainByUser,
  userLocation,
  wxscan,
  getProtocol,
  payApi,
  rapi,
  mockApi,
  confirmTip,
  previewPic,
  toastTip,
  uploadFile,
  uploadResource,
  getRgbColor,
  getPx,
  getRpx,
  changeTime
}