index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. import type { ISchema } from '@formily/json-schema';
  2. import { createSchemaField } from '@formily/react';
  3. import {
  4. ArrayItems,
  5. DatePicker,
  6. Form,
  7. FormGrid,
  8. FormItem,
  9. FormTab,
  10. Input,
  11. NumberPicker,
  12. PreviewText,
  13. Select,
  14. Space,
  15. } from '@formily/antd';
  16. import type { Field, FieldDataSource } from '@formily/core';
  17. import { createForm, onFieldReact, onFormInit } from '@formily/core';
  18. import GroupNameControl from '@/components/SearchComponent/GroupNameControl';
  19. import {
  20. DeleteOutlined,
  21. DoubleRightOutlined,
  22. ReloadOutlined,
  23. SaveOutlined,
  24. SearchOutlined,
  25. } from '@ant-design/icons';
  26. import {
  27. Button,
  28. Card,
  29. Dropdown,
  30. Empty,
  31. Menu,
  32. message,
  33. Popconfirm,
  34. Popover,
  35. Typography,
  36. } from 'antd';
  37. import { useEffect, useMemo, useState } from 'react';
  38. import type { ProColumns } from '@jetlinks/pro-table';
  39. import type { EnumData } from '@/utils/typings';
  40. import styles from './index.less';
  41. import Service from '@/components/SearchComponent/service';
  42. import _ from 'lodash';
  43. import { useIntl } from '@@/plugin-locale/localeExports';
  44. import classnames from 'classnames';
  45. const ui2Server = (source: SearchTermsUI): SearchTermsServer => [
  46. { terms: source.terms1 },
  47. { terms: source.terms2, type: source.type },
  48. ];
  49. const server2Ui = (source: SearchTermsServer): SearchTermsUI => ({
  50. terms1: source[0].terms,
  51. terms2: source[1]?.terms,
  52. type: source[0]?.type || 'and',
  53. });
  54. interface Props<T> {
  55. /** @name "搜索条件" */
  56. field: ProColumns<T>[];
  57. onSearch: (params: { terms: SearchTermsServer }) => void;
  58. target?: string;
  59. /**
  60. * @name "固定查询参数"
  61. * eg: 1: {[{ column: 'test', value: 'admin' }]}
  62. * 2: {[
  63. * {
  64. * terms: [{ column: 'parentId$isnull', value: '' }, { column: 'parentId$not', value: 'test', type: 'or' }],
  65. * },
  66. * {
  67. * terms: [{ column: 'id$not', value: 'test', type: 'and' }],
  68. * },
  69. * ]}
  70. * */
  71. defaultParam?: SearchTermsServer | Term[];
  72. // pattern?: 'simple' | 'advance';
  73. enableSave?: boolean;
  74. }
  75. const termType = [
  76. { label: '=', value: 'eq' },
  77. { label: '!=', value: 'not' },
  78. { label: '包含', value: 'like' },
  79. { label: '不包含', value: 'nlike' },
  80. { label: '>', value: 'gt' },
  81. { label: '>=', value: 'gte' },
  82. { label: '<', value: 'lt' },
  83. { label: '<=', value: 'lte' },
  84. { label: '属于', value: 'in' },
  85. { label: '不属于', value: 'nin' },
  86. ];
  87. const service = new Service();
  88. const initTerm = { termType: 'like' };
  89. const SchemaField = createSchemaField({
  90. components: {
  91. FormItem,
  92. FormTab,
  93. Input,
  94. Select,
  95. NumberPicker,
  96. FormGrid,
  97. ArrayItems,
  98. DatePicker,
  99. PreviewText,
  100. GroupNameControl,
  101. Space,
  102. },
  103. });
  104. const sortField = (field: ProColumns[]) => {
  105. let _temp = false;
  106. field.forEach((item) => {
  107. if (item.index) {
  108. _temp = true;
  109. return;
  110. }
  111. });
  112. if (!_temp) {
  113. // 如果没有index 就默认name字段最第一个
  114. field.map((item) => {
  115. console.log(item, 'items');
  116. if (item.dataIndex === 'name') {
  117. item.index = 0;
  118. return item;
  119. } else {
  120. return item;
  121. }
  122. });
  123. }
  124. // index排序
  125. return _.sortBy(field, (i) => i.index);
  126. };
  127. const SearchComponent = <T extends Record<string, any>>(props: Props<T>) => {
  128. const { field, target, onSearch, defaultParam, enableSave = true } = props;
  129. const intl = useIntl();
  130. const [expand, setExpand] = useState<boolean>(true);
  131. const initForm = server2Ui([{ terms: [initTerm] }]);
  132. const [logVisible, setLogVisible] = useState<boolean>(false);
  133. const [aliasVisible, setAliasVisible] = useState<boolean>(false);
  134. const [initParams, setInitParams] = useState<SearchTermsUI>(initForm);
  135. const [history, setHistory] = useState([]);
  136. /**
  137. * 过滤不参与搜索的数据
  138. */
  139. const filterSearchTerm = (): ProColumns<T>[] =>
  140. field
  141. .filter((item) => item.dataIndex)
  142. .filter((item) => !item.hideInSearch)
  143. .filter((item) => !['index', 'option'].includes(item.dataIndex as string));
  144. // 处理后的搜索条件
  145. const processedField = sortField(filterSearchTerm());
  146. const form = useMemo(
  147. () =>
  148. createForm<SearchTermsUI>({
  149. validateFirst: true,
  150. initialValues: initParams,
  151. effects() {
  152. onFormInit((form1) => {
  153. if (expand) {
  154. form1.setValues({
  155. terms1: [{ column: processedField[0]?.dataIndex, termType: 'like' }],
  156. });
  157. }
  158. });
  159. onFieldReact('*.*.column', async (typeFiled, f) => {
  160. const _column = (typeFiled as Field).value;
  161. const _field = field.find((item) => item.dataIndex === _column);
  162. if (_field?.valueType === 'select') {
  163. let option: { label: any; value: any }[] | FieldDataSource | undefined = [];
  164. if (_field?.valueEnum) {
  165. option = Object.values(_field?.valueEnum || {}).map((item) => ({
  166. label: item.text,
  167. value: item.status,
  168. }));
  169. } else if (_field?.request) {
  170. option = await _field.request();
  171. }
  172. f.setFieldState(typeFiled.query('.termType'), async (state) => {
  173. state.value = 'eq';
  174. });
  175. f.setFieldState(typeFiled.query('.value'), async (state) => {
  176. state.componentType = 'Select';
  177. state.loading = true;
  178. state.dataSource = option;
  179. state.loading = false;
  180. });
  181. } else if (_field?.valueType === 'digit') {
  182. f.setFieldState(typeFiled.query('.value'), async (state) => {
  183. state.componentType = 'NumberPicker';
  184. });
  185. f.setFieldState(typeFiled.query('.termType'), async (state) => {
  186. state.value = 'eq';
  187. });
  188. } else if (_field?.valueType === 'dateTime') {
  189. f.setFieldState(typeFiled.query('.value'), async (state) => {
  190. state.componentType = 'DatePicker';
  191. state.componentProps = { showTime: true };
  192. });
  193. f.setFieldState(typeFiled.query('.termType'), async (state) => {
  194. state.value = 'gt';
  195. });
  196. } else {
  197. f.setFieldState(typeFiled.query('.value'), async (state) => {
  198. state.componentType = 'Input';
  199. });
  200. }
  201. });
  202. },
  203. }),
  204. [expand],
  205. );
  206. const historyForm = createForm();
  207. const queryHistory = async () => {
  208. const response = await service.history.query(`${target}-search`);
  209. if (response.status === 200) {
  210. setHistory(response.result);
  211. }
  212. };
  213. const createGroup = (name: string): ISchema => ({
  214. 'x-decorator': 'FormItem',
  215. 'x-decorator-props': {
  216. gridSpan: 4,
  217. },
  218. 'x-component': 'ArrayItems',
  219. type: 'array',
  220. 'x-value': new Array(expand ? 1 : 3).fill({ termType: 'like' }),
  221. items: {
  222. type: 'object',
  223. 'x-component': 'FormGrid',
  224. 'x-component-props': {
  225. minColumns: 14,
  226. maxColumns: 14,
  227. columnGap: 24,
  228. // rowGap: 1,
  229. },
  230. properties: {
  231. type: {
  232. 'x-decorator': 'FormItem',
  233. 'x-component': 'GroupNameControl',
  234. 'x-decorator-props': {
  235. gridSpan: 2,
  236. },
  237. default: 'or',
  238. 'x-component-props': {
  239. name: name,
  240. },
  241. 'x-visible': !expand,
  242. },
  243. column: {
  244. type: 'string',
  245. 'x-decorator': 'FormItem',
  246. 'x-component': 'Select',
  247. 'x-decorator-props': {
  248. gridSpan: 3,
  249. },
  250. 'x-component-props': {
  251. placeholder: '请选择',
  252. },
  253. enum: filterSearchTerm().map((i) => ({ label: i.title, value: i.dataIndex } as EnumData)),
  254. },
  255. termType: {
  256. type: 'enum',
  257. 'x-decorator': 'FormItem',
  258. 'x-component': 'Select',
  259. 'x-decorator-props': {
  260. gridSpan: 3,
  261. },
  262. default: 'like',
  263. enum: termType,
  264. },
  265. value: {
  266. 'x-decorator-props': {
  267. gridSpan: 6,
  268. },
  269. 'x-decorator': 'FormItem',
  270. 'x-component': 'Input',
  271. },
  272. },
  273. },
  274. });
  275. const schema: ISchema = {
  276. type: 'object',
  277. properties: {
  278. layout: {
  279. type: 'void',
  280. 'x-component': 'FormGrid',
  281. 'x-component-props': {
  282. minColumns: 9,
  283. maxColumns: 9,
  284. },
  285. properties: {
  286. terms1: createGroup('第一组'),
  287. type: {
  288. 'x-decorator': 'FormItem',
  289. 'x-component': 'Select',
  290. 'x-decorator-props': {
  291. gridSpan: 1,
  292. style: {
  293. display: 'flex',
  294. alignItems: 'center',
  295. marginTop: '-22px',
  296. padding: '0 30px',
  297. },
  298. },
  299. default: 'and',
  300. enum: [
  301. { label: '并且', value: 'and' },
  302. { label: '或者', value: 'or' },
  303. ],
  304. },
  305. terms2: createGroup('第二组'),
  306. },
  307. },
  308. },
  309. };
  310. const handleExpand = () => {
  311. const value = form.values;
  312. if (expand) {
  313. value.terms1 = [0, 1, 2].map((i) => ({
  314. termType: 'like',
  315. column: (processedField[i]?.dataIndex as string) || null,
  316. type: 'or',
  317. }));
  318. value.terms2 = [3, 4, 5].map((i) => ({
  319. termType: 'like',
  320. column: (processedField[i]?.dataIndex as string) || null,
  321. type: 'or',
  322. }));
  323. } else {
  324. value.terms1 = [
  325. { termType: 'like', column: (processedField[0].dataIndex as string) || null },
  326. ];
  327. value.terms2 = [];
  328. }
  329. setInitParams(value);
  330. setExpand(!expand);
  331. };
  332. const simpleSchema: ISchema = {
  333. type: 'object',
  334. properties: {
  335. terms1: createGroup('第一组'),
  336. },
  337. };
  338. const handleHistory = (item: SearchHistory) => {
  339. const log = JSON.parse(item.content) as SearchTermsUI;
  340. form.setValues(log);
  341. setExpand(!(log.terms1?.length > 1 || log.terms2?.length > 1));
  342. };
  343. const historyDom = (
  344. <Menu className={styles.history}>
  345. {history.length > 0 ? (
  346. history.map((item: SearchHistory) => (
  347. <Menu.Item onClick={() => handleHistory(item)} key={item.id}>
  348. <div className={styles.list}>
  349. <Typography.Text ellipsis={{ tooltip: item.name }}>{item.name}</Typography.Text>
  350. <Popconfirm
  351. onConfirm={async (e) => {
  352. e?.stopPropagation();
  353. const response = await service.history.remove(`${target}-search`, item.key);
  354. if (response.status === 200) {
  355. message.success('操作成功');
  356. const temp = history.filter((h: any) => h.key !== item.key);
  357. setHistory(temp);
  358. }
  359. }}
  360. title={'确认删除吗?'}
  361. >
  362. <DeleteOutlined onClick={(e) => e.stopPropagation()} />
  363. </Popconfirm>
  364. </div>
  365. </Menu.Item>
  366. ))
  367. ) : (
  368. <Menu.Item>
  369. <div
  370. style={{
  371. display: 'flex',
  372. justifyContent: 'center',
  373. alignItems: 'center',
  374. width: '148px',
  375. }}
  376. >
  377. <Empty />
  378. </div>
  379. </Menu.Item>
  380. )}
  381. </Menu>
  382. );
  383. const formatValue = (value: SearchTermsUI): SearchTermsServer => {
  384. let _value = ui2Server(value);
  385. // 处理默认查询参数
  386. if (defaultParam && defaultParam?.length > 0) {
  387. if ('terms' in defaultParam[0]) {
  388. _value = _value.concat(defaultParam as SearchTermsServer);
  389. } else if ('value' in defaultParam[0]) {
  390. _value = _value.concat([{ terms: defaultParam }]);
  391. }
  392. }
  393. return _value
  394. .filter((i) => i.terms?.length > 0)
  395. .map((term) => {
  396. term.terms?.map((item) => {
  397. if (item.termType === 'like') {
  398. item.value = `%${item.value}%`;
  399. return item;
  400. }
  401. return item;
  402. });
  403. return term;
  404. });
  405. };
  406. const handleSearch = async () => {
  407. const value = form.values;
  408. const filterTerms = (data: Partial<Term>[] | undefined) =>
  409. data && data.filter((item) => item.column != null).filter((item) => item.value !== undefined);
  410. const _terms = _.cloneDeep(value);
  411. _terms.terms1 = filterTerms(_terms.terms1);
  412. _terms.terms2 = filterTerms(_terms.terms2);
  413. onSearch({ terms: formatValue(_terms) });
  414. };
  415. useEffect(() => {
  416. if (defaultParam) {
  417. handleSearch();
  418. }
  419. }, []);
  420. const handleSaveLog = async () => {
  421. const value = await form.submit<SearchTermsUI>();
  422. const value2 = await historyForm.submit<{ alias: string }>();
  423. const response = await service.history.save(`${target}-search`, {
  424. name: value2.alias,
  425. content: JSON.stringify(value),
  426. });
  427. if (response.status === 200) {
  428. message.success('保存成功!');
  429. } else {
  430. message.error('保存失败');
  431. }
  432. setAliasVisible(!aliasVisible);
  433. };
  434. const resetForm = async () => {
  435. const temp = initForm;
  436. const expandData = Array(expand ? 1 : 3).fill(initTerm);
  437. temp.terms1 = expandData;
  438. temp.terms2 = expandData;
  439. await form.reset();
  440. await handleSearch();
  441. };
  442. const SearchBtn = {
  443. simple: (
  444. <Button icon={<SearchOutlined />} onClick={handleSearch} type="primary">
  445. 搜索
  446. </Button>
  447. ),
  448. advance: (
  449. <Dropdown.Button
  450. icon={<SearchOutlined />}
  451. placement={'bottomLeft'}
  452. trigger={['click']}
  453. onClick={handleSearch}
  454. visible={logVisible}
  455. onVisibleChange={async (visible) => {
  456. setLogVisible(visible);
  457. if (visible) {
  458. await queryHistory();
  459. }
  460. }}
  461. type="primary"
  462. overlay={historyDom}
  463. >
  464. 搜索
  465. </Dropdown.Button>
  466. ),
  467. };
  468. const SaveBtn = (
  469. <Popover
  470. content={
  471. <Form style={{ width: '217px' }} form={historyForm}>
  472. <SchemaField
  473. schema={{
  474. type: 'object',
  475. properties: {
  476. alias: {
  477. 'x-decorator': 'FormItem',
  478. 'x-component': 'Input.TextArea',
  479. 'x-validator': [
  480. {
  481. max: 50,
  482. message: '最多可输入50个字符',
  483. },
  484. ],
  485. },
  486. },
  487. }}
  488. />
  489. <Button onClick={handleSaveLog} type="primary" className={styles.saveLog}>
  490. 保存
  491. </Button>
  492. </Form>
  493. }
  494. visible={aliasVisible}
  495. onVisibleChange={setAliasVisible}
  496. title="搜索名称"
  497. trigger="click"
  498. >
  499. <Button icon={<SaveOutlined />} block>
  500. {intl.formatMessage({
  501. id: 'pages.data.option.save',
  502. defaultMessage: '保存',
  503. })}
  504. </Button>
  505. </Popover>
  506. );
  507. return (
  508. <Card bordered={false} className={styles.container}>
  509. <Form form={form} className={styles.form} labelCol={4} wrapperCol={18}>
  510. <div className={expand && styles.simple}>
  511. <SchemaField schema={expand ? simpleSchema : schema} />
  512. <div className={styles.action} style={{ marginTop: expand ? 0 : -12 }}>
  513. <Space>
  514. {enableSave ? SearchBtn.advance : SearchBtn.simple}
  515. {enableSave && SaveBtn}
  516. <Button icon={<ReloadOutlined />} block onClick={resetForm}>
  517. 重置
  518. </Button>
  519. </Space>
  520. <div className={classnames(styles.more, !expand ? styles.simple : styles.advance)}>
  521. <Button type="link" onClick={handleExpand}>
  522. 更多筛选
  523. <DoubleRightOutlined style={{ marginLeft: 32 }} rotate={expand ? 90 : -90} />
  524. </Button>
  525. </div>
  526. </div>
  527. </div>
  528. </Form>
  529. </Card>
  530. );
  531. };
  532. export default SearchComponent;