/**************************
 *********公共方法**********
 **************************/

/**
 * 改变时间样式
 * 传参格式：Mon Jan 01 2018 00:00:00 GMT+0800 (中国标准时间)
 * 返回类型 2018-01-01
 */
export const getFormateDate = (time, fmt) => {
  if (Object.prototype.toString.call(time) !== '[object Date]') return
  let o = {
    'y+': time.getFullYear(),
    'M+': time.getMonth() + 1,
    'd+': time.getDate(),
    'h+': time.getHours(),
    'm+': time.getMinutes(),
    's+': time.getSeconds(),
    'q+': Math.floor((time.getMonth() + 3) / 3),
    'S': time.getMilliseconds()
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, o[k].toString().length === 1 ? ('0' + o[k]) : o[k])
    }
  }
  return fmt
}
// 获取时间间隔
export function addDateStr(startTime,AddDayCount) {   
  var dd = startTime;
  if (AddDayCount < 0) {
    dd.setDate(dd.getDate()-Math.abs(AddDayCount));//获取AddDayCount天后的日期
  } else {
    dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
  }
  var y = dd.getFullYear();   
  var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);//获取当前月份的日期，不足10补0
  var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();//获取当前几号，不足10补0
  return y+"-"+m+"-"+d;   
}
/// 数值加逗号
export function numFormat(num) {
  num = Number(num)
  var c = (num.toString().indexOf ('.') !== -1) ? num.toLocaleString() : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
  return c
}
//金额加逗号
export function AmountNumFormat(value) {
  if(!value) return '0.00'
  /*原来用的是Number(value).toFixed(0)，这样取整时有问题，例如0.51取整之后为1，感谢Nils指正*/
  /*后来改成了 Number(value)|0,但是输入超过十一位就为负数了，具体见评论 */
  var intPart = Math.trunc(value);
  var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); //将整数部分逢三一断
  var floatPart = ".00"; //预定义小数部分
  var value2Array = value.toString().split(".");
  //=2表示数据有小数位
  if(value2Array.length == 2) {
    floatPart = value2Array[1].toString(); //拿到小数部分

    if(floatPart.length == 1) { //补0,实际上用不着
      return intPartFormat + "." + floatPart + '0';
    } else {
      return intPartFormat + "." + floatPart;
    }

  } else {
    return intPartFormat + floatPart;
  }
}
//获取搜索结果数量,主要用于解析ERP返回的数量
export function getResListNum(value) {
  console.log(value)
  if(typeof value == null || value == '' || value == 'undefined'){
    console.log("wewewe")
    return 0
  } else {
    console.log(value.split('-'))
    return value.split('-')[1]
  }
}

// 根据汉字拼音排序的列表
export function pySegSort(data, str) {
  if (data.length == 0) return
  if (!String.prototype.localeCompare) return null
  var letters = '*ABCDEFGHJKLMNOPQRSTWXYZ'.split('')
  var zh = '阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀'.split('')
  var segs = [] // 存放数据
  var res = {}
  let curr
  var re = /[^\u4e00-\u9fa5]/
  var pattern = new RegExp("[`\\-~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？12345678990]")

  letters.filter((items, i) => {
    curr = {
      initial: '',
      data: []
    };
    data.map((v, index) => {
      // 特殊字符
      if (pattern.test(v[str][0])) {
        if ((!zh[i - 1] || zh[i - 1].localeCompare(v[str]) <= 0) && v[str].localeCompare(zh[i]) == -1) {
          curr.data.push(v)
        }
      }
      // 判断首个字是否是中文
      if (re.test(v[str][0])) {
        // 英文
        if (v[str][0].toUpperCase() == items) {
          curr.data.push(v)
        }
      } else {
        // 中文
        if ((!zh[i - 1] || zh[i - 1].localeCompare(v[str]) <= 0) && v[str].localeCompare(zh[i]) == -1) {
          curr.data.push(v)
        }
      }

    })
    if (curr.data.length) {
      curr.initial = letters[i]
      segs.push(curr);
      curr.data.sort((a, b) => {
        return a[str].localeCompare(b[str])
      });
    }
  })
  res.segs = Array.from(new Set(segs))
  return res
}
// 老版本 通过连接地址拼接获取参数
export function GetQueryString(name) {
  let urlArr = window.location.href.split('?')
  if (urlArr.length < 2) {
    return ''
  }
  let tempArr = urlArr[1].split('&')
  for (let i = 0; i < tempArr.length; i++) {
    let item = tempArr[i].split('=')
    if (item[0].trim() == name) {
      return decodeURI(item[1])
    }
  }
  return ''
}
/// 原生与web端的加解密
// export function GetQueryString(name) {
//   let str = getCookie('info')
//   // let str = 'uwE2rTgpaI2VGD0gIdlmHOV4y+3LRAFsONGnGAHaK4CAEOathh0vV0YPw+nFRPij0gh46CSOW8BcAxLn9BX38HSEZ0zSQ8/qBoi3jo0NRu0b8FeLI2KcMxa5etZIg/xGpXdU3qi+JQtVgoP2TI9+k3tjMk0dirPWovNmuu7f4heUXEo4ln+A7mZk04jxzwT82WIjxoVhSl6xYvGgv0OldvgHBqpfx2QezgwMjGgruyW87ozJRn9xiweOe4KBJAJ58FIHAixgWX03MmpzU0xhR6VT/YRP0tf8OEpJ/FU3aGVai329xN5Q/prYPWYAN1EE5iFpC+6XEdoi7ZkyQnz4bQbaUSswYHGUdbvNvStPTo+AISll549LHQbaEmSHX5uMZW9VE8KpX90G977WrTKFiGVWw8vciOEzJCLPon3SiaBWXlmPnRs5uASK0CD6vw3W5GXokCXWeQvjOvz1689UKs71uRwpwH4XGs8FADJlwL5LV/dpyKAcs7AEyZWlSnojeBptSf7y+hLHPf67li8nFqXjlewTmoakcMJU1e0n/jHCbc4vOIPzacWMCU2WZgGuGN7qLlQjvkaZ5OkmwN6Mr0p96gCdXR/5J1H8X0h1zi6ZR+9WqiP10iJoH+yc0uFR6Ca61kmwDoIWwY5xiIMoFtYW+gl8nkVdqVH9naWK7PbN964YqNiV1tEC/Pxl3Z8+FN8duy2Uj8Nk79bS3RRWkxCl1oHhpWvrUdwJcsawziM='
//   console.log(Decrypt(str))
//   let tempArr = Decrypt(str).split('&')
//   for (let i = 0; i < tempArr.length; i++) {
//     let item = tempArr[i].split('=')
//     if (item[0].trim() == name) {
//       return item[1]
//     }
//   }
//   return ''
// }
/// 解密
export function Decrypt(str) {
  // let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  // let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  let decrypt = CryptoJS.AES.decrypt(str, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}
/// 加密
export function AES_CBC_encrypt(word) {
  let srcs = CryptoJS.enc.Utf8.parse(word);
    let encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
    return encrypted.ciphertext.toString().toUpperCase();
}
 //设置cookie
 export function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = 'expires=' + d.toUTCString();
  console.info(cname + '=' + cvalue + "; " + expires);
  document.cookie = cname + '=' + cvalue + "; " + expires;
}
//获取cookie
export function getCookie(cname) {
  var name = cname + '=';
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == '') c = c.substring(1);
    if (c.indexOf(name) != -1){
      return c.substring(name.length, c.length);
    }
  }
  return '';
}
import CryptoJS from 'crypto-js'
const key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF"); //十六位十六进制数作为秘钥
const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412'); //十六位十六进制数作为秘钥偏移量