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


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 formatDateCHS(date) {
  date = date.toString();
  var year = date.substr(0, 4);
  var month = date.substr(5, 2);
  var day = date.substr(8, 2);

  return year + "年" + month + "月" + day + "日";
}


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) {
  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);
  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.showToast({
        title: '网络故障，请稍候再试！',
        duration: 3000
      });
      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 getSystemHeight() {
  var systemInfo = wx.getSystemInfoSync();
  var height = systemInfo.windowHeight;
  if (systemInfo.model) {
    if (height == 603 && systemInfo.model.indexOf("Plus") > 0) {
      height = 625;
    }
    else if (height == 504 && (
      systemInfo.model.indexOf("iPhone 6<") >= 0
      || systemInfo.model.indexOf("iPhone 7<") >= 0
      || systemInfo.model.indexOf("iPhone 6s<") >= 0
      || systemInfo.model.indexOf("iPhone 5") >= 0
      || systemInfo.model.indexOf("iPhone SE") >= 0
    )) {
      height = 596;
    }
  }

  height = height * 2;
  if (systemInfo.system && systemInfo.system.indexOf("Android") >= 0) {
    height = height + 168;
  }
  return height;
}

//获取存储数据，若不存在，则获得缺省值。
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();
    },
  });
}

//var arr=getWordArray("cakeface","a e");
//console.log(arr);
function getWordArray(word, key) {
  var result = [];
  word = word.toLowerCase();
  if (key.length == 1) {
    var number1 = word.indexOf(key);
    result.push({ css: "", name: word.substr(0, number1) });
    result.push({ css: "highlight", name: key });
    result.push({ css: "", name: word.substr(number1 + 1) });
  }
  else {
    if (key.indexOf(" ") >= 0) {
      var arrKey = key.split(" ");
      var number2 = word.lastIndexOf(arrKey[1]);
      var number1 = word.lastIndexOf(arrKey[0], number2 - 2);
      //console.log("number1:" + number1);
      //console.log("number2:" + number2);

      if (number1 + 2 != number2) {
        number1 = word.indexOf(arrKey[0], number1 + 1);
        number2 = word.indexOf(arrKey[1], number1 + 1);
      }
      result.push({ css: "", name: word.substr(0, number1) });
      result.push({ css: "highlight", name: arrKey[0] });
      result.push({ css: "", name: word.substr(number1 + 1, 1) });
      result.push({ css: "highlight", name: arrKey[1] });
      result.push({ css: "", name: word.substr(number2 + 1) });
    }
    else {
      var number1 = word.indexOf(key);
      var number2 = number1 + key.length;
      result.push({ css: "", name: word.substr(0, number1) });
      result.push({ css: "highlight", name: key });
      result.push({ css: "", name: word.substr(number2) });
    }

  }
  return result;
}

//var arrTemp=["test","a","bdt","bca"];
//console.log(sortArrayByStringLength(arrTemp));

//排序数组根据字符串长度
function sortArrayByStringLength(arr) {
  var result = [], temp = [];
  for (var i = 0; i < 30; i++) {
    temp.push([]);
  }
  for (var i = 0; i < arr.length; i++) {
    var item = arr[i];
    temp[item.length].push(item);
  }
  for (var i = 0; i < temp.length; i++) {
    temp[i].sort();
    for (var j = 0; j < temp[i].length; j++) {
      result.push(temp[i][j]);
    }
  }
  return result;
}

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 isChinese(temp) {
  var reg = /^[\u4e00-\u9fa5]|[\uFE30-\uFFA0]+$/;   /*定义验证表达式*/
    return reg.test(temp);     /*进行验证*/
}

function FormatMoney(money) {
  var result;
  if (money == 0)
    result = "0.00";
  else {
    result = (Math.round(money) / 100).toString();
    //console.log("1:"+result);
    if (result.indexOf(".") >= 0) {
      if (result.substr(result.indexOf(".")).length < 3)
        result += "0";
    }
    else {
      result += ".00";
    }
  }

  return result;
}

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,
  getSystemHeight: getSystemHeight,
  getStorageValue: getStorageValue,
  getWordArray: getWordArray,
  sortArrayByStringLength: sortArrayByStringLength,
  ReplaceAllString: ReplaceAllString,
  IsChinese: isChinese,
  FormatMoney: FormatMoney,
}