import React__default, { useState, useEffect } from 'react';
import { LabelValue, IconFont, AuthComponent } from '@zenview/micro-components';
import { cache, SocketEmitter } from '@zenview/micro-utils';
import { Service as Service$1, LMConfig } from '@zenview/micro-basic-library';
import { Modal, Button, Input, message } from 'antd';
import { observer, useLocalStore } from 'mobx-react';
import { a as _applyDecoratedDescriptor, b as _initializerDefineProperty } from '../_rollupPluginBabelHelpers-736b301a.js';
import { a as action, m as makeObservable, o as observable, b as autorun } from '../mobx.esm-dee4cf9f.js';

var config = {
  api: '/api/',
  communityApi: '/communityApi/',
  version: 'v1',
  version2: 'v2'
};

const {
  api
} = config;
var URL = {
  desensitization: {
    value: `${api}user/v2/cancel/desensitization/<id>`,
    label: '上传图片供以图搜图使用',
    requestId: 'desensitization'
  },
  getPublicKey: {
    value: `${api}/user/v2/getPublicKey`,
    label: '获取公钥',
    actionName: 'getPublicKey'
  }
};

const getHeaders = () => {
  return {
    Authorization: cache.getCache('token', 'session')
  };
};
class DesensitizationService {
  desensitization(data) {
    return Service$1.$http({
      headers: getHeaders(),
      url: URL.desensitization.value.replace('<id>', data.userId),
      method: "post",
      data,
      requestId: URL.desensitization.requestId
    });
  }
  getPwKey(password, RSA) {
    return Service$1.$http({
      url: URL.getPublicKey.value,
      method: 'post',
      requestId: 'getPublicKey'
    }).then(res => {
      var _res$data;
      if (!((_res$data = res.data) !== null && _res$data !== void 0 && _res$data.publicKey)) return '';
      return RSA.encrypt(password, res.data.publicKey) || '';
    });
  }
}
var Service = new DesensitizationService();

var _class, _descriptor, _descriptor2;
// import _ from 'lodash'

let instance = null;
let pageStore = (_class = class pageStore {
  constructor() {
    _initializerDefineProperty(this, "state", _descriptor, this);
    _initializerDefineProperty(this, "pageInit", _descriptor2, this);
    makeObservable(this);
  }
  static getInstance() {
    !instance && (instance = new pageStore());
    return instance;
  }
  setDesensitizationFun(boo) {
    this.state.isDesensitization = boo;
  }
}, _descriptor = _applyDecoratedDescriptor(_class.prototype, "state", [observable], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: function () {
    return {
      isDesensitization: false
    };
  }
}), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, "pageInit", [action], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: function () {
    return autorun(() => {
      const isDesensitization = cache.getCache('isDesensitization', 'session');
      const desensitizationTime = cache.getCache('desensitizationTime', 'session');
      const isOverdue = Number(desensitizationTime) - new Date().getTime() > 0;
      if (isOverdue) {
        // 时间没有过期，设置默认是否显示缓存
        this.setDesensitizationFun(isDesensitization);
      } else {
        // 时间过期，前端禁止看加密信息
        this.setDesensitizationFun(false);
      }
    });
  }
}), _applyDecoratedDescriptor(_class.prototype, "setDesensitizationFun", [action], Object.getOwnPropertyDescriptor(_class.prototype, "setDesensitizationFun"), _class.prototype), _class);

// micro-component

const cacheDesInfoObj = {
  isDesensitization: 'isDesensitization',
  desensitizationTime: 'desensitizationTime'
};
const EventNames = {
  // eslint-disable-line
  refreshDesensitization: 'refreshDesensitization' //脱敏刷新人员
};
let closeEyesTimer = null;
const DesensitizationInformation = observer(({
  name,
  val = '',
  noName,
  noEye = true,
  RSA
}) => {
  var _LMConfig$BSConfig, _LMConfig$BSConfig2;
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [userPassword, setUserPassword] = useState('');
  const pageStore$1 = useLocalStore(() => pageStore.getInstance());
  const DefaultDesensitizationTimer = LMConfig !== null && LMConfig !== void 0 && (_LMConfig$BSConfig = LMConfig.BSConfig) !== null && _LMConfig$BSConfig !== void 0 && _LMConfig$BSConfig.desensitizationTime ? Number(LMConfig === null || LMConfig === void 0 || (_LMConfig$BSConfig2 = LMConfig.BSConfig) === null || _LMConfig$BSConfig2 === void 0 ? void 0 : _LMConfig$BSConfig2.desensitizationTime) * 1000 : 1000 * 60 * 5;
  // console.log('默认脱敏时间', DefaultDesensitizationTimer / 1000 + '秒')

  const ModalClick = () => {
    const desensitizationTime = cache.getCache(cacheDesInfoObj.desensitizationTime, 'session');
    const isOverdue = Number(desensitizationTime) - new Date().getTime() > 0;

    // console.log(isOverdue)
    // window.sessionStorage?.isDesensitization只要存在，不管是true还是false都不需要重新请求
    // 除非设置时间过期
    if (window.sessionStorage[cacheDesInfoObj.isDesensitization] && isOverdue) {
      SocketEmitter.emit(EventNames.refreshDesensitization, {});
      cache.setCache(cacheDesInfoObj.isDesensitization, true, 'session');
      pageStore$1.setDesensitizationFun(true);
      closeEyesTimer = setTimeout(() => {
        SocketEmitter.emit(EventNames.refreshDesensitization, {});
        cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session');
        pageStore$1.setDesensitizationFun(false);
      }, DefaultDesensitizationTimer); // 5分钟后，页面中所有字段眼睛自动关闭，防止信息泄漏；
    } else {
      setIsModalVisible(true);
      setUserPassword('');
    }
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    setUserPassword('');
  };
  const CloseDesensitization = () => {
    cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session');
    SocketEmitter.emit(EventNames.refreshDesensitization, {});
    pageStore$1.setDesensitizationFun(false);
    clearTimeout(closeEyesTimer);
  };
  const ok = async RSA => {
    const password = await Service.getPwKey(userPassword, RSA);

    // local中有isDesensitization字段说明已经请求过了，没有的情况下请求
    const userId = cache.getCache('userId', 'session');
    Service.desensitization({
      userId,
      userPassword: password
    }).then(res => {
      if (+res.code === 0) {
        SocketEmitter.emit(EventNames.refreshDesensitization, {});
        pageStore$1.setDesensitizationFun(true);
        cache.setCache(cacheDesInfoObj.isDesensitization, true, 'session');
        cache.setCache(cacheDesInfoObj.desensitizationTime, new Date().getTime() + DefaultDesensitizationTimer, 'session');
        setIsModalVisible(false);
        closeEyesTimer = setTimeout(() => {
          cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session');
          pageStore$1.setDesensitizationFun(false);
        }, DefaultDesensitizationTimer); // 5分钟后，页面中所有字段眼睛自动关闭，防止信息泄漏；

        setUserPassword('');
        // setTimeout(() => {
        //   window.sessionStorage.removeItem(cacheDesInfoObj.isDesensitization)
        //   window.sessionStorage.removeItem(cacheDesInfoObj.desensitizationTime)
        //   pageStore.setDesensitizationFun(false)
        // }, DefaultDesensitizationTimer) // 用户持续15分钟不操作系统，则页面锁定，需要再次输入登录密码
      } else {
        message.error(res.message);
      }
    });
  };

  // 脱敏值转换
  const changeTheValue = t => {
    let isHideText = t;
    if (Number(t.replace(/\*/g, ''))) {
      // 证件号码，手机号脱敏
      const middleNum = (t === null || t === void 0 ? void 0 : t.length) >= 7 ? (t === null || t === void 0 ? void 0 : t.length) - 7 : 1;
      const middleText = new Array(middleNum).toString().split(',').map(() => '*').join('');
      isHideText = (t === null || t === void 0 ? void 0 : t.substring(0, 3)) + middleText + (t === null || t === void 0 ? void 0 : t.substring(t.length - 4));
    } else {
      // 姓名脱敏
      const middleNum = (t === null || t === void 0 ? void 0 : t.length) > 1 ? (t === null || t === void 0 ? void 0 : t.length) - 1 : 100;
      isHideText = t.length === 1 ? t : (t === null || t === void 0 ? void 0 : t.substring(0, 1)) + (middleNum !== 100 ? new Array(middleNum).toString().split(',').map(() => '*').join('') : '');
    }
    return pageStore$1.state.isDesensitization ? t : isHideText;
  };
  const desensitizationText = changeTheValue(val) || '暂无';
  let Default = null;
  if (name.includes('人') || name.includes('电话') || name.includes('号码') || name === '手机号' || name.includes('姓名')) {
    Default = /*#__PURE__*/React__default.createElement("div", {
      className: "desensitization-information",
      key: name
    }, /*#__PURE__*/React__default.createElement("div", {
      className: "d-i-num"
    }, noName ? desensitizationText : /*#__PURE__*/React__default.createElement(LabelValue, {
      key: name,
      label: name,
      className: "info-num",
      value: desensitizationText,
      emptyValue: "\u6682\u65E0",
      fontSize: 12
    })), !noEye && desensitizationText !== '暂无' ? pageStore$1.state.isDesensitization ? /*#__PURE__*/React__default.createElement("div", {
      className: "d-i-icon",
      onClick: () => CloseDesensitization()
    }, /*#__PURE__*/React__default.createElement(IconFont, {
      type: 'icon-xianshi'
    })) : /*#__PURE__*/React__default.createElement("div", {
      className: "d-i-icon",
      onClick: () => ModalClick()
    }, /*#__PURE__*/React__default.createElement(IconFont, {
      type: 'icon-yincang'
    })) : /*#__PURE__*/React__default.createElement(React__default.Fragment, null), /*#__PURE__*/React__default.createElement(Modal, {
      title: "\u5B89\u5168\u6821\u9A8C",
      visible: isModalVisible,
      onCancel: () => handleCancel(),
      width: 280,
      footer: [/*#__PURE__*/React__default.createElement(Button, {
        key: "back",
        type: "primary",
        onClick: () => ok(RSA)
      }, "\u63D0\u4EA4")]
    }, /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("div", null, "\u8BF7\u8F93\u5165\u7528\u6237\u5BC6\u7801"), /*#__PURE__*/React__default.createElement(Input, {
      type: "password",
      placeholder: "\u8BF7\u8F93\u5165\u767B\u5F55\u5BC6\u7801",
      onChange: e => setUserPassword(e.target.value)
    }))));
  }
  return Default;
});

// 查看脱敏信息按钮
const QueryDesensitizationButton = observer(props => {
  var _LMConfig$BSConfig3, _LMConfig$BSConfig4;
  const [buttonState, setButtonState] = useState(true);
  const [userPassword, setUserPassword] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const pageStore$1 = useLocalStore(() => pageStore.getInstance());
  const DefaultDesensitizationTimer = LMConfig !== null && LMConfig !== void 0 && (_LMConfig$BSConfig3 = LMConfig.BSConfig) !== null && _LMConfig$BSConfig3 !== void 0 && _LMConfig$BSConfig3.desensitizationTime ? Number(LMConfig === null || LMConfig === void 0 || (_LMConfig$BSConfig4 = LMConfig.BSConfig) === null || _LMConfig$BSConfig4 === void 0 ? void 0 : _LMConfig$BSConfig4.desensitizationTime) * 1000 : 1000 * 60 * 5;
  const modalRef = React__default.useRef();
  const {
    RSA
  } = props;
  useEffect(() => {
    const isDesensitization = cache.getCache(cacheDesInfoObj.isDesensitization, 'session');
    setButtonState(!isDesensitization);
  }, []);
  const StateChangeHandle = () => {
    if (buttonState) {
      ModalClick();
    } else {
      CloseDesensitization();
    }
  };
  const ModalClick = () => {
    const desensitizationTime = cache.getCache(cacheDesInfoObj.desensitizationTime, 'session');
    const isOverdue = Number(desensitizationTime) - new Date().getTime() > 0;

    // console.log(isOverdue)
    // window.sessionStorage?.isDesensitization只要存在，不管是true还是false都不需要重新请求
    // 除非设置时间过期
    if (window.sessionStorage[cacheDesInfoObj.isDesensitization] && isOverdue) {
      SocketEmitter.emit(EventNames.refreshDesensitization, {});
      cache.setCache(cacheDesInfoObj.isDesensitization, true, 'session');
      pageStore$1.setDesensitizationFun(true);
      setButtonState(!buttonState);
      closeEyesTimer = setTimeout(() => {
        SocketEmitter.emit(EventNames.refreshDesensitization, {});
        cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session');
        pageStore$1.setDesensitizationFun(false);
      }, DefaultDesensitizationTimer); // 5分钟后，页面中所有字段眼睛自动关闭，防止信息泄漏；
    } else {
      setIsModalVisible(true);
      setUserPassword('');
    }
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const CloseDesensitization = () => {
    cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session');
    SocketEmitter.emit(EventNames.refreshDesensitization, {});
    pageStore$1.setDesensitizationFun(false);
    clearTimeout(closeEyesTimer);
    setButtonState(!buttonState);
  };
  const ok = async RSA => {
    const password = await Service.getPwKey(userPassword, RSA);

    // local中有isDesensitization字段说明已经请求过了，没有的情况下请求
    const userId = cache.getCache('userId', 'session');
    Service.desensitization({
      userId,
      userPassword: password
    }).then(res => {
      if (+res.code === 0) {
        SocketEmitter.emit(EventNames.refreshDesensitization, {});
        pageStore$1.setDesensitizationFun(true);
        cache.setCache(cacheDesInfoObj.isDesensitization, true, 'session');
        cache.setCache(cacheDesInfoObj.desensitizationTime, new Date().getTime() + DefaultDesensitizationTimer, 'session');
        setIsModalVisible(false);
        closeEyesTimer = setTimeout(() => {
          cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session');
          pageStore$1.setDesensitizationFun(false);
          setIsModalVisible(false);
        }, DefaultDesensitizationTimer); // 5分钟后，页面中所有字段眼睛自动关闭，防止信息泄漏；
        setButtonState(!buttonState);
        // setTimeout(() => {
        //   window.sessionStorage.removeItem(cacheDesInfoObj.isDesensitization)
        //   window.sessionStorage.removeItem(cacheDesInfoObj.desensitizationTime)
        //   pageStore.setDesensitizationFun(false)
        // }, DefaultDesensitizationTimer) // 用户持续15分钟不操作系统，则页面锁定，需要再次输入登录密码
      } else {
        message.error(res.message);
      }
    });
  };
  return /*#__PURE__*/React__default.createElement(AuthComponent, {
    actionName: "queryDesensitizationInformation"
  }, /*#__PURE__*/React__default.createElement("div", {
    ref: modalRef
  }, /*#__PURE__*/React__default.createElement("div", {
    onClick: e => {
      StateChangeHandle();
    },
    className: "query-desensitization-button"
  }, /*#__PURE__*/React__default.createElement(IconFont, {
    type: buttonState ? 'icon-xianshi' : 'icon-yincang',
    className: "query-desensitization-icon"
  }), /*#__PURE__*/React__default.createElement("span", {
    className: "query-desensitization-text"
  }, buttonState ? '查看脱敏信息' : '隐藏脱敏信息')), /*#__PURE__*/React__default.createElement(Modal, {
    title: "\u5B89\u5168\u6821\u9A8C",
    visible: isModalVisible,
    onCancel: () => handleCancel(),
    getContainer: () => modalRef && modalRef.current,
    width: 280,
    footer: [/*#__PURE__*/React__default.createElement(Button, {
      key: "back",
      type: "primary",
      onClick: () => ok(RSA)
    }, "\u63D0\u4EA4")]
  }, /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("div", {
    style: {
      paddingBottom: '10px'
    }
  }, "\u8BF7\u8F93\u5165\u7528\u6237\u5BC6\u7801"), /*#__PURE__*/React__default.createElement(Input, {
    type: "password",
    value: userPassword,
    placeholder: "\u8BF7\u8F93\u5165\u767B\u5F55\u5BC6\u7801",
    onChange: e => setUserPassword(e.target.value)
  })))));
});

// 无状态文字脱敏
const desensitizationByState = t => {
  let isHideText = t;
  let textState = cache.getCache(cacheDesInfoObj.isDesensitization, 'session');
  if (Number(t.replace(/\*/g, ''))) {
    // 证件号码，手机号脱敏
    const middleNum = (t === null || t === void 0 ? void 0 : t.length) >= 7 ? (t === null || t === void 0 ? void 0 : t.length) - 7 : 1;
    const middleText = new Array(middleNum).toString().split(',').map(() => '*').join('');
    isHideText = (t === null || t === void 0 ? void 0 : t.substring(0, 3)) + middleText + (t === null || t === void 0 ? void 0 : t.substring(t.length - 4));
  } else {
    // 姓名脱敏
    const middleNum = (t === null || t === void 0 ? void 0 : t.length) > 1 ? (t === null || t === void 0 ? void 0 : t.length) - 1 : 100;
    isHideText = t.length === 1 ? t : (t === null || t === void 0 ? void 0 : t.substring(0, 1)) + (middleNum !== 100 ? new Array(middleNum).toString().split(',').map(() => '*').join('') : '');
  }
  return textState ? t : isHideText;
};
const getInfo = (name, val) => {
  return /*#__PURE__*/React__default.createElement(DesensitizationInformation, {
    noName: true,
    name: name,
    val: val,
    key: name
  });
};
var index = {
  DesensitizationInformation,
  QueryDesensitizationButton,
  desensitizationByState,
  getInfo
};

export { DesensitizationInformation, QueryDesensitizationButton, index as default, desensitizationByState, getInfo };
//# sourceMappingURL=index.js.map
