index.js 17.3 KB
Newer Older
田翔's avatar
田翔 committed
1
import React, { useMemo, useState, forwardRef, useImperativeHandle, useRef } from 'react'
2
import { Table, Button, Popconfirm, Input, Space, Tag, Popover, Checkbox, Form } from 'antd'
3 4
import { TweenOneGroup } from 'rc-tween-one'
import styles from './index.less'
田翔's avatar
田翔 committed
5
import { SearchOutlined, FormOutlined } from '@ant-design/icons'
6
import * as icons from '@ant-design/icons'
7
import Text from './components/Text'
8
import ResizeableTitle from './components/ResizeableTitle'
田翔's avatar
田翔 committed
9 10
import FileView from './components/FileView'
import CoordView from './components/CoordView'
田翔's avatar
田翔 committed
11
import SelectView from './components/SelectView'
12
import ValueEdit from './components/ValueEdit'
田翔's avatar
田翔 committed
13
import IconPack from '../../../components/IconPack'
14
import { isObject, isArray, getFieldInfo } from '../../../../utils'
田翔's avatar
田翔 committed
15

16 17
const iconList = Object.keys(icons).filter((item) => typeof icons[item] === 'object')

田翔's avatar
田翔 committed
18 19 20 21
const TablePack = (props, ref) => {

  useImperativeHandle(ref, () => ({
    setFilteredInfo,
22
    setSortedInfo,
23
    fileColumns,
田翔's avatar
田翔 committed
24
  }))
田翔's avatar
田翔 committed
25

26
  const { notUse, config, fieldList, loading, dataSource, sourceChange, rowSelection, onRow, tableChange, btnsClick, isEdit } = props
田翔's avatar
田翔 committed
27
  const { accountFieids, webShowFieldGroup, formJson, parent } = config
28
  const [fieldResize, setFieldResize] = useState({})
田翔's avatar
田翔 committed
29
  const [filteredInfo, setFilteredInfo] = useState({})
30
  const [sortedInfo, setSortedInfo] = useState({})
田翔's avatar
田翔 committed
31 32
  const [open, setOpen] = useState(false)
  const [checks, setChecks] = useState([])
田翔's avatar
田翔 committed
33
  const searchInput = useRef(null)
34
  const [form] = Form.useForm()
田翔's avatar
田翔 committed
35

36 37 38 39 40 41 42 43 44 45 46 47
  const filtered = useMemo(() => {
    let array = []
    if (isObject(filteredInfo)) {
      Object.keys(filteredInfo).forEach(v => {
        if (Array.isArray(filteredInfo[v])) {
          array.push({ filterName: v, filterValue: filteredInfo[v].join(',') })
        }
      })
    }
    return array
  }, [filteredInfo])

48 49
  //台账列表、台账选择器表头
  const getColumnProps = (json, v) => {
50
    const { fieldName, columnWidth, isSort, accurateSearch, alignment } = v
51
    const { widget, sourceType, options, addonAfter } = json?.[fieldName] || {}
52
    let searchProps = {}
53
    // console.log('json?.[fieldName]', json?.[fieldName])
田翔's avatar
田翔 committed
54
    if (accurateSearch) {
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
      if (['CheckBox', 'ComboBox', 'RadioButton'].includes(widget)) {
        if (sourceType === '手动输入') {
          searchProps = {
            filters: options.map(v => { return { text: v.value, value: v.value, } }),
          }
        }
      } else {
        searchProps = {
          filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => {
            return (
              <div
                style={{ padding: 8 }}
                onKeyDown={(e) => e.stopPropagation()}
              >
                <Input
                  placeholder={`搜索 ${fieldName}`}
                  value={selectedKeys[0]}
                  onChange={e => {
                    setSelectedKeys(e.target.value ? [e.target.value] : [])
                  }}
                  onPressEnter={() => {
                    confirm({ closeDropdown: true })
                  }}
                  style={{
                    marginBottom: 8,
                    display: 'block',
                    width: '280px',
                  }}
                />
                <Space>
                  <Button
                    type="primary"
                    onClick={() => {
                      confirm({ closeDropdown: true })
                    }}
                    icon={<SearchOutlined />}
                    size="small"
                    style={{ width: 90 }}
                  >
                    搜索
                  </Button>
                  <Button
                    onClick={() => {
                      clearFilters()
                      confirm({ closeDropdown: true })
                    }}
                    size="small"
                    style={{ width: 90 }}
                  >
                    重置
                  </Button>
                </Space>
              </div>
            )
          },
          filterIcon: (filtered) => (
            <SearchOutlined
              style={{
                color: filtered ? '#1890ff' : undefined,
              }}
            />
          ),
        }
      }
    }
    return {
121 122 123 124 125 126
      title: (
        <div className={styles.headerTitle}>
          {json[fieldName]?.title || fieldName}
          {addonAfter && !iconList.includes(addonAfter) ? `(${addonAfter})` : null}
        </div>
      ),
127 128 129 130 131 132 133
      dataIndex: fieldName,
      width: fieldResize[fieldName] || columnWidth || 120,
      ellipsis: true,
      sorter: Boolean(isSort),
      sortOrder: sortedInfo.field === fieldName ? sortedInfo.order : null,
      filteredValue: filteredInfo[fieldName] || null,
      ...searchProps,
134
      align: alignment === '中' ? 'center' : (alignment === '右' ? 'right' : 'left'),
135 136 137 138 139 140
      onHeaderCell: (column) => ({
        width: column.width,
        onResize: (e, props) => {
          setFieldResize({ ...fieldResize, [fieldName]: props?.size?.width })
        },
      }),
141
      render: (value, record) => {
142 143 144 145 146 147 148 149 150 151
        let props = { ...json[fieldName], value }
        if (widget === 'FileUpload') {
          return <FileView {...props} />
        }
        if (['Coordinate', 'Device', 'DrawPath', 'DrawArea'].includes(widget)) {
          return <CoordView {...props} />
        }
        if (['RadioButton', 'CheckBox'].includes(widget)) {
          return <SelectView {...props} />
        }
152
        return <Text align={alignment} text={value} />
153 154 155 156 157
      },
    }
  }

  //关联表单表头
158
  const getRelevanceColumnProps = ({ json, field, isEdit, autoArray }) => {
田翔's avatar
田翔 committed
159
    const { fieldName, columnWidth, isSort, accurateSearch, alignment } = field
160 161
    const { widget } = json?.[fieldName] || {}
    let searchProps = {}
田翔's avatar
田翔 committed
162
    if (accurateSearch) {
163 164
      searchProps = {
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
165 166 167 168 169
          <div
            style={{ padding: 8 }}
            onKeyDown={(e) => e.stopPropagation()}
          >
            <Input
170 171
              ref={searchInput}
              placeholder={`Search ${fieldName}`}
172
              value={selectedKeys[0]}
173
              onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
174
              onPressEnter={() => {
175
                confirm();
田翔's avatar
田翔 committed
176
              }}
177 178 179 180 181 182 183 184 185
              style={{
                marginBottom: 8,
                display: 'block',
              }}
            />
            <Space>
              <Button
                type="primary"
                onClick={() => {
186
                  confirm();
187 188 189
                }}
                icon={<SearchOutlined />}
                size="small"
190 191 192
                style={{
                  width: 90,
                }}
193 194 195 196 197
              >
                搜索
              </Button>
              <Button
                onClick={() => {
198 199
                  clearFilters();
                  confirm();
200 201
                }}
                size="small"
202 203 204
                style={{
                  width: 90,
                }}
205 206 207 208 209
              >
                重置
              </Button>
            </Space>
          </div>
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
        ),
        filterIcon: (filtered) => (
          <SearchOutlined
            style={{
              color: filtered ? '#1890ff' : undefined,
            }}
          />
        ),
        onFilter: (value, record) =>
          record[fieldName].toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownOpenChange: (visible) => {
          if (visible) {
            setTimeout(() => searchInput.current?.select(), 100);
          }
        },
225 226 227
      }
    }
    return {
228 229 230
      title: json[fieldName]?.title || fieldName,
      dataIndex: fieldName,
      width: fieldResize[fieldName] || columnWidth || 120,
231
      ellipsis: true,
232 233
      sorter: Boolean(isSort) ? (a, b) => a[fieldName] - b[fieldName] : false,
      filteredValue: filteredInfo[fieldName] || null,
234
      ...searchProps,
田翔's avatar
田翔 committed
235
      align: alignment === '中' ? 'center' : (alignment === '右' ? 'right' : 'left'),
236 237 238
      onHeaderCell: (column) => ({
        width: column.width,
        onResize: (e, props) => {
239
          setFieldResize({ ...fieldResize, [fieldName]: props?.size?.width })
240 241
        },
      }),
242
      render: (value, record) => {
243
        let props = { ...json[fieldName], fieldName, value, autoArray, record: { ...record } }
244
        if (isEdit && !notUse?.includes('edit')) {
245
          return (
246 247
            <ValueEdit
              {...props}
248 249 250 251 252 253
              onChange={({ fieldName, fieldValue }) => {
                btnsClick({ type: '变化', row: { ...record, [fieldName]: fieldValue } })
              }}
              otherChange={(otherRow) => {
                btnsClick({ type: '变化', row: { ...record, ...otherRow } })
              }}
254 255
              value={value}
            />
256 257
          )
        } else {
258
          if (['FileUpload'].includes(widget)) {
259 260 261 262 263 264 265 266 267
            return <FileView {...props} />
          }
          if (['Coordinate', 'Device', 'DrawPath', 'DrawArea'].includes(widget)) {
            return <CoordView {...props} />
          }
          if (['RadioButton', 'CheckBox'].includes(widget)) {
            return <SelectView {...props} />
          }
          return <Text text={value} />
268
        }
269
      },
270
    }
271
  }
田翔's avatar
田翔 committed
272

田翔's avatar
田翔 committed
273
  const btns = useMemo(() => {
274
    let array = []
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    //表格可编辑
    if (isEdit) {
      if (!notUse?.includes('del')) {
        array.push({ title: '删除', icon: <IconPack.ShanChu /> })
      }
    } else {
      if (!notUse?.includes('read')) {
        array.push({ title: '详情', icon: <IconPack.XiangQing />, })
      }
      if (!notUse?.includes('edit')) {
        array.push({ title: '编辑', icon: <IconPack.BianJi /> })
      }
      if (!notUse?.includes('del')) {
        array.push({ title: '删除', icon: <IconPack.ShanChu /> })
      }
290
    }
291

292
    return array
293
  }, [notUse, isEdit])
田翔's avatar
田翔 committed
294

田翔's avatar
田翔 committed
295 296 297 298 299
  const checkChange = (values) => {
    setChecks(values)
  }

  const showField = useMemo(() => {
300
    let showField = []
301 302 303 304 305 306 307 308 309 310 311 312
    accountFieids.forEach(v => {
      if (isArray(fieldList)) {
        if (fieldList.includes(v.fieldName)) {
          showField.push(v)
        }
      } else {
        if (v.webDisplay) {
          showField.push(v)
        }
      }
    })
    setChecks(showField.map(v => v.fieldName))
田翔's avatar
田翔 committed
313
    return showField
314
  }, [accountFieids, fieldList])
田翔's avatar
田翔 committed
315 316

  const fileColumns = useMemo(() => {
317
    let json = getFieldInfo(formJson)
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
    let autoArray = []
    Object.keys(json).forEach(key => {
      let item = json[key]
      if (item.widget === 'NumberInput') {
        if (item.calculateRule) {
          let parmas = {
            fields: item?.rules[0]?.fields,
            tableName: item.tableNameParent,
            filedFormulas: [
              {
                fieldName: key,
                formula: item.calculateRule
              }
            ]
          }
          autoArray.push(parmas)
        }
      }
    })
田翔's avatar
田翔 committed
337
    let array = []
338
    showField.forEach((v, i) => {
339
      if (parent === '关联表单') {
340 341
        // array.push(getRelevanceColumnProps(json, v, isEdit))
        array.push(getRelevanceColumnProps({ json, field: v, isEdit, autoArray }))
342 343 344
      } else {
        array.push(getColumnProps(json, v))
      }
田翔's avatar
田翔 committed
345 346
    })
    return array
347
  }, [parent, formJson, showField, fieldResize, filteredInfo, sortedInfo, isEdit, dataSource])
田翔's avatar
田翔 committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

  const showColumns = useMemo(() => {
    return fileColumns.filter(v => checks.includes(v.dataIndex))
  }, [checks, fileColumns])

  const content = (
    <div>
      <Checkbox.Group
        value={checks}
        style={{ width: '100%' }}
        onChange={checkChange}
      >
        {
          fileColumns.map(v => {
            return (
              <div key={v.dataIndex}>
                <Checkbox value={v.dataIndex}>{v.title}</Checkbox>
              </div>
            )
          })
        }
      </Checkbox.Group>
    </div>
  )
田翔's avatar
田翔 committed
372 373

  const columns = useMemo(() => {
田翔's avatar
田翔 committed
374
    let columns = [
田翔's avatar
田翔 committed
375 376 377 378
      {
        title: '序号',
        width: 50,
        align: 'center',
379 380
        filteredValue: null,
        render: (_, r, i) => i + 1
田翔's avatar
田翔 committed
381
      },
田翔's avatar
田翔 committed
382
      ...showColumns,
383 384 385 386
    ]
    if (btns.length) {
      columns.push(
        {
387
          title: (
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
            <div className={styles.operation}>
              <span>操作</span>
              <span className={styles.operationSpan}>
                <Popover
                  placement='bottomRight'
                  title={
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <div>列配置</div>
                      <Button size='small' type="link" onClick={() => setOpen(false)}>确定</Button>
                    </div>
                  }
                  trigger='click'
                  open={open}
                  content={content}
                  onOpenChange={(value) => {
                    setOpen(value)
                  }}
                  arrowPointAtCenter
                >
                  {
                    fileColumns.length ? <FormOutlined /> : null
                  }
                </Popover>
              </span>
            </div>
          ),
414
          width: btns.length * 35 + 30,
415 416 417 418 419 420
          align: 'center',
          filteredValue: null,
          fixed: 'right',
          render: (r) => {
            return (
              <div style={{ display: 'flex', justifyContent: 'center' }}>
421
                {
422
                  btns.map(v => {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
                    if (v.title === '删除') {
                      return (
                        <Popconfirm
                          key={v.title}
                          title='确定要删除数据吗?'
                          onConfirm={() => btnsClick({ type: v.title, row: r })}
                          okText='确定'
                          cancelText='取消'
                        >
                          <Button
                            type='link'
                            title='删除'
                            style={{ padding: '0 7px' }}
                            icon={v.icon}
                          />
                        </Popconfirm>
                      )
                    }
田翔's avatar
田翔 committed
441
                    return (
442
                      <Button
田翔's avatar
田翔 committed
443
                        key={v.title}
444 445 446 447 448
                        type='link'
                        title={v.title}
                        icon={v.icon}
                        style={{ padding: '0 7px' }}
                        onClick={() => btnsClick({ type: v.title, row: r })}
田翔's avatar
田翔 committed
449
                      >
450
                      </Button>
田翔's avatar
田翔 committed
451
                    )
452 453 454 455 456
                  })
                }
              </div>
            )
          }
田翔's avatar
田翔 committed
457
        }
458 459
      )
    }
田翔's avatar
田翔 committed
460 461 462 463
    if (parent === '台账选择器') {
      return fileColumns
    }
    return columns
464
  }, [parent, btns, dataSource, fileColumns, checks, open])
田翔's avatar
田翔 committed
465

466 467
  const onChange = (page, filters, sorter) => {
    setFilteredInfo(filters)
468
    setSortedInfo(sorter)
469
    tableChange?.(page, filters, sorter)
470 471
  }

472 473 474 475 476 477 478 479 480 481 482
  const closeTag = (e, { filterName, filterValue }) => {
    e.preventDefault()
    let filtered = {}
    for (let key in filteredInfo) {
      if (key === filterName) {
        filtered[key] = null
      } else {
        filtered[key] = filteredInfo[key]
      }
    }
    setFilteredInfo(filtered)
483
    tableChange?.({}, filtered, sortedInfo)
484 485
  }

田翔's avatar
田翔 committed
486
  return (
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    <div className={styles.tablePack} style={{ paddingTop: filtered.length ? '30px' : '10px' }}>
      {
        filtered.length ? (
          <div className={styles.condition}>
            <TweenOneGroup
              enter={{
                scale: 0.8,
                opacity: 0,
                type: 'from',
                duration: 200,
              }}
              onEnd={(e) => {
                if (e.type === 'appear' || e.type === 'enter') {
                  e.target.style = 'display: inline-block';
                }
              }}
              leave={{
                opacity: 0,
                width: 0,
                scale: 0,
                duration: 200,
              }}
              appear={false}
            >
              {
                filtered.map(v => {
                  return (
                    <span
                      key={v.filterName}
                      style={{ display: 'inline-block' }}
                    >
                      <Tag
519
                        color='blue'
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
                        closable
                        onClose={(e) => closeTag(e, v)}
                      >
                        <span>{v.filterName}</span>
                        <span style={{ padding: '0 3px' }}>:</span>
                        <span>{v.filterValue}</span>
                      </Tag>
                    </span>
                  )
                })
              }
            </TweenOneGroup>
          </div>
        ) : null
      }
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
      <Form form={form} component={false}>
        <Table
          size='small'
          rowKey='ID'
          bordered
          loading={loading}
          columns={columns}
          dataSource={dataSource}
          rowSelection={rowSelection}
          onRow={onRow}
          pagination={parent === '关联表单' ? { total: dataSource.length, showTotal: (value) => `总计 ${value} 条` } : false}
          scroll={{ x: '100%', y: 'calc(100% - 40px)' }}
          onChange={onChange}
          components={{
            header: {
              cell: ResizeableTitle
            },
          }}
        />
      </Form>
555
    </div>
田翔's avatar
田翔 committed
556 557 558 559
  )

}

田翔's avatar
田翔 committed
560
export default forwardRef(TablePack)