mtable.jsx 12 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
import React, { PureComponent } from "react";
import ProTable from "@ant-design/pro-table";
import request from "umi-request";
import Resizecell from "./Resizecell";
import { Tooltip } from "antd";
import { doFetch } from "@/utils/doFetch";
import bodyParse from "@/utils/bodyParse";

let defaultsize = localStorage.getItem("size"); //设置缓存

class Mtable extends PureComponent {
  constructor(props) {
    super(props);
    let { columns } = this.props;
    this.state = {
      total: 0,
      size: defaultsize ? defaultsize : "small",
      columns: columns,
      valueColumns: {},
    };
  }

  actionRefs = React.createRef();
  formRefs = React.createRef();

  componentWillReceiveProps(nextprops) {
    if (
      JSON.stringify(this.props.extraparams) !=
wuhao's avatar
wuhao committed
29
      JSON.stringify(nextprops.extraparams) ||
wuhao's avatar
wuhao committed
30 31
      JSON.stringify(this.props.path) != JSON.stringify(nextprops.path) ||
      JSON.stringify(this.props.refreshDep) !=
wuhao's avatar
wuhao committed
32 33
      JSON.stringify(nextprops.refreshDep) ||
      this.props.columns != nextprops.columns
wuhao's avatar
wuhao committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
    ) {
      if (nextprops.actionRef) {
        nextprops.actionRef?.current?.reload();
      } else {
        this.actionRefs?.current?.reload();
      }
      this.initDrage(nextprops);
    }
  }

  componentDidMount() {
    this.initDrage();
  }
  //初始化操作数据
  initDrage = (nextprops) => {
    let curprops = nextprops ?? this.props;
    let { extraparams, path, activeTabKey, columns } = curprops;
    if (!path) return;
    doFetch({
      url: "/ngic-base-business/paFieldScene/queryContro",
      params: {
        sceneMark: extraparams
          ? path + bodyParse(extraparams)
          : activeTabKey
wuhao's avatar
wuhao committed
58 59
            ? path + activeTabKey
            : path,
wuhao's avatar
wuhao committed
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
      },
    }).then((res) => {
      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],
            };
          }
        });
        //columns 列属性添加
        let columnes = columns.map((it, index) => {
          if (it.valueType == "select" || it.valueType == "checkbox") {
            if (Array.isArray(it.options)) {
              it.fieldProps = {
                options: [...it.options],
              };
            } else {
              it.request = async function () {
                let list = await it.options.database(it.options.params);
                return list.data.dataList;
              };
            }
          }

          if (it.valueType == "option") {
            it.key = "option";
            it.dataIndex = "option";
            it.fixed = "right";
          }

          let itemwidth = allcol[it.key]?.width
            ? allcol[it.key].width
            : it.width
wuhao's avatar
wuhao committed
121 122
              ? it.width
              : 160;
wuhao's avatar
wuhao committed
123 124 125 126 127 128 129 130 131 132 133
          return {
            ...it,
            width: itemwidth,
            onHeaderCell: (column) => ({
              width: column.width ?? itemwidth,
              onResize: this.handleResize(index),
              onResizeStop: this.handleResizeStop(index),
            }),
            render: it.render
              ? it.render
              : (text, row) => {
wuhao's avatar
wuhao committed
134 135 136 137 138 139 140 141
                return (
                  <Tooltip title={row[it.dataIndex]} placement="topLeft">
                    <span className="table-cell">
                      {row[it.dataIndex] ?? "-"}
                    </span>
                  </Tooltip>
                );
              },
wuhao's avatar
wuhao committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155
          };
        });

        this.setState({
          valueColumns: allcol,
          columns: columnes,
        });
      }
    });
  };

  //缩放表格
  handleResize =
    (index) =>
wuhao's avatar
wuhao committed
156 157 158 159 160 161 162 163 164 165 166
      (e, { size }) => {
        e.stopImmediatePropagation();
        this.setState(({ columns }) => {
          const nextColumns = [...columns];
          nextColumns[index] = {
            ...nextColumns[index],
            width: size.width,
          };
          return { columns: nextColumns };
        });
      };
wuhao's avatar
wuhao committed
167 168 169 170

  //更新表格缩放
  handleResizeStop =
    (index) =>
wuhao's avatar
wuhao committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
      (e, { size }) => {
        e.stopImmediatePropagation();
        let { extraparams, activeTabKey, path } = this.props;
        let submitdata = this.state.valueColumns ?? {},
          curkey = Object.keys(submitdata)[index];
        submitdata[curkey].width = parseInt(size.width);
        this.setState(
          {
            valueColumns: 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
205 206 207

  render() {
    let {
wuhao's avatar
wuhao committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
      pageSize,
      x,
      y,
      style,
      dataSource,
      onSearchChange,
      defaultPageSize,
      pagination, //分页
      rowKey, //行key
      actionRef, //操作ref
      formRef, //查询表单ref
      path, //路径
      activeTabKey, //当前tab
      extraparams, //拓展查询参数
      rowSelection, //行选择
      tableRender, //表格布局自定义
      getDefaultSelected, //获取默认选中的数据
      rowClassNameFn, //选中后行样式
      showQuickJumper, //false字符串 不显示
      expandable, //是否可展开
      onRow,
    } = this.props,
wuhao's avatar
wuhao committed
230 231 232 233
      { total, size } = this.state;
    let tabledataProps =
      dataSource && Array.isArray(dataSource)
        ? {
wuhao's avatar
wuhao committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247
          dataSource,
          pagination: {
            showTotal: (total, range) => <span>{total}</span>,
            showQuickJumper: false,
            showSizeChanger: true,
            defaultPageSize: defaultPageSize ? defaultPageSize : 15,
            pageSizeOptions: [10, 15, 30, 50, 100, 200],
            total: dataSource.length,
          },
          search: {
            filterType: "light", //轻量模式
          },
          toolBarRender: false,
        }
wuhao's avatar
wuhao committed
248
        : {
wuhao's avatar
wuhao committed
249 250 251 252 253 254 255 256 257 258 259 260 261 262
          request: async (params = {}) => {
            //表格数据获取 只需要传入url自动获得数据
            if (!path) {
              return;
            }
            //设置token
            let token = localStorage.getItem("TOKENS")
              ? localStorage.getItem("TOKENS")
              : "9410b3f7de5d63f2be42d80ec8241d2d";
            let headers = {
              "Content-Type": "application/json",
              token: token ? token : "",
            },
              newextraparams = extraparams ?? {};
wuhao's avatar
wuhao committed
263

wuhao's avatar
wuhao committed
264 265 266 267 268 269 270 271 272 273 274 275
            //处理传参 extraparams为除列筛选外的自定义传参
            let newparams = {
              ...params,
              ...newextraparams, //父组件传参
              pageIndex: params.current,
              pageSize: params.pageSize || pageSize,
            };
            delete newparams.current;
            if (pagination == "false") {
              delete newparams.pageIndex;
              delete newparams.pageSize;
            }
wuhao's avatar
wuhao committed
276

wuhao's avatar
wuhao committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
            let res = await request("/wms" + path, {
              body: JSON.stringify(newparams ? newparams : {}),
              headers,
              method: "POST",
            });
            return {
              data: res.data,
              total: res?.data?.total || res?.data?.dataList?.length,
            };
          },
          pagination: {
            showTotal: (total, range) => <span>{total}</span>,
            showQuickJumper: !showQuickJumper ? true : false,
            showSizeChanger: true,
            pageSizeOptions: [5, 10, 15, 30, 50, 100, 200],
            defaultPageSize: pageSize || 15,
            total,
          },
          search: {
            filterType: "light", //轻量模式
          },
        };
wuhao's avatar
wuhao committed
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 325 326 327 328 329 330 331 332
    return (
      <ProTable
        size={size}
        onSubmit={(params) => {
          onSearchChange && onSearchChange(params);
        }}
        onSizeChange={(size) => {
          localStorage.setItem("size", size); //设置全局表格规格缓存
          this.setState({
            size,
          });
        }}
        columns={this.state.columns}
        style={style || {}}
        actionRef={actionRef ? actionRef : this.actionRefs}
        formRef={formRef ? formRef : this.formRefs}
        rowKey={rowKey ? rowKey : "id"} //表格每行数据的key
        dateFormatter="string"
        postData={(data) => {
          if (data.page) {
            this.setState({
              total: data.page.total,
            });
          } else {
            this.setState({
              total: data.dataList.length,
            });
          }
          //分页or不分页获取数据
          getDefaultSelected && getDefaultSelected(data); //存在默认选中向上返回选中值
          let defaultval =
            pagination == "false"
              ? data.dataList
              : data.page
wuhao's avatar
wuhao committed
333 334
                ? data.page.list
                : []; //分页或不分页的接口返回数据
wuhao's avatar
wuhao committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
          return defaultval;
        }}
        components={{
          header: {
            cell: Resizecell,
          },
        }}
        rowSelection={rowSelection ? rowSelection : false}
        tableRender={
          tableRender ? (_, dom) => tableRender(_, dom) : (_, dom) => dom
        } //自定义表格主体
        rowClassName={
          rowClassNameFn ? (record, index) => rowClassNameFn(record, index) : ""
        } //自定义行高亮
        columnsState={{
          value: this.state.valueColumns,
          onChange: (val, state) => {
            let submitdata = {
              ...this.state.valueColumns,
              ...val,
            };
            this.setState(
              {
                valueColumns: submitdata,
              },
              (state) => {
                if (!this.props.path) return;
                doFetch({
                  url: "/ngic-base-business/paFieldScene/save",
                  params: {
                    sceneMark: extraparams
                      ? path + bodyParse(extraparams)
                      : activeTabKey
wuhao's avatar
wuhao committed
368 369
                        ? path + activeTabKey
                        : path,
wuhao's avatar
wuhao committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
                    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,
                      };
                    }),
                  },
                });
              }
            );
          },
        }}
        scroll={{
wuhao's avatar
wuhao committed
386
          x: x ?? 1024,
wuhao's avatar
wuhao committed
387 388 389 390 391 392 393 394 395 396
        }}
        {...tabledataProps}
        {...expandable}
        onRow={onRow ? (record) => onRow(record) : null}
      />
    );
  }
}

export default Mtable;