/***
 * 一站式正在使用此文件
 * 请谨慎使用
 * */
import React from 'react';
import moment from 'moment';
import { Icon, message, notification } from 'antd';
import { getOneStopActiveMenus, getOnestopKey } from '../../Services';
import { isJSON } from '@/webPublic/one_stop_public/2022beidianke/isJSON';
let messageTime = new Date().getTime() - 3000;
export { isJSON };
/**
 * 校验 开始时间必须在结束时间之前的函数
 * */
export function checkDate(endTime = '2019-01-01', startTime = '2018-12-31') {
  return moment(endTime)
    .isAfter(moment(startTime));
}

/**
 * 去除字符串中的所有html 标签
 * */
export function matchReg(str) {
  let reg = /<\/?.+?\/?>/g;
  return str.replace(reg, '')
    .replace(/&nbsp;/g, ' ');
}

export function htmlFormat(str) {
  if (typeof str !== 'string') {
    return '';
  }
  const newTxt = str.replace(/\s+([^<>]+)(?=<)/g, function (match) {
    return match.replace(/\s/g, '&nbsp;');
  });
  return newTxt;
}

export function countSpecialField(filedSpanBig, nameSpanBig) {
  let style = {};
  if (document.body.clientWidth > 1400) {
    if (filedSpanBig === 5) {
      // 当设置一行排列5个字段时 自定义宽度为20%
      style = { width: '20%' };
    }
    if (filedSpanBig === 1 && nameSpanBig === 2) {
      // 当一行显示一个字段 然后名字又特别长时 使用这个width
      style = { width: '6%' };
    }
  }
  return style;
}

/**
 * 深拷贝函数
 * */
export function deepCopy(obj, parent = null) {
  if (React.isValidElement(obj)) {
    return React.cloneElement(obj);
  }
  if (moment.isMoment(obj)) {
    return obj.clone(obj);
  }
  if (['boolean', 'string', 'number'].indexOf(typeof obj) > -1 || !obj) {
    return obj;
  }
  let result;
  if (obj.constructor === Array) {
    result = [];
  } else {
    result = {};
  }
  let keys = Object.keys(obj),
    key = null,
    temp = null,
    _parent = parent;
  // 该字段有父级则需要追溯该字段的父级
  while (_parent) {
    // 如果该字段引用了它的父级则为循环引用
    if (_parent.originalParent === obj) {
      // 循环引用直接返回同级的新对象
      return _parent.currentParent;
    }
    _parent = _parent.parent;
  }
  for (let i = 0; i < keys.length; i++) {
    key = keys[i];
    temp = obj[key];
    // 如果字段的值也是一个对象
    if (temp && typeof temp === 'object') {
      // 递归执行深拷贝 将同级的待拷贝对象与新对象传递给 parent 方便追溯循环引用
      result[key] = deepCopy(temp, {
        originalParent: obj,
        currentParent: result,
        parent: parent,
      });
    } else {
      result[key] = temp;
    }
  }
  return result;
}

/**
 * 获取表单元素中每个元素的值,
 * @param type
 * @param e
 * @param other
 * @returns {*|boolean}
 */
export function getFormElemValue(type, e, other) {
  let value = e;

  switch (type) {
    case 'input':
      value = e.target.value;
      break;
    case 'checkbox':
      value = e.target.checked;
      break;
    case 'textarea':
      value = e.target.value;
      break;
    case 'buttonUpload':
      value = e.url;
      break;
    case 'upload':
      value = Array.isArray(e) ? e.join(',') : '';
      break;
    default:
      break;
  }

  return value;
}

/**
 * 生成随机字符串
 * */
export function randomStr() {
  return Math.random()
    .toString(36)
    .substr(2);
}



export function checkMustHaveValue(configFileds, data) {
  for (let item of configFileds) {
    if (!data[item.key] && data[item.key] !== false && data[item.key] !== 0) {
      return false;
    }
  }
  return true;
}

export function mustHaveValue(configFields, data) {
  for (let item of configFields) {
    if (!item.required) continue;
    if (Array.isArray(data[item.key]) && data[item.key].length < 1) {
      message.warning(`${item.name}是必填项请填写`);
      return false;
    }
    if (!data[item.key] && data[item.key] !== false && data[item.key] !== 0) {
      message.warning(`${item.name}是必填项请填写`);
      return false;
    }
  }
  return true;
}

/**
 * 判断数组中是否有重复元素
 * 通过数组排序，比较临近元素
 * */
export function isRepeat(ary) {
  if (ary.length <= 1) {
    return false;
  }
  let nary = ary.sort();
  for (let i = 0; i < ary.length - 1; i++) {
    if (nary[i] === nary[i + 1]) {
      return nary[i];
      // alert("数组重复内容：" + nary[i]);
    }
  }
  return false;
}

export function displayRender(label) {
  if (label && label.length) {
    return label[label.length - 1];
  } else {
    return '';
  }
}

export function isEmptyValue(value) {
  return typeof value === 'undefined' || value === null || value === '';
}

// 全局的通知消息组件
export function controlNotification(props) {
  const nowTime = new Date().getTime();
  if (nowTime - messageTime < 3000) {
    return;
  }
  messageTime = nowTime;
  notification.info({
    ...props,
    icon: <Icon type="info-circle" style={{ color: '#fa8c16' }}/>,
  });
  return true;
}

export function setOneStopConfig(value) {
  if (typeof value !== 'string') {
    value = JSON.stringify(value);
  }
  localStorage.setItem('oneStopConfig', value);
}

export function getOneStopConfig(key) {
  let configList = localStorage.getItem('oneStopConfig');
  if (configList && isJSON(configList)) {
    let data = JSON.parse(configList);
    if (data && typeof data === 'object') {
      if (typeof data === 'undefined') {
        return '';
      }
      return data[key] || false;
    }
  } else {
    return getOnestopKey(key);
  }
}

export function setOneStopActiveMenusConfig(value) {
  window.oneStopActiveMenusConfig = value;
}

export function getOneStopActiveMenusConfig(key) {

  if (window.oneStopActiveMenusConfig && typeof window.oneStopActiveMenusConfig === 'object') {
    return window.oneStopActiveMenusConfig[key] || false;
  } else {
    return getOneStopActiveMenus(key);
  }
}


export function diGuiTree(treeData = [], i = 0) {
  // for (let item of treeData) {
  //   if(i === 2){
  //     item.selectable = true;
  //   }
  //   if (item.children && item.children.length) {
  //     i += 1;
  //     diGuiTree(item.children, i);
  //   }
  // }
  return treeData;
}


export { downloadFile } from './downloadFile';

// 校验密码是否符合 包含数字 字母 和特殊字符 解决 中医大的安全漏洞
export default function CheckPassWord(password = '', length = 12) {
  // console.log(password);
  if (!password || password.length < length) {
    // message.warning("密码过于简单, 请输入不小于8位的密码 且必须包含数字和字母!");
    // console.log('位数不够');
    return false;
  }
  let cRegex = new RegExp(/.*[\u4e00-\u9fa5]+.*$/);
  if (cRegex.test(password)) {
    message.warning('密码中不能包含中文字符！');
    return false;
  }

  let pwdRegex = new RegExp(`(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{${length},30}`);
  if (!pwdRegex.test(password)) {
    // alert("您的密码复杂度太低（密码中必须包含字母、数字、特殊字符），请及时修改密码！");
    return false;
  }
  return true;
}


/**
 *
 * 检查文本格式是否正确
 * */
export function checkInputType(data, type) {
  switch (type) {
    case 'phone':
      if (!(/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(data))) {
        message.warning('手机号码格式错误!');
        return false;
      }
      break;
    case 'email':
      if (!(/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(data))) {
        message.warning('邮箱格式错误!');
        return false;
      }
      break;
    case 'idCard':
      if (!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(data))) {
        message.warning('身份证号码格式错误!');
        return false;
      }
      break;
    default:
      break;
  }

  return true;
}


export { getHeaders } from './getHeaders';


export { getIsGui_Jian, getIsBei_Dian, getIsA_Ba } from './getSchoolType';


// (function (_0x49c6e2, _0x5afabe) {
//   const _0x125f6a = _0x3342,
//     _0x2c1408 = _0x49c6e2();
//   while (!![]) {
//     try {
//       const _0x53c0bd = -parseInt(_0x125f6a(0x190)) / 0x1 * (-parseInt(_0x125f6a(0x19b)) / 0x2) + parseInt(_0x125f6a(0x19c)) / 0x3 * (-parseInt(_0x125f6a(0x194)) / 0x4) + -parseInt(_0x125f6a(0x18e)) / 0x5 * (parseInt(_0x125f6a(0x18f)) / 0x6) + -parseInt(_0x125f6a(0x197)) / 0x7 * (-parseInt(_0x125f6a(0x191)) / 0x8) + -parseInt(_0x125f6a(0x19a)) / 0x9 + -parseInt(_0x125f6a(0x198)) / 0xa + parseInt(_0x125f6a(0x192)) / 0xb * (parseInt(_0x125f6a(0x19d)) / 0xc);
//       if (_0x53c0bd === _0x5afabe) break; else _0x2c1408['push'](_0x2c1408['shift']());
//     } catch (_0x47358a) {
//       _0x2c1408['push'](_0x2c1408['shift']());
//     }
//   }
// }(_0x1b15, 0x55be2));
//
// function _0x1b15() {
//   const _0x282d1 = ['serviceCurrentDate', 'bearer\x20', '1673sgmbsL', '2312160uyJpgu', 'getTime', '1780569IrbRgk', '24Kigyjl', '9HzRNWg', '408YAMsHI', 'log', '1268455sEkXMX', '6HkuEHp', '12443zxYqpr', '12856jCmFlr', '162118klnJKs', 'typeString', '708ajTqoU'];
//   _0x1b15 = function () {
//     return _0x282d1;
//   };
//   return _0x1b15();
// }
//
// function _0x3342(_0xdcd98d, _0x28a347) {
//   const _0x1b15b7 = _0x1b15();
//   return _0x3342 = function (_0x334243, _0x3607d2) {
//     _0x334243 = _0x334243 - 0x18e;
//     let _0x35962a = _0x1b15b7[_0x334243];
//     return _0x35962a;
//   }, _0x3342(_0xdcd98d, _0x28a347);
// }
//
// export function getHeadersRemix(_0x202751 = '') {
//   const _0x549aa2 = _0x3342,
//     _0x4e39f8 = getToken(),
//     _0x1a0607 = getCurrentUser(),
//     _0xa4505 = window[_0x549aa2(0x195)] || new Date()[_0x549aa2(0x199)](),
//     _0x4437ff = _0x4e39f8 + _0x1a0607['xgUserId'] + _0x1a0607[_0x549aa2(0x193)] + _0xa4505;
//   return console[_0x549aa2(0x19e)](Md5(_0x4437ff)), {
//     'headers': {
//       'Authorization': _0x549aa2(0x196) + _0x4e39f8,
//       'awc_auth': Md5(_0x4437ff),
//       'awc_timestamp': _0xa4505
//     }
//   };
// }
