var Crypto = require('cryptojs.js').Crypto;
var app = getApp();

function formatTime(date, format, isShort) {
  if (date) {
    date = new Date(ReplaceAllString(date.toString(),"-","/"));
    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()

    if (!format)
      format = "/";

    if (isShort)
      return [year, month, day].map(formatNumber).join(format);
    else
      return [year, month, day].map(formatNumber).join(format) + ' ' + [hour, minute, second].map(formatNumber).join(':');
  }
  else
    return "";
}

function checkIsArray(obj) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}

function formatDateCHS(date) {
  if (date) {
    date = date.toString();
    var year = date.substr(0, 4);
    var month = date.substr(5, 2);
    var day = date.substr(8, 2);

    if (year <= "1900")
      return "";
    else
      return year + "年" + month + "月" + day + "日";
  }
  else
    return "";
}

function formatDateENG(date, format) {
  if (date) {
    date = date.toString();
    if (!format)
      format = "/";
    date = date.replace("年", format);
    date = date.replace("月", format);
    date = date.replace("日", "");
    return date;
  }
  else
    return "";
}


function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//给字符串左侧补零
function addZero(str, length) {
  while (str.length < length) {
    str = "0" + str;
  }
  return str;
}

function getMinuteSecond(second, chs) {
  if (!second)
    second = 0;
  var secondUnit = "″";
  var minuteUnit = "′";
  var hourUnit = ":";
  if (chs) {
    secondUnit = "秒";
    minuteUnit = "分";
    hourUnit = "时";
    //second = Math.round(second);
  }
  if (second < 60)
    return second + secondUnit;
  else {
    var minute = Math.floor(second / 60);
    second = Math.round((second - minute * 60) * 1000) / 1000;

    if (minute >= 60) {
      var hour = Math.floor(minute / 60);
      minute = minute - hour * 60;

      if (minute == 0 && second == 0)
        return hour + hourUnit;
      else if (second == 0)
        return hour + hourUnit + minute + minuteUnit;
      else
        return hour + hourUnit + minute + minuteUnit + second + secondUnit;
    }
    else {
      if (second == 0)
        return minute + minuteUnit;
      else
        return minute + minuteUnit + second + secondUnit;
    }
  }
}

function Random(start, end) {
  var result = parseInt(Math.random() * (end - start + 1) + start);
  return result;
}
//打乱数组
function RandomArray(arr) {
  var arrResult = [];
  var maxCount = 0;
  do {
    var rnd = Random(0, arr.length - 1);
    if (arr[rnd]) {
      arrResult.push(arr[rnd]);
      arr[rnd] = null;
    }
    maxCount++;
  }
  while (arrResult.length < arr.length && maxCount < 1000);
  for (var i = 0; i < arr.length; i++)
    arr[i] = arrResult[i];
  return arrResult;
}

function Unique(arr) {
  var res = [];
  var json = {};
  for (var i = 0; i < arr.length; i++) {
    if (!json[arr[i]]) {
      res.push(arr[i]);
      json[arr[i]] = 1;
    }
  }
  return res;
}

function getEnumerationName(id, list) {
  for (var i = 0; i < list.length; i++) {
    if (id == list[i].EnumID) {
      return list[i].Name;
    }
  }
  return "";
}

function getEnumerationNameByDescription(description, list) {
  for (var i = 0; i < list.length; i++) {
    if (description == list[i].Description) {
      return list[i].Name;
    }
  }
  return "";
}

function getStringMaxLength(str, len) {
  if (str.length > len)
    return str.substr(0, len) + "...";
  else
    return str;
}

function sort(array, sort_order, obj, objType, obj2, objType2) {
  for (var i = 0; i < array.length - 1; i++) {
    for (var j = i + 1; j < array.length; j++) {
      var check;
      if (objType == "Number") {
        if (sort_order == "ASC")
          check = array[i][obj] > array[j][obj];
        else
          check = array[i][obj] < array[j][obj];
      }
      else {
        //console.log("array["+i+"]:"+array[i][obj]);
        //console.log("array["+j+"]:"+array[j][obj]);
        if (array[i][obj] && array[j][obj]) {
          try {
            if (sort_order == "ASC")
              check = array[i][obj].toString().localeCompare(array[j][obj].toString()) >= 0;
            else if (sort_order == "DESC")
              check = array[i][obj].toString().localeCompare(array[j][obj].toString()) < 0;
          }
          catch (ex) {
            console.log("ex:" + ex);
            if (sort_order == "ASC")
              check = array[i][obj].toString() >= array[j][obj].toString();
            else if (sort_order == "DESC")
              check = array[i][obj].toString() < array[j][obj].toString();

          }
        }
        else {
          check = false;
        }
      }
      if (check) {
        var temp = swap(array[i], array[j]);
        array[i] = temp.a;
        array[j] = temp.b;
      }
    }
  }
  return array;

  function swap(a, b) {
    var tempA = JSON.stringify(a);
    var tempB = JSON.stringify(b);
    return {
      a: JSON.parse(tempB),
      b: JSON.parse(tempA),
    }
  }
}
////测试sort
// var a = [
//   {
//     time: "2017-2-1",
//     a: 3,
//   }, {
//     time: "2017-4-1",
//     a: 5,
//   }, {
//     time: "2017-1-1",
//     a: 6
//   },{
//     time: "2017-2-1",
//     a: 3
//   },
// ];
// console.log(a);
// // var a = common.sort(a,"ASC", "time","String");
// // console.log(a);
// var a = common.sort(a,"DESC", "time","String");
// console.log(a);
// //var a = common.sort(a,"DESC", "a","Number");
// // console.log(a);

function checkError(err) {
  switch (err) {
    case 404:
    case 500:
    case 501:
    case 502:
    case 503:
    case 504:
    case 505:
      wx.redirectTo({
        url: './error',
      });
      break;
  }
  return null;
}

function Encrypt(word) {
  var mode = new Crypto.mode.CBC(Crypto.pad.pkcs7);
  var eb = Crypto.charenc.UTF8.stringToBytes(word);
  var kb = Crypto.charenc.UTF8.stringToBytes(app.globalData.Key);//KEY
  var vb = Crypto.charenc.UTF8.stringToBytes(app.globalData.IV);//IV
  var ub = Crypto.AES.encrypt(eb, kb, { iv: vb, mode: mode, asBpytes: true });
  return ub;
}

function Decrypt(word) {
  var mode = new Crypto.mode.CBC(Crypto.pad.pkcs7);
  var eb = Crypto.util.base64ToBytes(word);
  var kb = Crypto.charenc.UTF8.stringToBytes(app.globalData.Key);//KEY
  var vb = Crypto.charenc.UTF8.stringToBytes(app.globalData.IV);//IV
  var ub = Crypto.AES.decrypt(eb, kb, { asBpytes: true, mode: mode, iv: vb });
  return ub;
}

function isExistStr(str1, str2) {
  var result = false;
  if (str1) {
    if (str1.toString().indexOf(str2) >= 0) {
      result = true;
    }
  }
  return result;
}

//获取存储数据，若不存在，则获得缺省值。
function getStorageValue(obj, name, defaultStatus, callback) {
  wx.getStorage({
    key: name,
    success: function (res) {
      obj.data[name] = res.data;
      obj.setData(obj.data);
      if (callback)
        callback();
    },
    fail: function (res) {
      obj.data[name] = defaultStatus;
      obj.setData(obj.data);
      if (callback)
        callback();
    },
  });
}

function addDate(interval, number, date) {
  switch (interval.toLowerCase()) {
    case "y":
      return new Date(date.setFullYear(date.getFullYear() + number));
    case "m":
      return new Date(date.setMonth(date.getMonth() + number));
    case "d":
      return new Date(date.setDate(date.getDate() + number));
    case "w":
      return new Date(date.setDate(date.getDate() + 7 * number));
    case "h":
      return new Date(date.setHours(date.getHours() + number));
    case "n":
      return new Date(date.setMinutes(date.getMinutes() + number));
    case "s":
      return new Date(date.setSeconds(date.getSeconds() + number));
    case "l":
      return new Date(date.setMilliseconds(date.getMilliseconds() + number));
  }
}

function diffDate(interval, date1, date2) {
  var long = date2.getTime() - date1.getTime(); //相差毫秒
  switch (interval.toLowerCase()) {
    case "y":
      return parseInt(date2.getFullYear() - date1.getFullYear());
    case "m":
      return parseInt((date2.getFullYear() - date1.getFullYear()) * 12 + (date2.getMonth() - date1.getMonth()));
    case "d":
      return parseInt(long / 1000 / 60 / 60 / 24);
    case "w":
      return parseInt(long / 1000 / 60 / 60 / 24 / 7);
    case "h":
      return parseInt(long / 1000 / 60 / 60);
    case "n":
      return parseInt(long / 1000 / 60);
    case "s":
      return parseInt(long / 1000);
    case "l":
      return parseInt(long);
  }
}


function ReplaceAllString(str, replaceStrFrom, replaceStrTo) {//替换
  if (str && str.length > 0) {
    var reg = new RegExp(replaceStrFrom, "g");
    //console.log(str);
    return str.toString().replace(reg, replaceStrTo);
  }
  else
    return str;
}


function Trim(str) { //删除左右两端的空格
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

module.exports = {
  formatTime: formatTime,
  formatDateCHS: formatDateCHS,
  getMinuteSecond: getMinuteSecond,
  random: Random,
  randomArray: RandomArray,
  unique: Unique,
  getEnumerationName: getEnumerationName,
  getStringMaxLength: getStringMaxLength,
  sort: sort,
  addZero: addZero,
  checkError: checkError,
  Encrypt: Encrypt,
  Decrypt: Decrypt,
  getEnumerationNameByDescription: getEnumerationNameByDescription,
  isExistStr: isExistStr,
  getStorageValue: getStorageValue,
  ReplaceAllString: ReplaceAllString,
  addDate: addDate,
  diffDate: diffDate,
  Trim: Trim,
  checkIsArray: checkIsArray,
  formatDateENG: formatDateENG,
}