import React, { PureComponent } from "react";
import ProTable from "@ant-design/pro-table";
import request from "umi-request";
import Cascader from "./Cascader";
import { Tooltip } from "antd";

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

class Mtable extends PureComponent {
  state = {
    total: 0,
    size: defaultsize ? defaultsize : "small",
    valueEnum: {},
    columns: [],
  };

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

  componentWillReceiveProps(nextprops) {
    if (
      JSON.stringify(this.props.extraparams) !=
        JSON.stringify(nextprops.extraparams) ||
      JSON.stringify(this.props.path) != JSON.stringify(nextprops.path)
    ) {
      if (this.props.actionRef) {
        this.props.actionRef?.current?.reload();
      } else {
        this.actionRefs?.current?.reload();
      }
    }
  }

  render() {
    let {
        pageSize,
        x,
        y,
        style,
        dataSource,
        onSearchChange,
        defaultPageSize,
        dispatch, //dispatch
        columns, //表头
        pagination, //分页
        rowKey, //行key
        savekey, //保存查询条件key
        actionRef, //操作ref
        formRef, //查询表单ref
        path, //路径
        extraparams = {}, //拓展查询参数
        rowSelection, //行选择
        tableRender, //表格布局自定义
        getDefaultSelected, //获取默认选中的数据
        rowClassNameFn, //选中后行样式
        showQuickJumper, //false字符串 不显示
        expandable, //是否可展开
        onExpand,
      } = this.props,
      { total, size } = this.state;

    let scroll = {};
    if (y) {
      scroll = {
        ...scroll,
        y,
      };
    }
    if (x) {
      scroll = {
        ...scroll,
        x,
      };
    }
    let tabledataProps =
      dataSource && Array.isArray(dataSource)
        ? {
            dataSource,
            pagination:
              pagination == "false"
                ? false
                : {
                    showTotal: (total, range) => <span>共{total}条</span>,
                    showQuickJumper: false,
                    defaultPageSize: defaultPageSize ? defaultPageSize : 15,
                    pageSizeOptions: [10, 15, 30, 50, 100, 200],
                    total: dataSource.length,
                  },
            search: {
              filterType: "light", //轻量模式
            },
            toolBarRender: false,
          }
        : {
            request: async (params = {}) => {
              //表格数据获取 只需要传入url自动获得数据
              if (!path) {
                return;
              }
              //设置token
              let token = localStorage.getItem("TOKENY")
                ? localStorage.getItem("TOKENY")
                : "b60ef0c40b7f1b7e63c2b24b127988d4";
              let headers = {
                "Content-Type": "application/json",
                token: token ? token : "",
              };
              //处理传参 extraparams为除列筛选外的自定义传参
              let newparams = {
                ...params,
                ...extraparams, //父组件传参
                pageIndex: params.current,
                pageSize: params.pageSize || pageSize,
              };
              delete newparams.current;
              if (pagination == "false") {
                delete newparams.pageIndex;
                delete newparams.pageSize;
              }

              let res = await request("/wms" + path, {
                body: JSON.stringify(newparams ? newparams : {}),
                headers,
                method: "POST",
              });
              if (res.code == "0000") {
                return {
                  data: res.data,
                  total: res?.data?.page?.total || res?.data?.dataList?.length,
                };
              } else {
                return {
                  data:
                    pagination == "false"
                      ? {
                          dataList: [],
                        }
                      : {
                          page: {
                            list: [],
                          },
                        },
                  total: 0,
                };
              }
            },
            pagination: {
              showTotal: (total, range) => <span>共{total}条</span>,
              showQuickJumper: !showQuickJumper ? true : false,
              pageSizeOptions: [5, 10, 15, 30, 50, 100, 200],
              defaultPageSize: pageSize || 15,
              total,
            },
            search: {
              filterType: "light", //轻量模式
            },
          };
    let columnes = columns.map((it) => {
      if (it.valueType == "cascader") {
        it.renderFormItem = (
          item,
          { type, defaultRender, fieldProps, ...rest },
          form
        ) => {
          let newoption = it.options || it.belinked.options;
          if (Array.isArray(newoption)) {
            newoption = { option: newoption };
          } else {
            let newparams = {};
            Object.keys(newoption.params).map((it) => {
              newparams[it] = form.getFieldValue(it);
            });
            newoption = {
              option: {
                ...newoption,
                params: newparams,
              },
            };
          }
          let reset = columns.filter((item) => {
            let newop = item?.options || item?.belinked?.options;
            return (
              newop?.params && newop.params[it?.formItemProps?.name] == "linked"
            );
          });
          let resetkey = reset.map((it) => it?.formItemProps?.name);
          return <Cascader {...newoption} form={form} resetkey={resetkey} />;
        };
      }
      if (it.valueType == "select" || it.valueType == "checkbox") {
        if (Array.isArray(it.options)) {
          // it.request = async function () {
          //   return 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;
          };
        }
      }
      return {
        ...it,
        ellipsis: true,
        render: it.render
          ? it.render
          : (text, row) => {
              return (
                <Tooltip title={row[it.dataIndex]} placement="topLeft">
                  <span>{row[it.dataIndex] ?? "-"}</span>
                </Tooltip>
              );
            },
      };
    });
    return (
      <ProTable
        size={size}
        onSubmit={(params) => {
          onSearchChange && onSearchChange(params);
        }}
        onSizeChange={(size) => {
          localStorage.setItem("size", size); //设置全局表格规格缓存
          this.setState({
            size,
          });
        }}
        columns={columnes}
        scroll={scroll}
        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
              ? data.page.list
              : []; //分页或不分页的接口返回数据
          return defaultval;
        }}
        rowSelection={rowSelection ? rowSelection : false}
        tableAlertRender={false} //取消顶部筛选操作
        tableRender={
          tableRender ? (_, dom) => tableRender(_, dom) : (_, dom) => dom
        } //自定义表格主体
        rowClassName={
          rowClassNameFn ? (record, index) => rowClassNameFn(record, index) : ""
        } //自定义行高亮
        {...tabledataProps}
        {...expandable}
        onExpand={onExpand ?? null}
      />
    );
  }
}

export default Mtable;
