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) !=
        JSON.stringify(nextprops.extraparams) ||
      JSON.stringify(this.props.path) != JSON.stringify(nextprops.path) ||
      JSON.stringify(this.props.refreshDep) !=
        JSON.stringify(nextprops.refreshDep) ||
      this.props.columns != nextprops.columns
    ) {
      if (nextprops.actionRef) {
        nextprops.actionRef?.current?.reset();
      } else {
        this.actionRefs?.current?.reset();
      }
      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
          ? path + activeTabKey
          : path,
      },
    }).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
            ? it.width
            : 160;

          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) => {
                  return (
                    <Tooltip title={row[it.dataIndex]} placement="topLeft">
                      <span className="table-cell">
                        {row[it.dataIndex] ?? "-"}
                      </span>
                    </Tooltip>
                  );
                },
          };
        });

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

  //缩放表格
  handleResize =
    (index) =>
    (e, { size }) => {
      e.stopImmediatePropagation();
      this.setState(({ columns }) => {
        const nextColumns = [...columns];
        nextColumns[index] = {
          ...nextColumns[index],
          width: size.width,
        };
        return { columns: nextColumns };
      });
    };

  //更新表格缩放
  handleResizeStop =
    (index) =>
    (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,
                };
              }),
            },
          });
        }
      );
    };

  render() {
    let {
        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,
      { total, size } = this.state;
    let tabledataProps =
      dataSource && Array.isArray(dataSource)
        ? {
            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,
          }
        : {
            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 ?? {};

              //处理传参 extraparams为除列筛选外的自定义传参
              let newparams = {
                ...params,
                ...newextraparams, //父组件传参
                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",
              });
              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", //轻量模式
            },
          };
    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
              ? data.page.list
              : []; //分页或不分页的接口返回数据
          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
                      ? 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,
                      };
                    }),
                  },
                });
              }
            );
          },
        }}
        scroll={{
          x: x ?? 1024,
        }}
        {...tabledataProps}
        {...expandable}
        onRow={onRow ? (record) => onRow(record) : null}
      />
    );
  }
}

export default Mtable;
