index.tsx 19 KB

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