mtable.jsx 9.91 KB
Newer Older
wuhao's avatar
wuhao committed
1
import React, { useEffect, useRef, useState, memo } from "react";
wuhao's avatar
wuhao committed
2
import { ProTable } from "@ant-design/pro-components";
wuhao's avatar
wuhao committed
3 4 5
import Resizecell from "./Resizecell";
import { Tooltip } from "antd";
import { doFetch } from "@/utils/doFetch";
wuhao's avatar
wuhao committed
6
import { useAsyncEffect } from "ahooks";
wuhao's avatar
wuhao committed
7
import bodyParse from "@/utils/bodyParse";
krysent's avatar
krysent committed
8
import { history } from "umi";
wuhao's avatar
wuhao committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22
const Mtable = (props) => {
  const {
    actionRef, //表格动作
    formRef, //表单Ref
    rowKey, // key
    columns, //columns
    style, //style
    path, //接口地址
    extraparams, //额外参数
    pageSize, //修改默认pageSize
    pagination, //分页设置
    x, //横向滚动
    activeTabKey, //激活的tabKey 拖拽表格唯一标识使用 其他情况用不到
    refreshDep, //依赖刷新 (已废弃)
wuhao's avatar
wuhao committed
23
    getDefaultSelected, //存在默认选中向上返回选中值
wuhao's avatar
wuhao committed
24
  } = props;
wuhao's avatar
wuhao committed
25

krysent's avatar
krysent committed
26 27


wuhao's avatar
wuhao committed
28 29 30 31
  const actionRefs = actionRef ?? useRef(),
    formRefs = formRef ?? useRef(),
    ifspagination = pagination == "false" || pagination === false,
    [size, setsize] = useState("small"),
wuhao's avatar
wuhao committed
32
    [valueColumns, setvalueColumns] = useState({});
wuhao's avatar
wuhao committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
  const [columnes, setcolumnes] = useState(columns ?? []);

  //调用接口
  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 });
    //分页结果
krysent's avatar
krysent committed
51
    let data = result?.data?.page?.records,
wuhao's avatar
wuhao committed
52 53 54 55 56 57 58
      success = true,
      total = result?.data?.page?.total;
    //不带分页获取结果
    if (ifspagination) {
      data = result?.data?.dataList;
      total = result?.data?.dataList?.length;
    }
wuhao's avatar
wuhao committed
59 60 61
    //存在默认选中向上返回选中值
    getDefaultSelected && getDefaultSelected(result?.data);

wuhao's avatar
wuhao committed
62 63 64 65
    return {
      data,
      success,
      total,
wuhao's avatar
wuhao committed
66
    };
wuhao's avatar
wuhao committed
67
  };
krysent's avatar
krysent committed
68 69

  
wuhao's avatar
wuhao committed
70 71 72
  //更新 columns
  useEffect(() => {
    setcolumnes((s) => {
wuhao's avatar
wuhao committed
73
      return columns.map((it, index) => {
wuhao's avatar
wuhao committed
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
        let itemwidth = valueColumns[it.key]?.width
          ? valueColumns[it.key].width
          : it.width
          ? it.width
          : 160;
        let options = {};
        if (it.valueType == "select" || it.valueType == "checkbox") {
          if (Array.isArray(it.options)) {
            options = {
              fieldProps: {
                options: [...it.options],
              },
            };
          } else if (it.options) {
            options = {
              request: async (params) => {
                console.log(it.options.database);
                let list = await it?.options?.database(
                  it.options?.params ?? {}
                );
                return list.data.dataList;
              },
            };
          }
        }
        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>
              );
            },
          };
        }
wuhao's avatar
wuhao committed
118

wuhao's avatar
wuhao committed
119 120 121 122
        options = {
          ...options,
          width: itemwidth,
        };
wuhao's avatar
wuhao committed
123

wuhao's avatar
wuhao committed
124 125 126 127 128 129 130 131 132 133 134
        return {
          ...it,
          ...options,
          onHeaderCell: (column) => ({
            width: column.width ?? itemwidth,
            onResize: handleResize(index),
            onResizeStop: handleResizeStop(index),
          }),
        };
      });
    });
wuhao's avatar
wuhao committed
135
  }, [valueColumns]);
wuhao's avatar
wuhao committed
136 137

  //初始化操作数据
wuhao's avatar
wuhao committed
138
  const initDrage = async () => {
wuhao's avatar
wuhao committed
139
    if (!path) return;
wuhao's avatar
wuhao committed
140
    let res = await doFetch({
wuhao's avatar
wuhao committed
141 142 143 144 145
      url: "/ngic-base-business/paFieldScene/queryContro",
      params: {
        sceneMark: extraparams
          ? path + bodyParse(extraparams)
          : activeTabKey
wuhao's avatar
wuhao committed
146 147
          ? path + activeTabKey
          : path,
wuhao's avatar
wuhao committed
148
      },
wuhao's avatar
wuhao committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    });
    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,
wuhao's avatar
wuhao committed
165 166
          };
        });
wuhao's avatar
wuhao committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
      //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);
    }
187 188 189
    actionRefs?.current?.reset();
    // actionRefs?.current?.reload();
    // actionRefs?.current?.clearSelected()
wuhao's avatar
wuhao committed
190 191
  };

wuhao's avatar
wuhao committed
192
  //调用重新渲染表格
krysent's avatar
krysent committed
193 194
  useEffect(async () => {
    // console.log(history?.location?.pathname);
wuhao's avatar
wuhao committed
195
    await initDrage();
krysent's avatar
krysent committed
196 197
  }, [columns, extraparams, path, activeTabKey, refreshDep]);
  // 
wuhao's avatar
wuhao committed
198
  //缩放表格
wuhao's avatar
wuhao committed
199
  const handleResize =
wuhao's avatar
wuhao committed
200
    (index) =>
wuhao's avatar
wuhao committed
201 202 203 204 205 206 207 208 209 210 211
    (e, { size }) => {
      e.stopImmediatePropagation();
      setcolumnes((s) => {
        const nextColumns = [...s];
        nextColumns[index] = {
          ...nextColumns[index],
          width: size.width,
        };
        return nextColumns;
      });
    };
wuhao's avatar
wuhao committed
212 213

  //更新表格缩放
wuhao's avatar
wuhao committed
214
  const handleResizeStop =
wuhao's avatar
wuhao committed
215
    (index) =>
wuhao's avatar
wuhao committed
216 217
    (e, { size }) => {
      e.stopImmediatePropagation();
wuhao's avatar
wuhao committed
218
      let submitdata = { ...valueColumns } ?? {},
wuhao's avatar
wuhao committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
        curkey = Object.keys(submitdata)[index];
      submitdata[curkey].width = parseInt(size.width);
      setvalueColumns(submitdata);
      doFetch({
        url: "/ngic-base-business/paFieldScene/save",
        params: {
          sceneMark: extraparams
            ? path + bodyParse(extraparams)
            : 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
241 242
      });
    };
wuhao's avatar
wuhao committed
243

wuhao's avatar
wuhao committed
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
  return (
    <ProTable
      {...props}
      size={size}
      onSubmit={(params) => {
        console.log(params, "onSubmit");
      }}
      onSizeChange={(size) => {
        localStorage.setItem("size", size); //设置全局表格规格缓存
        setsize(size);
      }}
      columns={columnes ?? []}
      style={style || {}}
      actionRef={actionRefs}
      formRef={formRefs}
      rowKey={rowKey ?? "id"} //表格每行数据的key
      dateFormatter="string"
      request={request}
      scroll={{
        x: x ?? 1024,
      }}
      components={{
        header: {
          cell: Resizecell,
        },
      }}
      columnsState={{
        value: valueColumns,
        onChange: (val, state) => {
krysent's avatar
krysent committed
273 274 275 276 277 278 279 280
          console.log(val);
          if (Object.keys(val).length === 0) {
            console.log(val, valueColumns);
            setvalueColumns((s) => {
              let submitdata = {
                ...s,
                ...valueColumns,
              };
krysent's avatar
krysent committed
281
              console.log(submitdata);
krysent's avatar
krysent committed
282 283 284 285 286
              let controList = Object.keys(submitdata).map((it, i) => {
                return {
                  fieldKey: it,
                  fieldWidth: submitdata[it].width,
                  fieldOrder: i,
krysent's avatar
krysent committed
287
                  fieldFixed: "",
krysent's avatar
krysent committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
                  fieldShow: true,
                };
              });
              doFetch({
                url: "/ngic-base-business/paFieldScene/save",
                params: {
                  sceneMark: extraparams
                    ? path + bodyParse(extraparams)
                    : activeTabKey
                    ? path + activeTabKey
                    : path,
                  controList: controList,
                },
              });
              return controList;
wuhao's avatar
wuhao committed
303
            });
krysent's avatar
krysent committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
          } else {
            setvalueColumns((s) => {
              let submitdata = {
                ...s,
                ...val,
              };
              doFetch({
                url: "/ngic-base-business/paFieldScene/save",
                params: {
                  sceneMark: extraparams
                    ? path + bodyParse(extraparams)
                    : 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
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        },
      }}
      pagination={
        ifspagination
          ? false
          : {
              showTotal: (total, range) => <span>{total}</span>,
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: [5, 10, 15, 30, 50, 100, 200],
              defaultPageSize: pageSize || 15,
            }
      }
      search={{
        filterType: "light", //轻量模式
      }}
    />
  );
};
wuhao's avatar
wuhao committed
351

wuhao's avatar
wuhao committed
352
export default memo(Mtable);