mtable.jsx 12.8 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,
左玲玲's avatar
左玲玲 committed
46 47
    toolBarRender = false,
    dataSourceFieldsChange
wuhao's avatar
wuhao committed
48 49 50 51 52 53 54
  } = 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
55
  const [newparames, setnewparams] = useState({});
wuhao's avatar
wuhao committed
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

  //调用接口
  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
左玲玲's avatar
左玲玲 committed
97 98 99 100
            ? it.width
            : resizeable
              ? 160
              : 'auto';
wuhao's avatar
wuhao committed
101 102
        let options = {},
          faoptopns = it?.searchOptions ?? it?.options;
wuhao's avatar
wuhao committed
103
        if (['select', 'treeSelect', 'radio', 'checkbox', 'cascader'].includes(it?.valueType)) {
wuhao's avatar
wuhao committed
104
          if (Array.isArray(faoptopns)) {
wuhao's avatar
wuhao committed
105 106
            options = {
              fieldProps: {
左玲玲's avatar
左玲玲 committed
107
                ...it?.fieldProps,
wuhao's avatar
wuhao committed
108
                options: [...faoptopns],
wuhao's avatar
wuhao committed
109 110
              },
            };
wuhao's avatar
wuhao committed
111
          } else if (faoptopns) {
wuhao's avatar
wuhao committed
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 162 163
            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
164 165
      let options = {},
        faoptopns = it?.searchOptions ?? it?.options;
wuhao's avatar
wuhao committed
166
      if (['select', 'treeSelect', 'radio', 'checkbox', 'cascader'].includes(it?.valueType)) {
wuhao's avatar
wuhao committed
167
        if (Array.isArray(faoptopns)) {
wuhao's avatar
wuhao committed
168 169
          options = {
            fieldProps: {
左玲玲's avatar
左玲玲 committed
170
              ...it?.fieldProps,
wuhao's avatar
wuhao committed
171
              options: [...faoptopns],
wuhao's avatar
wuhao committed
172 173
            },
          };
wuhao's avatar
wuhao committed
174
        } else if (faoptopns) {
wuhao's avatar
wuhao committed
175
          options = {
wuhao's avatar
wuhao committed
176
            params: newparames,
wuhao's avatar
wuhao committed
177
            request: async (params) => {
wuhao's avatar
wuhao committed
178
              if (Object.keys(it?.options).includes('linkParams')) {
wuhao's avatar
wuhao committed
179 180 181 182 183 184 185
                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
186 187 188 189 190 191 192
                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
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 224 225
            },
          };
        }
      }
      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
226 227
        key: it.searchKey ?? it?.key,
        valueType: it.searchValueType ?? it?.valueType,
wuhao's avatar
wuhao committed
228 229
      };
    });
wuhao's avatar
wuhao committed
230
  }, [columns, newparames]);
wuhao's avatar
wuhao committed
231 232 233 234

  //初始化操作数据
  const initDrage = async () => {
    if (!path) return;
TZW's avatar
TZW committed
235 236 237 238 239 240
    let res = await doFetch({
      url: '/ngic-base-business/paFieldScene/queryContro',
      params: {
        sceneMark: activeTabKey ? path + activeTabKey : path,
      },
    });
wuhao's avatar
wuhao committed
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 279 280
    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
281 282 283
    iscurrent && actionRefs?.current?.reload();
    // actionRefs?.current?.reset();
  }, [columns, extraparams, path, activeTabKey, refreshDep, iscurrent]);
wuhao's avatar
wuhao committed
284 285 286 287

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

  //更新表格缩放
  const handleResizeStop =
    (index) =>
左玲玲's avatar
左玲玲 committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
      (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
325 326 327

  const components = resizeable
    ? {
左玲玲's avatar
左玲玲 committed
328 329 330
      components: {
        header: {
          cell: Resizecell,
wuhao's avatar
wuhao committed
331
        },
左玲玲's avatar
左玲玲 committed
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,
                  };
                }),
              },
wuhao's avatar
wuhao committed
355
            });
左玲玲's avatar
左玲玲 committed
356 357
            return submitdata;
          });
wuhao's avatar
wuhao committed
358
        },
左玲玲's avatar
左玲玲 committed
359 360
      },
    }
wuhao's avatar
wuhao committed
361
    : {};
wuhao's avatar
wuhao committed
362

左玲玲's avatar
左玲玲 committed
363
  const datas = dataSource ? { dataSource, toolBarRender: toolBarRender == false ? false : () => { } } : { request };
wuhao's avatar
wuhao committed
364 365 366 367
  return (
    <ProTable
      {...props}
      {...components}
wuhao's avatar
wuhao committed
368
      {...datas}
wuhao's avatar
wuhao committed
369 370
      size={size}
      onSubmit={(params) => {
wuhao's avatar
wuhao committed
371 372 373 374 375 376 377 378 379 380 381
        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
382
            }
wuhao's avatar
wuhao committed
383 384 385 386 387 388 389
          });
        if (Object.keys(newparams).length > 0) {
          setnewparams((s) => ({
            ...s,
            ...newparams,
          }));
        }
左玲玲's avatar
左玲玲 committed
390
        dataSourceFieldsChange && dataSourceFieldsChange(params)
wuhao's avatar
wuhao committed
391 392 393 394 395 396 397
      }}
      onSizeChange={(size) => {
        localStorage.setItem('size', size); //设置全局表格规格缓存
        setsize(size);
      }}
      columns={
        resizeable
wuhao's avatar
wuhao committed
398 399
          ? columnes?.filter?.((it) => ['split', 'nosubmit'].indexOf(it.valueType) == -1) ?? []
          : columncs?.filter?.((it) => ['split', 'nosubmit'].indexOf(it.valueType) == -1) ?? []
wuhao's avatar
wuhao committed
400 401 402 403 404 405 406 407 408
      }
      style={style || {}}
      actionRef={actionRefs}
      formRef={formRefs}
      rowKey={rowKey ?? 'id'} //表格每行数据的key
      dateFormatter="string"
      scroll={
        x
          ? {
左玲玲's avatar
左玲玲 committed
409 410
            x: x,
          }
wuhao's avatar
wuhao committed
411 412
          : {}
      }
wuhao's avatar
wuhao committed
413 414 415
      pagination={
        pagination
          ? {
左玲玲's avatar
左玲玲 committed
416 417 418 419 420 421
            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
422 423
          : false
      }
wuhao's avatar
wuhao committed
424 425
      search={{
        filterType: 'light', //轻量模式
wuhao's avatar
wuhao committed
426
        placement: 'bottomLeft',
wuhao's avatar
wuhao committed
427 428 429 430 431 432
      }}
    />
  );
};

export default memo(Mtable);