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

function formatTime(date, format, isShort) {
  if (!date) return "";
  
  let dateObj;
  if (date instanceof Date) {
    dateObj = date;
  } else {
    // 统一处理日期字符串格式
    let dateStr = date.toString();
    
    // 处理包含GMT的格式
    if (dateStr.includes('GMT')) {
      // 提取日期部分，转换为 yyyy/MM/dd HH:mm:ss 格式
      let parts = dateStr.match(/(\w+)\s+(\w+)\s+(\d+)\s+(\d+)\s+(\d+):(\d+):(\d+)/);
      if (parts) {
        let months = {'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,
                     'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12};
        let month = months[parts[2]];
        dateStr = `${parts[4]}/${formatNumber(month)}/${formatNumber(parts[3])} ${parts[5]}:${parts[6]}:${parts[7]}`;
      }
    }
    
    // 统一将-转换为/
    dateStr = dateStr.replace(/-/g, '/');
    
    // 确保日期格式为 yyyy/MM/dd HH:mm:ss
    if (!/^\d{4}\/\d{1,2}\/\d{1,2}/.test(dateStr)) {
      return "";
    }
    
    dateObj = new Date(dateStr);
  }

  // 检查日期是否有效
  if (isNaN(dateObj.getTime())) {
    return "";
  }

  var year = dateObj.getFullYear();
  var month = dateObj.getMonth() + 1;
  var day = dateObj.getDate();
  var hour = dateObj.getHours();
  var minute = dateObj.getMinutes();
  var second = dateObj.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(':');
  }
}

function formatDateCHS(date,isLong) {
  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 "";
    if (isLong)
      return year + "年" + month + "月" + day + "日" +date.substr(10);
    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) {
  const newDate = new Date(date);
  
  switch (interval.toLowerCase()) {
    case "y":
      newDate.setFullYear(newDate.getFullYear() + number);
      break;
    case "m":
      newDate.setMonth(newDate.getMonth() + number);
      break;
    case "d":
      newDate.setDate(newDate.getDate() + number);
      break;
    case "w":
      newDate.setDate(newDate.getDate() + 7 * number);
      break;
    case "h":
      newDate.setHours(newDate.getHours() + number);
      break;
    case "n":
      newDate.setMinutes(newDate.getMinutes() + number);
      break;
    case "s":
      newDate.setSeconds(newDate.getSeconds() + number);
      break;
    case "l":
      newDate.setMilliseconds(newDate.getMilliseconds() + number);
      break;
    default:
      throw new Error(`不支持的间隔类型: ${interval}`);
  }
  
  return newDate;
}


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);
  }
}

/**
 * 替换字符串中的所有匹配项
 * @param {string} str - 需要替换的字符串
 * @param {string} replaceStrFrom - 需要被替换的子字符串
 * @param {string} replaceStrTo - 替换后的子字符串
 * @returns {string} 替换后的字符串
 */
function ReplaceAllString(str, replaceStrFrom, replaceStrTo) {
  if (typeof str === 'string' && typeof replaceStrFrom === 'string' && typeof replaceStrTo === 'string' && str.length > 0) {
    const reg = new RegExp(replaceStrFrom, 'g');
    return str.replace(reg, replaceStrTo);
  }
  return str;
}



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

function IsNumber(value) {//判断是否是数字，true：是，false：不是
  return !isNaN(value);
}

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

  }
  return result;
}

function initMonthCalendar(dates, line = 6,isNull=true) {
  //console.log(dates); 
  //dates="2022-07-19";
  var date = new Date(dates);                          // 初始时间格式
   
   var y = date.getFullYear();
   var m = date.getMonth();
   var days = new Date(y, m+1, 0).getDate();          // 获取这个月共有多少天
   var firstDayWeek = new Date(y, m, 1).getDay();       // 月份第一天星期几
 
   firstDayWeek--
   if (firstDayWeek==-1)
    firstDayWeek=6;
   //console.log("firstDayWeek："+firstDayWeek); 
   var arr = [];     // 存储日历格式的数组
   var n = [];       // 日历格式中的一行
   var d = 1;        // 日历格式中的天数
 
   // 先根据这个月第一天排星期几
   // 把上个月剩下几天留在这个月的'奸细'放在最前头
   for(let i = 0; i < firstDayWeek; i++) {
     if(isNull)
        n.unshift("");
     else
        n.unshift(new Date(y, m, 0 - i).getDate());
   }
 
   // 开启循环
   // 一星期占一行，一行一个外循环
   // 这里我默认想要6行
   for (let j = 0; j < line; j++) {
     // 一天占一个格子，最多一星期7个格子
     // 这里我想要7个格子
     for (let i = 0; i < 7; i++) {
       if(d > days) {
         // 这个月都放完了，该放什么？
         // new Date(2020, 8, 31)  --> 9月没有31 === 10月1
          if (isNull){
            //n.push("");
          }
          else
            n.push(new Date(y, m, d++).getDate());
          
       } else {
         // 放置这个月的天数
 　　　　　　 n.push(d++);
       } 
       if (n.length == 7) break;    // 放了7个格子该结束了
     }
     //arr.push(n);
     //n = [];           // 这一行放完了，清空ba
   }
   return n;
}

/**
 * 过滤数组中单词的特殊字符
 * @param {Array} words - 需要过滤的单词数组
 * @returns {Array} 返回处理后的数组，只包含字母、单引号、连字符和空格
 * @example
 * filterWordsWithSpecialChars(["hello!", "world@123"]) // 返回 ["hello", "world"]
 */
function filterWordsWithSpecialChars(words) {
  if (!Array.isArray(words)) {
    return [];
  }
  
  return words.map(word => {
    if (!word) return '';
    // 只保留大小写字母、单引号、连字符和空格
    return word.toString().replace(/[^a-zA-Z''\- ]/g, '');
  });
}

/**
 * 字符串数组去重并去除每个字符串的前后空格
 * @param {string[]} arr - 输入的字符串数组
 * @returns {string[]} 去重并去除前后空格后的数组
 */
function removeDuplicateAndTrimStrings(arr) {
  if (!Array.isArray(arr)) {
      return [];
  }
  
  // 先对每个字符串进行trim处理，然后使用Set去重
  return [...new Set(arr.map(str => str ? str.trim() : ''))];
}

/**
 * 使用多个分隔符分割字符串
 * @param {string} str - 要分割的原始字符串
 * @param {string[]} delimiters - 分隔符数组
 * @returns {string[]} 分割后的字符串数组
 */
function splitByMultipleDelimiters(str, delimiters) {
  if (!str || !delimiters || delimiters.length === 0) {
    return [str];
  }

  // 创建正则表达式，转义特殊字符
  const escapedDelimiters = delimiters.map(d => 
    d.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  );
  
  // 构建正则表达式模式
  const pattern = new RegExp(`(${escapedDelimiters.join('|')})`);
  
  // 执行分割
  const parts = str.split(pattern);
  
  // 过滤掉分隔符本身
  return parts.filter(part => !delimiters.includes(part));
}


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,
  IsNumber:IsNumber,
  formatDateENG: formatDateENG,
  formatMoney:formatMoney,
  initMonthCalendar:initMonthCalendar,
  filterWordsWithSpecialChars:filterWordsWithSpecialChars,
  removeDuplicateAndTrimStrings:removeDuplicateAndTrimStrings,
  splitByMultipleDelimiters:splitByMultipleDelimiters,
}