import moment from 'moment';
import {checkIsExistsEffectBayzgz, getPerAuthRecordbyId} from '../services/api';
export function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

export function getTimeDistance(type) {
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }

  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);

    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }

    const beginTime = now.getTime() - day * oneDay;

    return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
  }

  if (type === 'month') {
    const year = now.getFullYear();
    const month = now.getMonth();
    const nextDate = moment(now).add(1, 'months');
    const nextYear = nextDate.year();
    const nextMonth = nextDate.month();

    return [
      moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
      moment(
        moment(
          `${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`
        ).valueOf() - 1000
      )
    ];
  }

  if (type === 'year') {
    const year = now.getFullYear();

    return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
  }
}

/**
 * 去掉前后 空格/空行/tab 的正则 预先定义 避免在函数中重复构造
 * @type {RegExp}
 */
const trimReg = /(^\s*)|(\s*$)/g;

/**
 * 判断一个东西是不是空 空格 空字符串 undefined 长度为0的数组及对象会被认为是空的
 * @param key
 * @returns {boolean}
 */
export function isEmpty (key) {
  if (key === undefined || key === '' || key === null) {
      return true;
  }
  if (typeof (key) === 'string') {
      key = key.replace(trimReg, '');
      if (key == '' || key == null || key == 'null' || key == undefined || key == 'undefined') {
          return true;
      } else{
          return false;
      }
  } else if (typeof (key) === 'undefined') {
      return true;
  } else if (typeof (key) === 'object') {
      for (let i in key) {
          return false;
      }
      return true;
  } else if (typeof (key) === 'boolean') {
      return false;
  }
}

export function getPlainNode(nodeList, parentPath = '') {
  const arr = [];
  nodeList.forEach(node => {
    const item = node;
    item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
    item.exact = true;
    if (item.children && !item.component) {
      arr.push(...getPlainNode(item.children, item.path));
    } else {
      if (item.children && item.component) {
        item.exact = false;
      }
      arr.push(item);
    }
  });
  return arr;
}

export function digitUppercase(n) {
  const fraction = ['角', '分'];
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
  let num = Math.abs(n);
  let s = '';
  fraction.forEach((item, index) => {
    s += (digit[Math.floor(num * 10 * 10 ** index) % 10] + item).replace(
      /零./,
      ''
    );
  });
  s = s || '整';
  num = Math.floor(num);
  for (let i = 0; i < unit[0].length && num > 0; i += 1) {
    let p = '';
    for (let j = 0; j < unit[1].length && num > 0; j += 1) {
      p = digit[num % 10] + unit[1][j] + p;
      num = Math.floor(num / 10);
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
  }

  return s
    .replace(/(零.)*零元/, '元')
    .replace(/(零.)+/g, '零')
    .replace(/^整$/, '零元整');
}

//查询参数
export function gup(name, url) {
  if (!url) url = location.href;
  url = decodeURIComponent(url);
  name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  const regexS = '[\\?&]' + name + '=([^&#]*)';
  const regex = new RegExp(regexS);
  const results = regex.exec(url);
  return results == null ? null : results[1];
}

/**
 * 计算日期年月日
 * @date RangePicker值 修改计算规则，day全部加上1
 */
export function getDateInterval(date) {
  const startminTime = new Date(date[0]['_d']).getTime();
  const endminTime = new Date(date[1]['_d']).getTime();

  const currentStartYear = moment(startminTime).format('YYYY');
  const currentEndYear = moment(endminTime).format('YYYY');
  const currentStartMonth = moment(startminTime).format('MM');
  const currentEndMonth = moment(endminTime).format('MM');
  const currentStartDay = moment(startminTime).format('DD');
  const currentEndDay = moment(endminTime).format('DD');

  let year;
  let month;
  let day;
  if (currentEndYear >= currentStartYear) {
    if (currentEndMonth > currentStartMonth) {
      year = currentEndYear - currentStartYear;
      if (currentEndDay >= currentStartDay) {
        month = currentEndMonth - currentStartMonth;
        day = currentEndDay - currentStartDay + 1;
      } else {
        month = currentEndMonth - currentStartMonth - 1;
        day = currentEndDay - currentStartDay + 31;
      }
    } else if (currentEndMonth === currentStartMonth) {
      if (currentEndDay >= currentStartDay) {
        year = currentEndYear - currentStartYear;
        month = currentEndMonth - currentStartMonth;
        day = currentEndDay - currentStartDay + 1;
      } else {
        year = currentEndYear - currentStartYear - 1;
        month = currentEndMonth - currentStartMonth + 11;
        day = currentEndDay - currentStartDay + 31;
      }
    } else {
      year = currentEndYear - currentStartYear - 1;
      if (currentEndDay >= currentStartDay) {
        month = currentEndMonth - currentStartMonth + 12;
        day = currentEndDay - currentStartDay + 1;
      } else {
        month = currentEndMonth - currentStartMonth + 12 - 1;
        day = currentEndDay - currentStartDay + 31;
      }
    }
  }
  let timeLimit;
  if (year === 0) {
    if (month === 0) {
      timeLimit = day + '天';
      if (day === 0) {
        timeLimit = '';
      }
    } else {
      timeLimit = month + '月' + day + '天';
    }
  } else {
    timeLimit = year + '年' + month + '月' + day + '天';
  }

  if (month === 11 && day === 30) {
    year += 1;
    month = 0;
    day = 0;
    timeLimit = year + '年' + month + '月' + day + '天';
  }
  return timeLimit;
}

/**
 * 遍历部门人员数据 用于处理get-treeper-bydepart接口返回数据
 * @date treeDate
 */
export function checkMember(data) {
  data = data.map(item => {
    if (item.children && item.children.length) {
      let needDisable = true;
      const temp = subItem => {
        subItem.filter(tempItem => {
          if (tempItem.children && tempItem.children.length) {
            temp(tempItem.children);
            return tempItem;
          } else {
            if (tempItem.treeType === '2') {
              needDisable = false;
            }
            return tempItem;
          }
        });
      };
      temp(item.children);
      needDisable ? (item.disableCheckbox = true) : null;
      checkMember(item.children);
      return item;
    } else {
      if (item.treeType !== '2') {
        item.disableCheckbox = true;
        item.disabled = true;
        item.isLeaf = true;
      }
      return item;
    }
  });

  return data;
}

/**
 * 生成一个用不重复的ID
 */
export function GenNonDuplicateID(randomLength) {
  return Number(
    Math.random()
      .toString()
      .substr(3, randomLength) + Date.now()
  ).toString(36);
}

/**
 * 获取当前时间，并格式化为：yyyy-MM-dd HH:mm:ss
 */
export function getFormatDate(substr = true) {
  const date = new Date();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  let currentDate;
  if (substr) {
    currentDate = date.getFullYear() + "-" + month + "-" + strDate
      + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
  } else {
    currentDate = date.getFullYear() + "-" + month + "-" + strDate;
  }
  return currentDate;
}


/**
 * iverry
 * 日志打印
 */
export const log = (value, key='remack', color1 = 'orange', color2 = '#1890ff') => {
  if (typeof key == 'object') {
    key = JSON.stringify(key);
  }
  if (typeof value == 'object') {
    value = JSON.stringify(value);
  }
  if (!key) {
    key = '这是一个测试日志';
  }
  // console.log(
  //   `%c ${value} %c ${key}\n`,
  //   `color:#fff;padding:1px;border-radius:3px 0 0 3px; background-color: ${color1};`,
  //   `border-radius: 0 3px 2px 0;border: 1px solid ${color2};color: ${color2};`
  // );
};
export const $log = (value,  remack = 'test', color = 'orange', color2 = 'blue') => {
  if (typeof value == 'object') {
    value = JSON.stringify(value);
  }
  // console.log(
  //   `%c ${value}\n %c ${remack}\n`,
  //   `color:#fff;padding:1px 3px;border-radius:3px 0 0 3px; background-color: ${color};`,
  //   `border-radius: 0 3px 2px 0;border: 1px solid ${color2};color: ${color2};`
  // );
};

/**
 * 返回年月日
 * @export
 * @param {Date} date
 * @param {string} [splitor='-']
 * @returns
 */
export function getDate(date, splitor = '-') {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}${splitor}${addZeroPrefix(month)}${splitor}${day}`
}

/**
 * 返回时分秒/时分
 * @export
 * @param {*} date
 * @param {boolean} [withSecond=false]
 * @returns
 */
export function getTime(date, withSecond = false) {
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return withSecond ? `${addZeroPrefix(hour)}:${addZeroPrefix(minute)}:${addZeroPrefix(second)}` : `${hour}:${addZeroPrefix(minute)}`
}

export function getFullDate(date) {
  return `${getDate(date)} ${getTime(date)}`
}

export function isToday(date) {
  return date.toDateString() === new Date().toDateString()
}
/**
 * 个位数，加0前缀
 * @param {*} number
 * @returns
 */
function addZeroPrefix(number) {
  return number < 10 ? `0${number}` : number
}


/**
根据身份证号码判断性别
15位身份证号码：第7、8位为出生年份(两位数)，第9、10位为出生月份，第11、12位代表出生日
18位身份证号码：第7、8、9、10位为出生年份(四位数)，第11、第12位为出生月份，
第13、14位代表出生日期，第17位代表性别，奇数为男，偶数为女。
*/
//根据身份证号获取年龄
export function getAge(identityCard) {
  var len = (identityCard + "").length;
  var strBirthday = "";
  if (len == 18)//处理18位的身份证号码从号码中得到生日和性别代码
  {
    strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
  }
  if (len == 15) {
    var birthdayValue = '';
    birthdayValue = identityCard.charAt(6) + identityCard.charAt(7);
    if (parseInt(birthdayValue) < 10) {
      strBirthday = "20" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
    } else {
      strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
    }

  }
  //时间字符串里，必须是“/”
  var birthDate = new Date(strBirthday);
  var nowDateTime = new Date();
  var age = nowDateTime.getFullYear() - birthDate.getFullYear();
  //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
  if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}

// 通过身份证校验人员年龄在对应的省份是否符合要求
export function checkAage(idCardNo, regProvince) {
  const result = {
    status: '-1',
    text: ''
  };
  const age = getAge(idCardNo);
  if(age<0) {
    return {
      status: '-2',
      text: '该人未出生'
    };
  }
  // 北京、新疆、陕西、宁夏
  if (
    /(^11)|(^65)|(^64)|(^61)/.test(regProvince) &&  //判断省份(北京、新疆、陕西、宁夏判断年龄)
    (age < 18 || age > 60)
  ) {
    result.text = '所属地区进行保安员资格证报名人员年龄限制在18~60岁（含），该人员不在范围内。';
  }else if (
    /^45/.test(regProvince) &&  //判断省份(广西判断年龄)
    (age < 18 || age > 65)
  ) { // 广西
    result.text = '所属地区进行保安员资格证报名人员年龄限制在18~65岁（含），该人员不在范围内。';
  }else if (
    !/(^11)|(^65)|(^64)|(^61)|(^45)/.test(regProvince)
    &&
    (age < 18)
  ) { // 其他
    result.text = '所属地区进行保安员资格证报名人员年龄限制在18岁（含）以上，该人员不在范围内。';
  }else {
    result.status = '0';
  }
  return result;
}

// 资格证报名校验人员是否可以报名
export async function checkPerCanSignUp(perId, regProvince) {
  const existRes = await checkIsExistsEffectBayzgz({ perId });
  // 1:代表存在保安员资格证，不能报名，0代表不存在可以报名
  if (existRes.data != '0') {
    return {
      status: '-1',
      text: '该人员已存在保安员资格证，无法报名。'
    };
  }
  // 获取人员身份验证信息
  const authRes = await getPerAuthRecordbyId({ perId });
  const { idCardNo, authStatus } = authRes.data;
  const ageRes = checkAage(idCardNo, regProvince);
  if(ageRes.status != '0') {
    return ageRes;
  }
  if (authStatus != 1) {
    return {
      status: '-1',
      text: '该人员尚未完成实名认证，无法报名。需通过实名认证，才可进行报名。'
    };
  }
  // 验证通过
  return {
    status: '0',
    text: ''
  };
}

/*
格式化数据，小数部分不做处理，对整数部分进行千分位格式化的处理，如果有符号，正常保留
*/
export function formatCurrency(num){
  if(num){
      //将num中的$,去掉，将num变成一个纯粹的数据格式字符串
      num = num.toString().replace(/\$|\,/g,'');
      //如果num不是数字，则将num置0，并返回
      if(''==num || isNaN(num)){return 'Not a Number ! ';}
      //如果num是负数，则获取她的符号
      var sign = num.indexOf("-")> 0 ? '-' : '';
      //如果存在小数点，则获取数字的小数部分
      var cents = num.indexOf(".")> 0 ? num.substr(num.indexOf(".")) : '';
      cents = cents.length>1 ? cents : '' ;//注意：这里如果是使用change方法不断的调用，小数是输入不了的
      //获取数字的整数数部分
      num = num.indexOf(".")>0 ? num.substring(0,(num.indexOf("."))) : num ;
      //如果没有小数点，整数部分不能以0开头
      if('' == cents){ if(num.length>1 && '0' == num.substr(0,1)){return 'Not a Number ! ';}}
      //如果有小数点，且整数的部分的长度大于1，则整数部分不能以0开头
      else{if(num.length>1 && '0' == num.substr(0,1)){return 'Not a Number ! ';}}
      //针对整数部分进行格式化处理，这是此方法的核心，也是稍难理解的一个地方，逆向的来思考或者采用简单的事例来实现就容易多了
      /*
        也可以这样想象，现在有一串数字字符串在你面前，如果让你给他家千分位的逗号的话，你是怎么来思考和操作的?
        字符串长度为0/1/2/3时都不用添加
        字符串长度大于3的时候，从右往左数，有三位字符就加一个逗号，然后继续往前数，直到不到往前数少于三位字符为止
       */
      for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
      {
          num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
      }
      //将数据（符号、整数部分、小数部分）整体组合返回
      return (sign + num + cents);
  }
  else{
    return null
  }
}

 //时间+8小时(华为云会议中用到的UTC时间)
export function addUTC(time, action) {
  const offset = 8 * 60 * 60 * 1000;
  time = new Date(Date.parse(time));
  time = time.getTime();
  if (action == 'add') {
    time = time + offset;
  } else {
    time = time - offset;
  }
  let newDate = new Date(parseInt(time))
  let month = parseInt(newDate.getMonth()) + 1
  const getMinutes = newDate.getMinutes() === 0 ? '00' : newDate.getMinutes()
  const startTime =
    newDate.getFullYear() +
    "-" +
    month +
    "-" +
    newDate.getDate() +
    " " +
    newDate.getHours() +
    ":" +
    // newDate.getMinutes()
    getMinutes
  return startTime
}

/**解决减法里精度缺失问题
 * 方法：先变整，在做运算，在除
 * */
export function solveLackAccuracy(num1,num2){
  let num1Length =0;
  let num2Length = 0;
  if(num1.toString().split(".")[1]){
    num1Length = num1.toString().split(".")[1].length
  }
  if(num2.toString().split(".")[1]){
    num2Length = num2.toString().split(".")[1].length
  }
  if(num1Length>0||num2Length>0){
    let length = num1Length
    if(num2Length>num1Length){
      length=num2Length
    }
    num1=num1*Math.pow(10,length)
    num2=num2*Math.pow(10,length)
    let num = num1-num2
    return num/Math.pow(10,length)
  }else{
    return num1-num2
  }
}

//时间戳为10位需*1000，时间戳为13位的话不需乘1000
//返回年-月-日 时：分：秒
export function timestamp(timestamp){
  var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
  var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
  var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
  var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
  return Y + M + D + h + m + s;
}

//js将2021-08-21T10:00:18.000+00:00转换成年月日时分秒
export function transformTimestamp (timestamp) {
  const date=new Date(timestamp)
  const Y = date.getFullYear() + '-';
  const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())+ ':';
  const s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()); // 秒
  const dateString = Y + M + D + h + m+s;
  return dateString;
}
