index.tsx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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, Menu, Popconfirm, 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 { onlyMessage, randomString } from '@/utils/util';
  37. import { useHistory, useLocation } from 'umi';
  38. import { Empty } from '@/components';
  39. const ui2Server = (source: SearchTermsUI): SearchTermsServer => [
  40. { terms: source.terms1 },
  41. { terms: source.terms2, type: source.type },
  42. ];
  43. const server2Ui = (source: SearchTermsServer): SearchTermsUI => ({
  44. terms1: source[0].terms,
  45. terms2: source[1]?.terms,
  46. type: source[0]?.type || 'and',
  47. });
  48. interface Props<T> {
  49. /** @name "搜索条件" */
  50. field: ProColumns<T>[];
  51. onSearch: (params: { terms: SearchTermsServer }) => void;
  52. target?: string;
  53. /**
  54. * @name "固定查询参数"
  55. * eg: 1: {[{ column: 'test', value: 'admin' }]}
  56. * 2: {[
  57. * {
  58. * terms: [{ column: 'parentId$isnull', value: '' }, { column: 'parentId$not', value: 'test', type: 'or' }],
  59. * },
  60. * {
  61. * terms: [{ column: 'id$not', value: 'test', type: 'and' }],
  62. * },
  63. * ]}
  64. * */
  65. defaultParam?: SearchTermsServer | Term[];
  66. /**
  67. * @name "搜索组件模式"
  68. * simple 限制只支持一组搜索条件,用于小弹窗搜索时使用
  69. */
  70. model?: 'simple' | 'advance';
  71. enableSave?: boolean;
  72. initParam?: SearchTermsServer;
  73. style?: React.CSSProperties;
  74. bodyStyle?: React.CSSProperties;
  75. }
  76. const termType = [
  77. { label: '=', value: 'eq' },
  78. { label: '!=', value: 'not' },
  79. { label: '包含', value: 'like' },
  80. { label: '不包含', value: 'nlike' },
  81. { label: '>', value: 'gt' },
  82. { label: '>=', value: 'gte' },
  83. { label: '<', value: 'lt' },
  84. { label: '<=', value: 'lte' },
  85. { label: '属于', value: 'in' },
  86. { label: '不属于', value: 'nin' },
  87. ];
  88. const service = new Service();
  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. TreeSelect,
  103. },
  104. });
  105. /**
  106. * 搜索字段排序
  107. * @param field
  108. */
  109. const sortField = (field: ProColumns[]) => {
  110. let _temp = false;
  111. field.forEach((item) => {
  112. if (item.index) {
  113. _temp = true;
  114. return;
  115. }
  116. });
  117. if (!_temp) {
  118. // 如果没有index 就默认name字段最第一个
  119. field.map((item) => {
  120. if (item.dataIndex === 'name') {
  121. item.index = 0;
  122. return item;
  123. } else {
  124. return item;
  125. }
  126. });
  127. }
  128. // index排序
  129. return _.sortBy(field, (i) => i.index);
  130. };
  131. // 保存历史记录
  132. // 过滤不参与搜索的列数据 ==> 字段排序
  133. // 场景一:简单模式
  134. // 默认搜索参数,根据Index 来判断,或者默认name为第一组条件
  135. // 场景二:高级模式
  136. // 默认六组搜索条件。根据字段index排序
  137. // const nodeFor = <T extends Record<string, any>>(props: Props<T>, ref) => {
  138. // console.log(props,ref)
  139. // return (<></>)
  140. // }
  141. //
  142. // export const node = forwardRef(nodeFor) as <RecordType extends Record<string, any>>(props: Props<RecordType>, ref?: React.Ref<HTMLDivElement>) => React.ReactElement
  143. const SearchComponent = <T extends Record<string, any>>(props: Props<T>) => {
  144. const { field, target, onSearch, defaultParam, enableSave = true, initParam, model } = props;
  145. const _history = useHistory();
  146. const _location = useLocation();
  147. /**
  148. * 过滤不参与搜索的数据 ?
  149. * TODO Refactor 依赖透明?
  150. */
  151. const filterSearchTerm = (): ProColumns<any>[] =>
  152. field
  153. .filter((item) => item.dataIndex)
  154. .filter((item) => !item.hideInSearch)
  155. .filter((item) => !['index', 'option'].includes(item.dataIndex as string));
  156. /**
  157. * 根据dataIndex 过滤不参与查询的参数
  158. *
  159. * @param _field 查询的列
  160. * @param excludes 过滤的字段名称
  161. */
  162. // const filterSearchTerm2 = (_field: ProColumns<T>[] = [], excludes: string[] = []) =>
  163. // _field.filter(item => item.dataIndex)
  164. // .filter(item => !item.hideInSearch)
  165. // .filter(item => !excludes.includes(item.dataIndex as string))
  166. // 处理后的搜索条件
  167. const processedField = sortField(filterSearchTerm());
  168. const defaultTerms = (index: number) =>
  169. ({
  170. termType: 'like',
  171. column: (processedField[index]?.dataIndex as string) || null,
  172. type: 'or',
  173. } as Partial<Term>);
  174. const intl = useIntl();
  175. const [expand, setExpand] = useState<boolean>(true);
  176. const initForm = server2Ui(initParam || [{ terms: [defaultTerms(0)] }]);
  177. const [aliasVisible, setAliasVisible] = useState<boolean>(false);
  178. const [initParams, setInitParams] = useState<SearchTermsUI>(initForm);
  179. const [history, setHistory] = useState([]);
  180. const [logVisible, setLogVisible] = useState<boolean>(false);
  181. const uiParamRef = useRef(initParam);
  182. const form = useMemo(
  183. () =>
  184. createForm<SearchTermsUI>({
  185. validateFirst: true,
  186. initialValues: initParams,
  187. effects() {
  188. onFieldReact('*.*.column', async (typeFiled, f) => {
  189. // if ((typeFiled as Field).modified) {
  190. const isModified = (typeFiled as Field).modified;
  191. const _column = (typeFiled as Field).value;
  192. const _field = field.find((item) => item.dataIndex === _column);
  193. if (_column === 'id') {
  194. if (isModified) {
  195. f.setFieldState(typeFiled.query('.termType'), async (state) => {
  196. state.value = 'eq';
  197. });
  198. }
  199. f.setFieldState(typeFiled.query('.value'), async (state) => {
  200. state.componentType = 'Input';
  201. state.componentProps = {
  202. allowClear: true,
  203. // onchange:(event:any)=>{
  204. // console.log(event.target?.value)
  205. // }
  206. };
  207. });
  208. } else {
  209. switch (_field?.valueType) {
  210. case 'select':
  211. let __option: { label: any; value: any }[] | FieldDataSource | undefined = [];
  212. f.setFieldState(typeFiled.query('.termType'), async (state) => {
  213. state.value = 'eq';
  214. });
  215. if (_field?.valueEnum) {
  216. __option = Object.values(_field?.valueEnum || {}).map((item) => ({
  217. label: item.text,
  218. value: item.status,
  219. }));
  220. } else if (_field?.request) {
  221. __option = await _field.request();
  222. }
  223. if (isModified) {
  224. f.setFieldState(typeFiled.query('.termType'), async (state) => {
  225. state.value = 'eq';
  226. });
  227. }
  228. f.setFieldState(typeFiled.query('.value'), async (state) => {
  229. state.componentType = 'Select';
  230. state.dataSource = __option;
  231. state.componentProps = {
  232. allowClear: true,
  233. showSearch: true,
  234. filterOption: (input: string, option: any) =>
  235. option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0,
  236. };
  237. });
  238. break;
  239. case 'treeSelect':
  240. let _option: { label: any; value: any }[] | FieldDataSource | undefined = [];
  241. if (_field?.valueEnum) {
  242. _option = Object.values(_field?.valueEnum || {}).map((item) => ({
  243. label: item.text,
  244. value: item.status,
  245. }));
  246. } else if (_field?.request) {
  247. _option = await _field.request();
  248. }
  249. if (isModified) {
  250. f.setFieldState(typeFiled.query('.termType'), (_state) => {
  251. _state.value = 'eq';
  252. });
  253. }
  254. f.setFieldState(typeFiled.query('.value'), (state) => {
  255. state.componentType = 'TreeSelect';
  256. state.dataSource = _option;
  257. state.componentProps = {
  258. ..._field.fieldProps,
  259. allowClear: true,
  260. showSearch: true,
  261. treeNodeFilterProp: 'name',
  262. filterOption: (input: string, option: any) =>
  263. option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0,
  264. };
  265. });
  266. break;
  267. case 'digit':
  268. f.setFieldState(typeFiled.query('.value'), async (state) => {
  269. state.componentType = 'NumberPicker';
  270. state.componentProps = { allowClear: true };
  271. });
  272. if (isModified) {
  273. f.setFieldState(typeFiled.query('.termType'), async (state) => {
  274. state.value = 'eq';
  275. });
  276. }
  277. break;
  278. case 'dateTime':
  279. f.setFieldState(typeFiled.query('.value'), async (state) => {
  280. state.componentType = 'DatePicker';
  281. state.componentProps = { showTime: true, allowClear: true };
  282. });
  283. f.setFieldState(typeFiled.query('.termType'), async (state) => {
  284. state.value = 'eq';
  285. });
  286. // console.log(isModified);
  287. if (isModified) {
  288. f.setFieldState(typeFiled.query('.termType'), async (state) => {
  289. state.value = 'eq';
  290. });
  291. }
  292. break;
  293. default:
  294. if (isModified) {
  295. f.setFieldState(typeFiled.query('.termType'), async (state) => {
  296. state.value = 'like';
  297. });
  298. }
  299. f.setFieldState(typeFiled.query('.value'), async (state) => {
  300. state.componentType = 'Input';
  301. state.componentProps = { allowClear: true };
  302. });
  303. break;
  304. }
  305. }
  306. // }
  307. });
  308. onFieldValueChange('*.*.column', (field1, form1) => {
  309. form1.setFieldState(field1.query('.value'), (state1) => {
  310. if (field1.modified) {
  311. state1.value = undefined;
  312. }
  313. });
  314. });
  315. },
  316. }),
  317. [target, expand],
  318. );
  319. const historyForm = createForm();
  320. const queryHistory = async () => {
  321. const response = await service.history.query(`${target}-search`);
  322. if (response.status === 200) {
  323. setHistory(response.result);
  324. }
  325. };
  326. const createGroup = (name: string): ISchema => ({
  327. 'x-decorator': 'FormItem',
  328. 'x-decorator-props': {
  329. gridSpan: 4,
  330. },
  331. 'x-component': 'ArrayItems',
  332. type: 'array',
  333. 'x-value': new Array(expand ? 1 : 3).fill({ termType: 'like' }),
  334. items: {
  335. type: 'object',
  336. 'x-component': 'FormGrid',
  337. 'x-component-props': {
  338. minColumns: 14,
  339. maxColumns: 14,
  340. columnGap: 24,
  341. // rowGap: 1,
  342. },
  343. properties: {
  344. type: {
  345. 'x-decorator': 'FormItem',
  346. 'x-component': 'GroupNameControl',
  347. 'x-decorator-props': {
  348. gridSpan: 3,
  349. },
  350. default: 'or',
  351. 'x-component-props': {
  352. name: name,
  353. },
  354. 'x-visible': !expand,
  355. },
  356. column: {
  357. type: 'string',
  358. 'x-decorator': 'FormItem',
  359. 'x-component': 'Select',
  360. 'x-decorator-props': {
  361. gridSpan: 3,
  362. },
  363. 'x-component-props': {
  364. placeholder: '请选择',
  365. },
  366. enum: filterSearchTerm().map((i) => ({ label: i.title, value: i.dataIndex } as EnumData)),
  367. },
  368. termType: {
  369. type: 'enum',
  370. 'x-decorator': 'FormItem',
  371. 'x-component': 'Select',
  372. 'x-decorator-props': {
  373. gridSpan: 3,
  374. },
  375. default: 'like',
  376. enum: termType,
  377. },
  378. value: {
  379. 'x-decorator-props': {
  380. gridSpan: 6,
  381. },
  382. 'x-decorator': 'FormItem',
  383. 'x-component': 'Input',
  384. },
  385. },
  386. },
  387. });
  388. const schema: ISchema = {
  389. type: 'object',
  390. properties: {
  391. layout: {
  392. type: 'void',
  393. 'x-component': 'FormGrid',
  394. 'x-component-props': {
  395. minColumns: 9,
  396. maxColumns: 9,
  397. },
  398. properties: {
  399. terms1: createGroup('第一组'),
  400. type: {
  401. 'x-decorator': 'FormItem',
  402. 'x-component': 'Select',
  403. 'x-decorator-props': {
  404. gridSpan: 1,
  405. style: {
  406. display: 'flex',
  407. alignItems: 'center',
  408. marginTop: '-22px',
  409. padding: '0 30px',
  410. },
  411. },
  412. default: 'and',
  413. enum: [
  414. { label: '并且', value: 'and' },
  415. { label: '或者', value: 'or' },
  416. ],
  417. },
  418. terms2: createGroup('第二组'),
  419. },
  420. },
  421. },
  422. };
  423. const handleForm = (_expand?: boolean) => {
  424. const value = form.values;
  425. const __expand = _expand !== undefined ? _expand : expand;
  426. // 第一组条件值
  427. const _terms1 = _.cloneDeep(value.terms1?.[0]);
  428. const uiParam = uiParamRef.current;
  429. // 判断一下条件。。是否展开。
  430. if (__expand) {
  431. value.terms1 = [
  432. uiParam?.[0]?.terms?.[0] || _terms1 || defaultTerms(0),
  433. uiParam?.[0]?.terms?.[1] || defaultTerms(1),
  434. uiParam?.[0]?.terms?.[2] || defaultTerms(2),
  435. ];
  436. value.terms2 = [
  437. uiParam?.[1]?.terms?.[0] || defaultTerms(3),
  438. uiParam?.[1]?.terms?.[1] || defaultTerms(4),
  439. uiParam?.[1]?.terms?.[2] || defaultTerms(5),
  440. ];
  441. } else {
  442. value.terms1 = [uiParam?.[0]?.terms?.[0] || _terms1 || defaultTerms(0)];
  443. value.terms2 = [];
  444. }
  445. setInitParams(value);
  446. };
  447. const handleExpand = () => {
  448. handleForm();
  449. setExpand(!expand);
  450. };
  451. useEffect(() => {
  452. // 1、一组条件时的表单值
  453. // 2、六组条件时的表单值
  454. // 3、拥有默认条件时的表单值
  455. // 合并初始化的值
  456. //expand false 6组条件 true 1组条件
  457. if (initParam && initParam[0].terms && initParam[0].terms.length > 1) {
  458. handleExpand();
  459. }
  460. }, [initParam]);
  461. const simpleSchema: ISchema = {
  462. type: 'object',
  463. properties: {
  464. terms1: createGroup('第一组'),
  465. },
  466. };
  467. const handleHistory = (item: SearchHistory) => {
  468. const log = JSON.parse(item.content) as SearchTermsUI;
  469. setLogVisible(false);
  470. uiParamRef.current = ui2Server(log);
  471. const _expand =
  472. !!(log.terms1 && log.terms1.length > 1) || !!(log.terms2 && log.terms2.length > 1);
  473. if (_expand) {
  474. setExpand(false);
  475. }
  476. handleForm(_expand);
  477. };
  478. const formatValue = (value: SearchTermsUI): SearchTermsServer => {
  479. let _value = ui2Server(value);
  480. // 处理默认查询参数
  481. if (defaultParam && defaultParam?.length > 0) {
  482. if ('terms' in defaultParam[0]) {
  483. _value = _value.concat(defaultParam as SearchTermsServer);
  484. } else if ('value' in defaultParam[0]) {
  485. _value = _value.concat([{ terms: defaultParam }]);
  486. }
  487. }
  488. return _value
  489. .filter((i) => i.terms && i.terms?.length > 0)
  490. .map((_term) => {
  491. _term.terms = _term.terms
  492. ?.filter((term) => term.value !== '')
  493. .map((item) => {
  494. if (item.termType === 'like' && item.value && item.value !== '') {
  495. item.value = `%${item.value}%`;
  496. return item;
  497. }
  498. if (item.termType === 'nlike' && item.value && item.value !== '') {
  499. item.value = `%${item.value}%`;
  500. return item;
  501. }
  502. return item;
  503. });
  504. return _term;
  505. });
  506. };
  507. const handleSearchValue = (
  508. data: SearchTermsServer,
  509. fields: ProColumns<T>[],
  510. ): SearchTermsServer => {
  511. return data.map((item) => {
  512. item.terms?.forEach((termsItem) => {
  513. const _fieldItem = fields.find((fieldItem) => fieldItem.dataIndex === termsItem.column);
  514. if (
  515. _fieldItem &&
  516. _fieldItem.search &&
  517. _fieldItem.search.transform &&
  518. _.isFunction(_fieldItem.search.transform)
  519. ) {
  520. termsItem.value = _fieldItem.search.transform(termsItem.value, '', '');
  521. }
  522. });
  523. return item;
  524. });
  525. };
  526. const handleSearch = async (type: boolean = true) => {
  527. const value = form.values;
  528. const filterTerms = (data: Partial<Term>[] | undefined) =>
  529. data && data.filter((item) => item.column != null).filter((item) => item.value !== undefined);
  530. const _terms = _.cloneDeep(value);
  531. _terms.terms1 = filterTerms(_terms.terms1);
  532. _terms.terms2 = filterTerms(_terms.terms2);
  533. const _temp = formatValue(_terms);
  534. uiParamRef.current = ui2Server(value);
  535. if (
  536. (_terms.terms1 && _terms.terms1.length > 1) ||
  537. (_terms.terms2 && _terms.terms2.length >= 1)
  538. ) {
  539. // 展开高级搜索
  540. setExpand(false);
  541. handleForm(true);
  542. }
  543. const params = new URLSearchParams(_location.search);
  544. params.delete('q');
  545. params.delete('target');
  546. if (
  547. (value.terms1 && value.terms1.length && value.terms1?.some((item) => item.value)) ||
  548. (value.terms2 && value.terms2.length && value.terms2?.some((item) => item.value))
  549. ) {
  550. if (type) {
  551. params.append('q', JSON.stringify(value));
  552. if (props.target) {
  553. params.append('target', props.target);
  554. }
  555. _history.push({
  556. hash: _location.hash,
  557. search: '?' + params.toString(),
  558. });
  559. // setUrl({ q: JSON.stringify(value), target: props.target });
  560. }
  561. } else {
  562. _history.push({
  563. hash: _location.hash,
  564. search: '?' + params.toString(),
  565. });
  566. }
  567. const newTemp = handleSearchValue(_.cloneDeep(_temp), props.field);
  568. onSearch({ terms: newTemp });
  569. };
  570. const handleLocation = async (l: any, tar?: string) => {
  571. // 防止页面下多个TabsTabPane中的查询组件共享路由中的参数
  572. const params = new URLSearchParams(l.search);
  573. const q = params.get('q');
  574. const _target = params.get('target');
  575. const value = await form.submit<SearchTermsUI>();
  576. if (q && props.model !== 'simple' && value && !value.terms1?.[0].value && !value.terms2) {
  577. // 表单有值的情况下,不改变表单
  578. if (_target && tar && _target === tar) {
  579. const _qJson: any = JSON.parse(q);
  580. form.setInitialValues(_qJson);
  581. handleSearch(false);
  582. return;
  583. }
  584. // form.setInitialValues(JSON.parse(q));
  585. // handleSearch(false);
  586. }
  587. };
  588. useEffect(() => {
  589. handleLocation(_location, props.target);
  590. }, [_location, props.target]);
  591. useEffect(() => {
  592. if (defaultParam) {
  593. handleSearch(!(props.model === 'simple'));
  594. }
  595. }, []);
  596. const historyDom = (
  597. <Menu className={styles.history}>
  598. {history.length > 0 ? (
  599. history.map((item: SearchHistory) => (
  600. <Menu.Item
  601. key={item.id || randomString(9)}
  602. onClick={() => {
  603. handleHistory(item);
  604. handleSearch();
  605. }}
  606. >
  607. <div className={styles.list}>
  608. <Typography.Text className={styles['list-text']} ellipsis={{ tooltip: item.name }}>
  609. {item.name}
  610. </Typography.Text>
  611. <Popconfirm
  612. title="确定删除嘛"
  613. onConfirm={async (e) => {
  614. e?.stopPropagation();
  615. const response = await service.history.remove(`${target}-search`, item.key);
  616. if (response.status === 200) {
  617. onlyMessage('操作成功');
  618. const temp = history.filter((h: any) => h.key !== item.key);
  619. setHistory(temp);
  620. }
  621. }}
  622. >
  623. <DeleteOutlined />
  624. </Popconfirm>
  625. </div>
  626. </Menu.Item>
  627. ))
  628. ) : (
  629. <Menu.Item>
  630. <div
  631. style={{
  632. display: 'flex',
  633. justifyContent: 'center',
  634. alignItems: 'center',
  635. width: '148px',
  636. }}
  637. >
  638. <Empty />
  639. </div>
  640. </Menu.Item>
  641. )}
  642. </Menu>
  643. );
  644. const handleSaveLog = async () => {
  645. const value = await form.submit<SearchTermsUI>();
  646. const value2 = await historyForm.submit<{ alias: string }>();
  647. const response = await service.history.save(`${target}-search`, {
  648. name: value2.alias,
  649. content: JSON.stringify(value),
  650. });
  651. if (response.status === 200) {
  652. onlyMessage('保存成功!');
  653. } else {
  654. onlyMessage('保存失败', 'error');
  655. }
  656. setAliasVisible(!aliasVisible);
  657. };
  658. const resetForm = async (type: boolean) => {
  659. const value = form.values;
  660. if (!expand) {
  661. value.terms1 = [defaultTerms(0), defaultTerms(1), defaultTerms(2)];
  662. value.terms2 = [defaultTerms(3), defaultTerms(4), defaultTerms(5)];
  663. } else {
  664. value.terms1 = [defaultTerms(0)];
  665. value.terms2 = [];
  666. }
  667. setInitParams(value);
  668. await handleSearch(type);
  669. };
  670. const SearchBtn = {
  671. simple: (
  672. <>
  673. {
  674. // @ts-ignore
  675. <Button
  676. icon={<SearchOutlined />}
  677. onClick={() => {
  678. handleSearch(false);
  679. }}
  680. type="primary"
  681. htmlType={'submit'}
  682. >
  683. 搜索
  684. </Button>
  685. }
  686. </>
  687. ),
  688. advance: (
  689. <Dropdown.Button
  690. icon={<SearchOutlined />}
  691. placement={'bottomLeft'}
  692. destroyPopupOnHide
  693. // @ts-ignore
  694. onClick={handleSearch}
  695. visible={logVisible}
  696. onVisibleChange={async (visible) => {
  697. setLogVisible(visible);
  698. if (visible) {
  699. await queryHistory();
  700. }
  701. }}
  702. type="primary"
  703. overlay={historyDom}
  704. htmlType={'submit'}
  705. >
  706. 搜索
  707. </Dropdown.Button>
  708. ),
  709. };
  710. const SaveBtn = (
  711. <Popover
  712. content={
  713. <Form style={{ width: '217px' }} form={historyForm}>
  714. <SchemaField
  715. schema={{
  716. type: 'object',
  717. properties: {
  718. alias: {
  719. 'x-decorator': 'FormItem',
  720. 'x-component': 'Input.TextArea',
  721. 'x-validator': [
  722. {
  723. max: 64,
  724. message: '最多可输入64个字符',
  725. },
  726. {
  727. required: true,
  728. message: '请输入名称',
  729. },
  730. ],
  731. },
  732. },
  733. }}
  734. />
  735. <Button onClick={handleSaveLog} type="primary" className={styles.saveLog}>
  736. 保存
  737. </Button>
  738. </Form>
  739. }
  740. visible={aliasVisible}
  741. onVisibleChange={setAliasVisible}
  742. title="搜索名称"
  743. trigger="click"
  744. >
  745. <Button icon={<SaveOutlined />} block>
  746. {intl.formatMessage({
  747. id: 'pages.data.option.save',
  748. defaultMessage: '保存',
  749. })}
  750. </Button>
  751. </Popover>
  752. );
  753. return (
  754. <Card
  755. bordered={false}
  756. className={styles.container}
  757. style={props.style}
  758. bodyStyle={props.bodyStyle}
  759. >
  760. <Form
  761. form={form}
  762. className={styles.form}
  763. labelCol={4}
  764. wrapperCol={18}
  765. onAutoSubmit={() => (SearchBtn.advance ? handleSearch : handleSearch(false))}
  766. >
  767. <div className={expand && styles.simple}>
  768. <SchemaField schema={expand ? simpleSchema : schema} />
  769. <div className={styles.action} style={{ marginTop: expand ? 0 : -12 }}>
  770. <Space>
  771. {enableSave ? SearchBtn.advance : SearchBtn.simple}
  772. {enableSave && SaveBtn}
  773. <Button
  774. icon={<ReloadOutlined />}
  775. block
  776. onClick={() => {
  777. resetForm(model !== 'simple');
  778. }}
  779. >
  780. 重置
  781. </Button>
  782. </Space>
  783. {model !== 'simple' && (
  784. <div className={classnames(styles.more, !expand ? styles.simple : styles.advance)}>
  785. <Button type="link" onClick={handleExpand}>
  786. 更多筛选
  787. <DoubleRightOutlined style={{ marginLeft: 32 }} rotate={expand ? 90 : -90} />
  788. </Button>
  789. </div>
  790. )}
  791. </div>
  792. </div>
  793. </Form>
  794. </Card>
  795. );
  796. };
  797. export default SearchComponent;