mtable.jsx 12.7 KB
Newer Older
wuhao's avatar
wuhao committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react-hooks/rules-of-hooks */
import React, { useEffect, useRef, useState, memo, useMemo } from 'react';
import { ProTable } from '@ant-design/pro-components';
import Resizecell from './Resizecell';
import { Tooltip } from 'antd';
import { doFetch } from '@/utils/doFetch';
import { useAsyncEffect } from 'ahooks';
import bodyParse from 'query-string';

let handlEmptyChild = (tree = []) => {
  const newtree = tree.map((item) => {
    if (!item.children || item.children.length == 0) {
      item.value = item.key;
      return item;
    } else {
      item.value = item.key;
      return {
        ...item,
        children: handlEmptyChild(item.children),
      };
    }
  });
  return newtree;
};

const Mtable = (props) => {
  const {
TZW's avatar
TZW committed
29
    headerTitle,
wuhao's avatar
wuhao committed
30 31 32 33 34 35 36 37
    actionRef, //表格动作
    formRef, //表单Ref
    rowKey, // key
    columns = [], //columns
    style, //style
    path, //接口地址
    extraparams, //额外参数
    pageSize, //修改默认pageSize
左玲玲's avatar
左玲玲 committed
38
    pagination = true, //分页设置
wuhao's avatar
wuhao committed
39 40 41 42
    x, //横向滚动
    activeTabKey, //激活的tabKey 拖拽表格唯一标识使用 其他情况用不到
    refreshDep, //依赖刷新 (已废弃)
    getDefaultSelected, //存在默认选中向上返回选中值
左玲玲's avatar
左玲玲 committed
43
    resizeable = false,
wuhao's avatar
wuhao committed
44
    dataSource,
TZW's avatar
TZW committed
45
    iscurrent = true,
wuhao's avatar
wuhao committed
46 47 48 49 50 51 52
  } = props;
  const actionRefs = actionRef ?? useRef(),
    formRefs = formRef ?? useRef(),
    ifspagination = pagination == 'false' || pagination === false,
    [size, setsize] = useState('small'),
    [valueColumns, setvalueColumns] = useState({});
  const [columnes, setcolumnes] = useState(columns ?? []);
wuhao's avatar
wuhao committed
53
  const [newparames, setnewparams] = useState({});
wuhao's avatar
wuhao committed
54 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

  //调用接口
  const request = async (params, sort, filter) => {
    if (!path) return;
    let newparams = {
      ...params,
      ...extraparams, //父组件传参
      pageIndex: params.current,
      pageSize: params.pageSize || pageSize,
    };
    delete newparams.current;
    if (ifspagination) {
      delete newparams.pageIndex;
      delete newparams.pageSize;
    }
    const result = await doFetch({ url: path, params: newparams });
    //分页结果
    let data = result?.data?.page?.list,
      success = true,
      total = result?.data?.page?.total;
    //不带分页获取结果
    if (ifspagination) {
      data = result?.data?.dataList;
      total = result?.data?.dataList?.length;
    }
    //存在默认选中向上返回选中值
    getDefaultSelected && getDefaultSelected(result?.data);
    return {
      data,
      success,
      total,
    };
  };
  //更新 columns
  useEffect(() => {
    setcolumnes((s) => {
      return columns.map((item, index) => {
        let it = { ...item };
        let itemwidth = valueColumns[it.key]?.width
          ? valueColumns[it.key].width
          : it.width
TZW's avatar
TZW committed
95 96 97 98
          ? it.width
          : resizeable
          ? 160
          : 'auto';
wuhao's avatar
wuhao committed
99 100
        let options = {},
          faoptopns = it?.searchOptions ?? it?.options;
wuhao's avatar
wuhao committed
101
        if (['select', 'treeSelect', 'radio', 'checkbox', 'cascader'].includes(it?.valueType)) {
wuhao's avatar
wuhao committed
102
          if (Array.isArray(faoptopns)) {
wuhao's avatar
wuhao committed
103 104
            options = {
              fieldProps: {
左玲玲's avatar
左玲玲 committed
105
                ...it?.fieldProps,
wuhao's avatar
wuhao committed
106
                options: [...faoptopns],
wuhao's avatar
wuhao committed
107 108
              },
            };
wuhao's avatar
wuhao committed
109
          } else if (faoptopns) {
wuhao's avatar
wuhao committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
            options = {
              request: async (params) => {
                let list = await doFetch({ url: it?.options?.path, params: it?.options?.params });
                const res = list.data.dataList;
                return it.valueType == 'treeSelect' ? handlEmptyChild(res) : res;
              },
            };
          }
        }
        if (it.valueType == 'option') {
          options = {
            key: 'option',
            dataIndex: 'option',
            fixed: 'right',
          };
        }
        if (!it.render) {
          options = {
            ...options,
            render: (text, row) => {
              return (
                <Tooltip title={row[it.dataIndex]} placement="topLeft">
                  <span className="table-cell">{row[it.dataIndex] ?? '-'}</span>
                </Tooltip>
              );
            },
          };
        }
        options = {
          ...options,
          width: itemwidth,
        };

        delete it.formItemProps;
        return {
          ...it,
          ...options,
          onHeaderCell: (column) => ({
            width: column.width ?? itemwidth,
            onResize: handleResize(index),
            onResizeStop: handleResizeStop(index),
          }),
        };
      });
    });
  }, [valueColumns]);

  let columncs = useMemo(() => {
    if (resizeable) return;
    return columns.map((item, index) => {
      let it = { ...item };
      let itemwidth = it.width ? it.width : resizeable ? 160 : 'auto';
wuhao's avatar
wuhao committed
162 163
      let options = {},
        faoptopns = it?.searchOptions ?? it?.options;
wuhao's avatar
wuhao committed
164
      if (['select', 'treeSelect', 'radio', 'checkbox', 'cascader'].includes(it?.valueType)) {
wuhao's avatar
wuhao committed
165
        if (Array.isArray(faoptopns)) {
wuhao's avatar
wuhao committed
166 167
          options = {
            fieldProps: {
左玲玲's avatar
左玲玲 committed
168
              ...it?.fieldProps,
wuhao's avatar
wuhao committed
169
              options: [...faoptopns],
wuhao's avatar
wuhao committed
170 171
            },
          };
wuhao's avatar
wuhao committed
172
        } else if (faoptopns) {
wuhao's avatar
wuhao committed
173
          options = {
wuhao's avatar
wuhao committed
174
            params: newparames,
wuhao's avatar
wuhao committed
175
            request: async (params) => {
wuhao's avatar
wuhao committed
176
              if (Object.keys(it?.options).includes('linkParams')) {
wuhao's avatar
wuhao committed
177 178 179 180 181 182 183
                let resparams = {},
                  linkParams = it?.options?.linkParams ?? {};
                for (let i in linkParams) {
                  let paramsKey = !linkParams[i] ? i : linkParams[i];
                  resparams[paramsKey] = newparames[i];
                }
                let list = await doFetch({ url: it?.options?.path, params: resparams });
wuhao's avatar
wuhao committed
184 185 186 187 188 189 190
                const res = list.data.dataList;
                return it.valueType == 'treeSelect' ? handlEmptyChild(res) : res;
              } else {
                let list = await doFetch({ url: it?.options?.path, params: it?.options?.params });
                const res = list.data.dataList;
                return it.valueType == 'treeSelect' ? handlEmptyChild(res) : res;
              }
wuhao's avatar
wuhao committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
            },
          };
        }
      }
      if (it.valueType == 'option') {
        options = {
          key: 'option',
          dataIndex: 'option',
          fixed: 'right',
        };
      }
      if (!it.render) {
        options = {
          ...options,
          render: (text, row) => {
            return (
              <Tooltip title={row[it.dataIndex]} placement="topLeft">
                <span className="table-cell">{row[it.dataIndex] ?? '-'}</span>
              </Tooltip>
            );
          },
        };
      }

      options = {
        ...options,
        width: itemwidth,
      };

      delete it.formItemProps;
      return {
        ...it,
        ...options,
TZW's avatar
TZW committed
224 225
        key: it.searchKey ?? it?.key,
        valueType: it.searchValueType ?? it?.valueType,
wuhao's avatar
wuhao committed
226 227
      };
    });
wuhao's avatar
wuhao committed
228
  }, [columns, newparames]);
wuhao's avatar
wuhao committed
229 230 231 232

  //初始化操作数据
  const initDrage = async () => {
    if (!path) return;
TZW's avatar
TZW committed
233 234 235 236 237 238
    let res = await doFetch({
      url: '/ngic-base-business/paFieldScene/queryContro',
      params: {
        sceneMark: activeTabKey ? path + activeTabKey : path,
      },
    });
wuhao's avatar
wuhao committed
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    if (res.code == '0000') {
      //datalist:接口返回状态
      let datalist = {};
      res?.data?.dataList &&
        res.data.dataList.map((it) => {
          const { fieldKey, fieldWidth, fieldOrder, fieldFixed, fieldShow } = it ?? {};
          datalist[fieldKey] = {
            width: fieldWidth,
            order: fieldOrder,
            fixed: fieldKey == 'option' || fieldKey == 'option_dataindex' ? 'right' : fieldFixed,
            show: fieldShow,
          };
        });
      //allcol 默认状态设置 valueColumns 为columns全列设置
      let allcol = {};
      columns.map((it, i) => {
        if (it.valueType == 'option') {
          allcol.option = {
            order: columns.length - 1,
            show: true,
            fixed: 'right',
            ...datalist.option,
          };
        } else {
          allcol[it.key] = {
            order: i,
            show: true,
            ...datalist[it.key],
          };
        }
      });
      setvalueColumns(allcol);
    }
  };

  //调用重新渲染表格
  useAsyncEffect(async () => {
    if (resizeable) {
      await initDrage();
    }
TZW's avatar
TZW committed
279 280 281
    iscurrent && actionRefs?.current?.reload();
    // actionRefs?.current?.reset();
  }, [columns, extraparams, path, activeTabKey, refreshDep, iscurrent]);
wuhao's avatar
wuhao committed
282 283 284 285

  //缩放表格
  const handleResize =
    (index) =>
TZW's avatar
TZW committed
286 287 288 289 290 291 292 293 294 295 296
    (e, { size }) => {
      e.stopImmediatePropagation();
      setcolumnes((s) => {
        const nextColumns = [...s];
        nextColumns[index] = {
          ...nextColumns[index],
          width: size.width,
        };
        return nextColumns;
      });
    };
wuhao's avatar
wuhao committed
297 298 299 300

  //更新表格缩放
  const handleResizeStop =
    (index) =>
TZW's avatar
TZW committed
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    (e, { size }) => {
      e.stopImmediatePropagation();
      let submitdata = { ...valueColumns } ?? {},
        curkey = Object.keys(submitdata)[index];
      submitdata[curkey].width = parseInt(size.width);
      setvalueColumns(submitdata);
      doFetch({
        url: '/ngic-base-business/paFieldScene/save',
        params: {
          sceneMark: activeTabKey ? path + activeTabKey : path,
          controList: Object.keys(submitdata).map((it, i) => {
            return {
              fieldKey: it,
              fieldWidth: i == index ? parseInt(size.width) : submitdata[it].width,
              fieldOrder: submitdata[it].order,
              fieldFixed: submitdata[it].fixed,
              fieldShow: submitdata[it].show,
            };
          }),
        },
      });
    };
wuhao's avatar
wuhao committed
323 324 325

  const components = resizeable
    ? {
TZW's avatar
TZW committed
326 327 328 329
        components: {
          header: {
            cell: Resizecell,
          },
wuhao's avatar
wuhao committed
330
        },
TZW's avatar
TZW committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
        columnsState: {
          value: valueColumns,
          onChange: (val, state) => {
            setvalueColumns((s) => {
              let submitdata = {
                ...s,
                ...val,
              };
              doFetch({
                url: '/ngic-base-business/paFieldScene/save',
                params: {
                  sceneMark: activeTabKey ? path + activeTabKey : path,
                  controList: Object.keys(submitdata).map((it) => {
                    return {
                      fieldKey: it,
                      fieldWidth: submitdata[it].width,
                      fieldOrder: submitdata[it].order,
                      fieldFixed: submitdata[it].fixed,
                      fieldShow: submitdata[it].show,
                    };
                  }),
                },
              });
              return submitdata;
wuhao's avatar
wuhao committed
355
            });
TZW's avatar
TZW committed
356
          },
wuhao's avatar
wuhao committed
357
        },
TZW's avatar
TZW committed
358
      }
wuhao's avatar
wuhao committed
359
    : {};
wuhao's avatar
wuhao committed
360 361 362

  const datas = dataSource ? { dataSource, toolBarRender: false } : { request };

wuhao's avatar
wuhao committed
363 364 365 366
  return (
    <ProTable
      {...props}
      {...components}
wuhao's avatar
wuhao committed
367
      {...datas}
wuhao's avatar
wuhao committed
368 369
      size={size}
      onSubmit={(params) => {
wuhao's avatar
wuhao committed
370 371 372 373 374 375 376 377 378 379 380
        let newparams = {},
          curkey = Object.keys(params)[Object.keys(params).length - 1],
          curval = Object.values(params)[Object.keys(params).length - 1];
        columns
          ?.filter((it) => !(it.search === false || it.hideInSearch === true))
          .map((it, i) => {
            let { linkParams } = it?.options ?? {};
            if (linkParams && Object.keys(linkParams).includes(curkey)) {
              for (let dataindex in linkParams) {
                newparams[dataindex] = formRefs?.current?.getFieldValue?.(dataindex);
              }
wuhao's avatar
wuhao committed
381
            }
wuhao's avatar
wuhao committed
382 383 384 385 386 387 388
          });
        if (Object.keys(newparams).length > 0) {
          setnewparams((s) => ({
            ...s,
            ...newparams,
          }));
        }
wuhao's avatar
wuhao committed
389 390 391 392 393 394 395
      }}
      onSizeChange={(size) => {
        localStorage.setItem('size', size); //设置全局表格规格缓存
        setsize(size);
      }}
      columns={
        resizeable
wuhao's avatar
wuhao committed
396 397
          ? columnes?.filter?.((it) => ['split', 'nosubmit'].indexOf(it.valueType) == -1) ?? []
          : columncs?.filter?.((it) => ['split', 'nosubmit'].indexOf(it.valueType) == -1) ?? []
wuhao's avatar
wuhao committed
398 399 400 401 402 403 404 405 406
      }
      style={style || {}}
      actionRef={actionRefs}
      formRef={formRefs}
      rowKey={rowKey ?? 'id'} //表格每行数据的key
      dateFormatter="string"
      scroll={
        x
          ? {
TZW's avatar
TZW committed
407 408
              x: x,
            }
wuhao's avatar
wuhao committed
409 410
          : {}
      }
wuhao's avatar
wuhao committed
411 412 413
      pagination={
        pagination
          ? {
TZW's avatar
TZW committed
414 415 416 417 418 419
              showTotal: (total, range) => <span>{total}</span>,
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: [5, 10, 15, 30, 50, 100, 200],
              defaultPageSize: pageSize || 15,
            }
wuhao's avatar
wuhao committed
420 421
          : false
      }
wuhao's avatar
wuhao committed
422 423
      search={{
        filterType: 'light', //轻量模式
wuhao's avatar
wuhao committed
424
        placement: 'bottomLeft',
wuhao's avatar
wuhao committed
425 426 427 428 429 430
      }}
    />
  );
};

export default memo(Mtable);