const QQMapWX = require('../common/component/mapSDK/qqmap-wx-jssdk.min.js');
const app = require('../app.js');

var regChar = { //非特殊字符作为值
  '?':'qweqwqjoijweq',
  '&':'asdauihdasfsdas',
  '=':'fqwebwfubwefqwf'
}

function formatTime(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();

  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  );
}
function formatTimeTxt(year, month, day) {
  return [year, month, day].map(formatNumber).join('');
}
function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
}
function makeNumToHour(n) {
  return formatNumber(n) + ':00';
}
function makeHourToNum(t) {
  return parseInt(t.toString().split(':')[0]);
}
function makeNumToDay(n) {
  return '周' + '日一二三四五六'[n];
}
function makeNumToFullTimeArr(n) {
  // 20171010
  n = n.toString();
  let year = n.substring(0, 4);
  let month = n.substring(4, 6);
  let date = n.substring(6, 8);
  return [year, month, date];
}
function isPhoneNum(txt) {
  return /^1[34578]\d{9}$/.test(txt);
}
function arrUniqueFilter(arr) {
  return arr.filter((item, pos, array) => array.indexOf(item) === pos);
}
function bindInput(event) {
  var obj = {},
    key = event.target.dataset['key'];
  // Toast.showToast('success', event.detail.value);
  obj[key] = event.detail.value;
  this.setData(obj);
  // console.log(obj[key])
}
function encodeParam(str){
  var encode = [];
  var tempSwitch = false
  for (let i = 0; i < str.length; i++) {
    Object.keys(regChar).forEach(function(key){
      if (str.charAt(i) === key){
        encode.push(regChar[key]);
        tempSwitch = true
        return;
      }
    })
    if (!tempSwitch){
      encode.push(str.charAt(i))
    }
    tempSwitch = false
  }
  return encode.join('')
}

function decodeParam(str) {
  var keyReg = ''
  Object.keys(regChar).forEach(function (key) {
    keyReg = new RegExp(regChar[key],'g')
    // console.log(regChar[key])
    str = str.replace(keyReg, key)
  })
  return str
}
function removeArrItem(arr, item) {
  var newarr = [];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] != item) {
      newarr.push(arr[i]);
    }
  }
  return newarr;
}
class Timer {
  constructor({ max, delay = 1000 }) {
    console.log(max, delay);
    this.timer = null;
    this.max = max;
    this.delay = delay;
  }
  run(cb) {
    this.timer = setInterval(() => {
      if (this.max >= 0) {
        cb && cb(this.max--);
      } else {
        this.cancel();
      }
    }, this.delay);
  }
  cancel() {
    this.timer && clearInterval(this.timer);
  }
}
class Toast {
  constructor() {
    // this.successImage = 'images/icon-success.png';
    // this.warnImage = '../../../images/icon-warn.png';
    // this.loadingImage = 'images/icon-loading.png';
    this.image = {
      success: '../../../images/icon-success.png',
      warn: '../../../images/icon-warn.png',
      loading: '../../../images/icon-loading.png'
    };
  }
  showToast(type = 'success', title, success = () => { }) {
    let imgUrl = '';
    let t = '';
    switch (type) {
      case 'success':
      case 'tip':
        wx.showModal({
          title: '提示',
          content: title,
          showCancel: false,
          confirmColor: '#e83828',
          success
        });
        break;
      case 'warn':
        // imgUrl = this.warnImage;
        t = type == 'success' ? '成功' : '提示';
        wx.showModal({
          title: t,
          content: title,
          showCancel: false,
          confirmColor: '#e83828',
          success
        });
        break;
      case 'loading':
        wx.showToast({
          //title: '手机号码输入错误',
          title: title || '加载中...',
          icon: type,
          mask: true
        });
        break;
    }
  }
  showToast2(type = 'success', title = '') {
    switch (type) {
      case 'loading':
        wx.showLoading({
          mask: true,
          title: title || '加载中...'
        });
        break;
      case 'success':
      case 'warn':
      default:
        wx.showToast({
          //title: '手机号码输入错误',
          title: title,
          icon: type,
          image: this.image[type],
          mask: true
        });
        break;
    }
  }
  hideLoading() {
    wx.hideLoading();
  }
}
//记录访问id 存储在全局
function recordAccess(options){
  if(!options.id)return;
  let {
    cookieIDs = []
  } = app.default.globalData;
  let id = options.id;

  for (let i = 0; i < cookieIDs.length; i++) {
    if (cookieIDs[i] && id == cookieIDs[i]) {
      cookieIDs = removeArrItem(cookieIDs, cookieIDs[i])
    }
  }

  if (id != undefined && (typeof (Number(id)) == 'number')) {
    cookieIDs.unshift(id)
  }
  console.log(id)

  app.default.globalData.cookieIDs = cookieIDs

  console.log(app.default.globalData.cookieIDs)
}

module.exports = {
  formatTime,
  removeArrItem,
  formatTimeTxt,
  formatNumber,
  isPhoneNum,
  makeNumToHour,
  makeHourToNum,
  makeNumToDay,
  makeNumToFullTimeArr,
  arrUniqueFilter,
  Timer,
  bindInput,
  encodeParam,
  decodeParam,
  recordAccess,
  Toast: new Toast(),
  qqmapsdk: new QQMapWX({
    key: '2Z3BZ-H7EWO-F4YWX-SG5JF-2VOK2-S2FUB'
  })
};
