import React, { FC } from 'react'; import { Tooltip } from 'antd'; import { NoField } from '@sensoro/sensoro-design'; import { usePermission } from '@sensoro/core'; import { formatPhoneNumber } from '@/utils/utils'; import { reduce, findLastIndex } from 'lodash'; type DataMaskType = | 'name' | 'contact' | 'certificateNumber' | 'licencePlate' | 'address' | undefined; interface IDataMaskProps { type?: DataMaskType; data?: string; children?: string; lengthLimit?: number; // 名称支持限制长度 } const DataMask: FC = props => { const { type, data, children, lengthLimit } = props; const text = data || children; const replacer = '*'; const getMaskData = (type: DataMaskType, text: string) => { let str = text || ''; const length = str.split('').length; switch (type) { case 'name': str = reduce( text, (ret: string, char: string, idx) => { if (length < 3) { if (idx > 0) { return ret + replacer; } else { return ret + char; } } else { if (idx === 0 || idx === length - 1) { return ret + char; } else { return ret + replacer; } } }, '', ); // 名称支持限制长度 if (lengthLimit && str.length > lengthLimit) { str = str.replace(/\*+/, '**'); } break; case 'contact': str = reduce( formatPhoneNumber(text), (ret: string, char: string, idx) => { if (idx < 3 || idx > length - 4) { return ret + char; } else { return ret + replacer; } }, '', ); break; case 'certificateNumber': str = reduce( text, (ret: string, char: string, idx) => { if (idx < 7 || idx > length - 4) { return ret + char; } else { return ret + replacer; } }, '', ); break; case 'licencePlate': str = reduce( text, (ret: string, char: string, idx) => { if (idx < 2 || idx > length - 3) { return ret + char; } else { return ret + replacer; } }, '', ); break; case 'address': const spaceLastIdx = findLastIndex(str, char => char === ' '); str = reduce( text, (ret: string, char: string, idx) => { if (spaceLastIdx < idx) { return ret + replacer; } else { return ret + char; } }, '', ); break; default: str = reduce( text, (ret: string, char: string, idx) => { return ret + replacer; }, '', ); break; } return str; }; return text ? ( usePermission('privacy:show') ? ( {text} ) : usePermission('privacy:read') ? ( {getMaskData(type, text)} ) : ( {getMaskData(type, text)} ) ) : ( ); }; export default DataMask;