import qrcode from './qrcode.js'
// import barcode from './barcode.js'
import { get, post } from './http.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 urlToObj = function (url) {
  let obj = {}
  let str = url.slice(url.indexOf('?') + 1)
  let arr = str.split('&')
  for (let i = 0; i < arr.length; i++) {
    let arr_temp = arr[i].split('=')
    obj[arr_temp[0]] = arr_temp[1]
  }
  return obj
}

const removeCss = function (content) {
  let reg = /(style|class)="[^"]+"/gi
  let img = /<img[^>]+>/gi
  let res
  if (img.test(content)) {
    res = content.match(img)
    for (let i = 0; i < res.length; i++) {
      console.log(res[i].replace(reg, ''))
      content = content.replace(res[i], res[i].replace(reg, ''))
    }
  }
  // (/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"')
  return content.replace(/\<img/gi, '<img class="richImg"  ')
}

const getPrePage = function (content) {
  let pages = getCurrentPages()
  return pages[pages.length - 1]
}

const objToParam = function (param) {
  if (Object.prototype.toString.call(param) !== '[object Object]') {
    return ''
  }
  let queryParam = ''
  for (let key in param) {
    if (param.hasOwnProperty(key)) {
      let value = param[key]
      queryParam += toQueryPair(key, value)
    }
  }
  return queryParam
}

let callBackList = []
let timer_

/**
 * 开启定时器
 */
const startTimer = function () {
  if (!timer_) {
    timer_ = setInterval(() => {
      if (callBackList.length == 0) {
        console.log('倒计时结束 关闭定时器')
        clearInterval(timer_)
        timer_ = null
      }
      callBackList.forEach((item, index) => {
        item.currentTime--
        var h = parseInt(item.currentTime / 3600) //小时
        var m = parseInt((item.currentTime / 60) % 60) //分钟
        var s = parseInt(item.currentTime % 60) //当前的秒
        let obj = {
          h,
          m,
          s,
          currentTime: item.currentTime
        }
        item.fn(obj)
        if (item.currentTime <= 0) {
          callBackList.splice(index, 1)
        }
      })
    }, 1000)
  }
}

const addTime = function (callback, currentTime) {
  if (currentTime) {
    callBackList.push({ fn: callback, currentTime })
    console.log('第' + callBackList.length + '个倒计时开启')
    if (!timer_) {
      startTimer()
    }
  }
}

const removeTime = function (fn) {
  for (var i = 0; i < callBackList.length; i++) {
    let item = callBackList[i]
    if (item.fn == fn) {
      console.log('清除倒计时~')
      callBackList.splice(i, 1)
    }
  }
}

function toQueryPair(key, value) {
  if (typeof value == 'undefined') {
    return `${key}=&`
  }
  return `${key}=${value}&`
}

/**
 * 插件内部是根据width, height参数的rpx值来进行绘画
 * 把数字转换成条形码
 */
// function toBarcode(canvasId, code, width, height) {
//   barcode.code128(wx.createCanvasContext(canvasId), code, width, height)
// }

/**
 * 把数字转换成二维码
 */
function toQrcode(canvasId, code, width, height) {
  let pixelRatio1 = 750 / wx.getSystemInfoSync().windowWidth
  qrcode.api.draw(code, {
    ctx: wx.createCanvasContext(canvasId),
    width: width / pixelRatio1,
    height: height / pixelRatio1
  })
}

/**
 * @description 函数节流: 每隔一段时间，只执行一次函数
 * @param { Function } fn 需要延迟执行的函数
 * @param { Number } interval 延迟执行的时间，默认值500ms
 */
function throttle(fn, interval = 200) {
  // 记录定时器id
  let timer = null // 是否是第一次调用
  let isFirstTime = true
  return function () {
    const args = arguments
    const _me = this // 第一次直接执行,改变标志,无需延迟
    if (isFirstTime) {
      fn.apply(_me, args)
      return (isFirstTime = false)
    } // 不是第一次 // 存在定时器,前面的延迟操作没有完成,直接返回,拒绝调用请求
    if (timer) {
      return false
    } // 延迟执行
    timer = setTimeout(() => {
      clearTimeout(timer)
      timer = null
      fn.apply(_me, args)
    }, interval)
  }
}

/**
 * @description 函数防抖: 延迟函数执行，并且不管触发多少次都只执行最后一次
 * @param {Function} fn
 * @param {Number} interval
 */
function debounce(fn, interval) {
  let timer = null
  let gapTime = interval || 200 //间隔时间，如果interval不传，则默认200ms
  return function () {
    clearTimeout(timer)
    let context = this
    let args = arguments //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
    timer = setTimeout(function () {
      fn.call(context, args)
    }, gapTime)
  }
}

/**
 * 店铺信息
 * /api/store/info
 */
function getStoreInfo(store_id) {
  return new Promise((resolve, reject) => {
    get(
      'api/store/info',
      {
        store_id
      },
      (res) => {
        wx.setStorageSync('store_id', String(store_id))
        getApp().globalData.storeData = res.data
        resolve(res.data)
      },
      (err) => {
        reject(err)
      }
    )
  })
}

/**
 * @description 用户点击行为统计 v2/api/user/user_click
 * @param  {string} type
 * 1是推送的点击 2是订单详情点击 3是banner充值 4是上镜小V脸 5是banner新人体验活动   7是邀请 8是被邀请
 */
async function  trackUserEvent(type) {
  try {
    let resp = await post('v2/api/user/user_click', { type })      
    if (resp === 200) {
      // 数据上报成功
    }
  } catch (error) {
    // 上报失败
    console.log(error)
  }
}

module.exports = {
  formatTime,
  urlToObj,
  removeCss,
  getPrePage,
  objToParam,
  addTime,
  removeTime,
  toQrcode,
  throttle,
  debounce,
  getStoreInfo,
  trackUserEvent
}
