mtable.jsx 9.73 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";
wuhao's avatar
wuhao committed
8

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

wuhao's avatar
wuhao committed
26 27 28 29
  const actionRefs = actionRef ?? useRef(),
    formRefs = formRef ?? useRef(),
    ifspagination = pagination == "false" || pagination === false,
    [size, setsize] = useState("small"),
wuhao's avatar
wuhao committed
30
    [valueColumns, setvalueColumns] = useState({});
wuhao's avatar
wuhao committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
  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
49
    let data = result?.data?.page?.records,
wuhao's avatar
wuhao committed
50 51 52 53 54 55 56
      success = true,
      total = result?.data?.page?.total;
    //不带分页获取结果
    if (ifspagination) {
      data = result?.data?.dataList;
      total = result?.data?.dataList?.length;
    }
wuhao's avatar
wuhao committed
57 58 59
    //存在默认选中向上返回选中值
    getDefaultSelected && getDefaultSelected(result?.data);

wuhao's avatar
wuhao committed
60 61 62 63
    return {
      data,
      success,
      total,
wuhao's avatar
wuhao committed
64
    };
wuhao's avatar
wuhao committed
65 66 67 68
  };
  //更新 columns
  useEffect(() => {
    setcolumnes((s) => {
wuhao's avatar
wuhao committed
69
      return columns.map((it, index) => {
wuhao's avatar
wuhao committed
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
        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
114

wuhao's avatar
wuhao committed
115 116 117 118
        options = {
          ...options,
          width: itemwidth,
        };
wuhao's avatar
wuhao committed
119

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

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

wuhao's avatar
wuhao committed
186 187 188
  //调用重新渲染表格
  useAsyncEffect(async () => {
    await initDrage();
wuhao's avatar
wuhao committed
189
  }, [columns, extraparams, path, activeTabKey, refreshDep]);
wuhao's avatar
wuhao committed
190

wuhao's avatar
wuhao committed
191
  //缩放表格
wuhao's avatar
wuhao committed
192
  const handleResize =
wuhao's avatar
wuhao committed
193
    (index) =>
wuhao's avatar
wuhao committed
194 195 196 197 198 199 200 201 202 203 204
    (e, { size }) => {
      e.stopImmediatePropagation();
      setcolumnes((s) => {
        const nextColumns = [...s];
        nextColumns[index] = {
          ...nextColumns[index],
          width: size.width,
        };
        return nextColumns;
      });
    };
wuhao's avatar
wuhao committed
205 206

  //更新表格缩放
wuhao's avatar
wuhao committed
207
  const handleResizeStop =
wuhao's avatar
wuhao committed
208
    (index) =>
wuhao's avatar
wuhao committed
209 210
    (e, { size }) => {
      e.stopImmediatePropagation();
wuhao's avatar
wuhao committed
211
      let submitdata = { ...valueColumns } ?? {},
wuhao's avatar
wuhao committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
        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
234 235
      });
    };
wuhao's avatar
wuhao committed
236

wuhao's avatar
wuhao committed
237 238 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
  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
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
          console.log(val);
          if (Object.keys(val).length === 0) {
            console.log(val, valueColumns);
            setvalueColumns((s) => {
              let submitdata = {
                ...s,
                ...valueColumns,
              };

              let controList = Object.keys(submitdata).map((it, i) => {
                return {
                  fieldKey: it,
                  fieldWidth: submitdata[it].width,
                  fieldOrder: i,
                  fieldFixed: submitdata[it].fixed,
                  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
296
            });
krysent's avatar
krysent committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
          } 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
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
        },
      }}
      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
344

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