import { baseURL } from '../constant.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
}

const $httpServer = (config = {}) => {
  const { url, data, method} = config
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseURL}/${url}`,
      data,
      method: method,
      success(response) {
        resolve(response.data)
      },
      error(err) {
        reject(err)
      }
    })
  })
}

const query2search = (query) => Object.keys(query).map(k => (`${k}=${query[k]}`)).join('&')

module.exports = {
  formatTime: formatTime,
  $httpServer: $httpServer,
  query2search: query2search,
}