import _Pagination from "@alifd/next/es/pagination";
import _Table from "@alifd/next/es/table";
import _Balloon from "@alifd/next/es/balloon";
import _Icon from "@alifd/next/es/icon";
import _Button from "@alifd/next/es/button";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _regeneratorRuntime from "@babel/runtime/regenerator";
function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
import React from 'react';
import { bizCssPrefix } from "../../variables";
import { getUserTableHeader } from "./api";
import CheckboxDialog from "./components/checkbox-dialog";
import RenderCell from "./components/render-cell";
import { getUniFormList } from "../../utils/api";
import events from "../../utils/events";
import "./index.scss";
//这是基础通用表格组件
var CommonTable = /*#__PURE__*/function (_React$Component) {
  _inheritsLoose(CommonTable, _React$Component);
  function CommonTable(_props) {
    var _this;
    _this = _React$Component.call(this, _props) || this;
    //获取表格数据
    _this.getData = /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(commonVOs) {
        var _this$props, pageInfo, pageSize, isPagination, __designMode, fieldList, mode, obj, _iterator, _step, item, designTableData, current, _obj, data, _data, records, total, tableData;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _this$props = _this.props, pageInfo = _this$props.pageInfo, pageSize = _this$props.pageSize, isPagination = _this$props.isPagination, __designMode = _this$props.__designMode, fieldList = _this$props.fieldList, mode = _this$props.mode;
              if (!(__designMode === 'design')) {
                _context.next = 7;
                break;
              }
              obj = {};
              for (_iterator = _createForOfIteratorHelperLoose(fieldList); !(_step = _iterator()).done;) {
                item = _step.value;
                obj[item.fieldName] = item.displayName;
              }
              designTableData = [obj];
              _this.setState({
                tableData: designTableData
              });
              return _context.abrupt("return");
            case 7:
              if (!(mode === 'browse' || mode === 'edit')) {
                _context.next = 30;
                break;
              }
              current = _this.state.current; // console.log(pageInfo)
              _obj = {
                pageCode: pageInfo.code,
                commonVOs: commonVOs || []
              };
              data = null;
              _this.setState({
                loading: true
              });
              _context.prev = 12;
              if (!isPagination) {
                _context.next = 19;
                break;
              }
              _context.next = 16;
              return getUniFormList(_obj, current, pageSize);
            case 16:
              data = _context.sent;
              _context.next = 22;
              break;
            case 19:
              _context.next = 21;
              return getUniFormList(_obj, 1, 1000000);
            case 21:
              data = _context.sent;
            case 22:
              _context.next = 26;
              break;
            case 24:
              _context.prev = 24;
              _context.t0 = _context["catch"](12);
            case 26:
              _context.prev = 26;
              _this.setState({
                loading: false
              });
              return _context.finish(26);
            case 29:
              if (data) {
                _data = data, records = _data.records, total = _data.total;
                tableData = records;
                _this.setState({
                  tableData: tableData,
                  total: total
                });
              }
            case 30:
            case "end":
              return _context.stop();
          }
        }, _callee, null, [[12, 24, 26, 29]]);
      }));
      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }();
    //数据初始化
    _this.init = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
      var _this$props2, __designMode, id, pageInfo, fieldList, children, mode, data, defaultColumns;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            _this$props2 = _this.props, __designMode = _this$props2.__designMode, id = _this$props2.id, pageInfo = _this$props2.pageInfo, fieldList = _this$props2.fieldList, children = _this$props2.children, mode = _this$props2.mode;
            _context2.next = 3;
            return _this.getData();
          case 3:
            if (!(__designMode === 'design')) {
              _context2.next = 5;
              break;
            }
            return _context2.abrupt("return");
          case 5:
            _context2.prev = 5;
            _context2.next = 8;
            return getUserTableHeader(id, pageInfo.code);
          case 8:
            data = _context2.sent;
            _this.setState({
              userColumns: data.userColumns
            });
            _context2.next = 16;
            break;
          case 12:
            _context2.prev = 12;
            _context2.t0 = _context2["catch"](5);
            defaultColumns = children.filter(function (item) {
              var props = item.props;
              return props.isShow;
            }).map(function (child) {
              var props = child.props,
                key = child.key;
              // console.log(key)
              return {
                key: key,
                fieldName: props.fieldName,
                displayName: props.displayName,
                checked: true
                // displayName: props.fieldName,
              };
            });

            _this.setState({
              userColumns: defaultColumns
            });
            // console.log(error)
          case 16:
            if (mode === 'add') {
              _this.setState({
                tableData: []
              });
              _this.addRow();
            }
          case 17:
          case "end":
            return _context2.stop();
        }
      }, _callee2, null, [[5, 12]]);
    }));
    //监听过滤器查找数据
    _this.onFilter = /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(commonVOs) {
        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              // console.log(commonVOs);
              _this.setState({
                current: 1
              });
              _context3.next = 3;
              return _this.getData(commonVOs);
            case 3:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }));
      return function (_x2) {
        return _ref3.apply(this, arguments);
      };
    }();
    //修改页数
    _this.onChange = function (currentPage) {
      _this.setState({
        current: currentPage
      });
      // console.log(currentPage);
    };
    //添加行数
    _this.addRow = function () {
      var _this$props3 = _this.props,
        fieldList = _this$props3.fieldList,
        children = _this$props3.children;
      var tableData = _this.state.tableData;
      // console.log(tableData)
      var newData = {};
      // fieldList.filter
      var _loop = function _loop() {
        var item = _step2.value;
        var child = children.filter(function (item1) {
          return item1.key === item.id;
        });
        if (child.length) {
          newData[item.fieldName] = child[0].props.defaultValue;
        } else {
          newData[item.fieldName] = '';
        }
      };
      for (var _iterator2 = _createForOfIteratorHelperLoose(fieldList), _step2; !(_step2 = _iterator2()).done;) {
        _loop();
      }
      // console.log(tableData);
      tableData.push(newData);
      _this.setState({
        tableData: tableData
      });
    };
    //移入行
    _this.onRowMouseEnter = function (record, index, e) {
      var _this$props4 = _this.props,
        __designMode = _this$props4.__designMode,
        mode = _this$props4.mode;
      // console.log(e.currentTarget.parentElement)
      if (__designMode === 'design' || mode === 'browse') return;
      _this.setState({
        editRowIndex: index
      });
    };
    //移出列
    _this.onRowMouseLeave = function (record, index, e) {
      var _this$props5 = _this.props,
        __designMode = _this$props5.__designMode,
        mode = _this$props5.mode;
      if (__designMode === 'design' || mode === 'browse') return;
      _this.setState({
        editRowIndex: -1
      });
    };
    //渲染头部选择框
    _this.renderCheckbox_ = function () {
      var userColumns = _this.state.userColumns;
      var _this$props6 = _this.props,
        pageInfo = _this$props6.pageInfo,
        id = _this$props6.id;
      return /*#__PURE__*/React.createElement(CheckboxDialog, {
        tableId: id,
        pageInfo: pageInfo
        // defaultValue={this.state.userColumns}
        ,
        dataSource: userColumns,
        onSave: function onSave(list) {
          _this.setState({
            balloonVisible: false,
            userColumns: list
          });
        },
        onClose: function onClose() {
          _this.setState({
            balloonVisible: false
          });
        }
      });
    };
    //渲染操作列
    _this._renderActionColumnCell = function (value, index, record) {
      var mode = _this.props.mode;
      if (mode === 'add') return null;
      var tableData = _this.state.tableData;
      //删除行
      var deleteRow = function deleteRow(index) {
        tableData.splice(index, 1);
        _this.setState({
          tableData: tableData
        });
      };
      return /*#__PURE__*/React.createElement("div", {
        "class": "action-btn"
      }, /*#__PURE__*/React.createElement(_Button, {
        // onClick={}
        className: "btn",
        size: "small",
        text: true,
        warning: true,
        type: "normal"
      }, "\u7F16\u8F91"), /*#__PURE__*/React.createElement(_Button, {
        onClick: function onClick() {
          return deleteRow(index);
        },
        className: "btn",
        size: "small",
        text: true,
        warning: true,
        type: "normal"
      }, "\u5220\u9664"));
    };
    _this._renderActionColumn = function () {
      var __designMode = _this.props.__designMode;

      //点击自定义表格标题弹窗
      var onClickBalloon = function onClickBalloon() {
        // const { __designMode } = this.props;
        if (__designMode === 'design') {
          return;
        }
        _this.setState({
          balloonVisible: !_this.state.balloonVisible
        });
      };
      return /*#__PURE__*/React.createElement(_Table.Column, {
        className: "common-table-column",
        lock: "right"
        // width={60}
        ,
        cell: function cell(value, index, record) {
          return _this._renderActionColumnCell(value, index, record);
        }
        // console.log(record);
        //自定义表格头部标题
        ,
        title: function title() {
          return /*#__PURE__*/React.createElement("div", {
            className: "action"
          }, /*#__PURE__*/React.createElement(_Balloon, {
            arrowPointToCenter: true,
            autoFocus: false,
            v2: true,
            visible: _this.state.balloonVisible,
            trigger: /*#__PURE__*/React.createElement("span", {
              onClick: function onClick() {
                onClickBalloon();
              }
            }, /*#__PURE__*/React.createElement(_Icon, {
              className: "action-icon",
              type: "list"
            })),
            closable: false,
            triggerType: "click"
          }, __designMode !== 'design' && _this.renderCheckbox_()));
        },
        dataIndex: "action"
      });
    };
    _this.state = {
      loading: false,
      columns: [],
      total: 0,
      tableData: [],
      current: 1,
      balloonVisible: false,
      userColumns: [],
      editRowIndex: -1
    };
    return _this;
  }
  //监听数据更新
  var _proto = CommonTable.prototype;
  _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState, snapshot) {
    // console.log(prevState)
    // console.log(this.state)
    if (prevState.current !== this.state.current || prevProps.isPagination !== this.props.isPagination || prevProps.pageSize !== this.props.pageSize || prevProps.fieldList !== this.props.fieldList) {
      this.getData();
    }
  };
  _proto.componentDidMount = /*#__PURE__*/function () {
    var _componentDidMount = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
      var _this2 = this;
      return _regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            events.on('onFilter', function (commonVOs) {
              return _this2.onFilter(commonVOs);
            });
            _context4.next = 3;
            return this.init();
          case 3:
          case "end":
            return _context4.stop();
        }
      }, _callee4, this);
    }));
    function componentDidMount() {
      return _componentDidMount.apply(this, arguments);
    }
    return componentDidMount;
  }();
  _proto.componentWillUnmount = function componentWillUnmount() {
    var _this3 = this;
    events.off('onFilter', function () {
      return _this3.onFilter;
    });
  };
  //渲染头部
  _proto.renderColumns = function renderColumns() {
    var _this4 = this;
    var _this$props7 = this.props,
      children = _this$props7.children,
      __designMode = _this$props7.__designMode,
      mode = _this$props7.mode,
      pageInfo = _this$props7.pageInfo;
    var editRowIndex = this.state.editRowIndex;
    var childrenDom = [];
    //区分设计器跟预览
    if (__designMode !== 'design') {
      var userColumns = this.state.userColumns;
      var showColumns = userColumns.filter(function (item) {
        return item.checked;
      });
      var _loop2 = function _loop2() {
        var column = showColumns[i];
        var child = children.filter(function (item) {
          var props = item.props;
          return props.fieldName === column.fieldName;
        });
        if (child.length) {
          childrenDom.push(child[0]);
        }
      };
      for (var i = 0; i < showColumns.length; i++) {
        _loop2();
      }
    } else {
      childrenDom = children;
    }
    var cellChange = function cellChange(data, fieldName, index) {
      // console.log(fieldName);
      var tableData = _this4.state.tableData;
      tableData[index][fieldName] = data;
      _this4.setState({
        tableData: tableData
      });
    };
    return React.Children.map(childrenDom, function (child, index) {
      var props = child.props;
      return /*#__PURE__*/React.createElement(_Table.Column, {
        className: "common-table-column",
        dataIndex: props.fieldName,
        colSpan: props.colSpan,
        width: 150,
        key: 'child' + index
        // cell={(value, index, record) => this._renderCell(value, index, record, child)}
        ,
        cell: function cell(value, index, record) {
          // console.log(value,index,record,context)
          return /*#__PURE__*/React.createElement(RenderCell, {
            key: index,
            pageInfo: pageInfo,
            mode: mode,
            child: child,
            value: value || '',
            index: index,
            editRowIndex: editRowIndex,
            onChange: function onChange(data) {
              return cellChange(data, props.fieldName, index);
            }
          });
        },
        title: /*#__PURE__*/React.cloneElement(child)
      });
    });
  };
  _proto.render = function render() {
    var _this5 = this;
    var _this$props8 = this.props,
      isPagination = _this$props8.isPagination,
      pageSize = _this$props8.pageSize,
      children = _this$props8.children,
      style = _this$props8.style,
      __designMode = _this$props8.__designMode,
      mode = _this$props8.mode;
    var _this$state = this.state,
      total = _this$state.total,
      loading = _this$state.loading;
    return /*#__PURE__*/React.createElement("div", {
      className: bizCssPrefix + '-common-table',
      style: style
    }, /*#__PURE__*/React.createElement(_Table, {
      dataSource: this.state.tableData
      // primaryKey="id"
      ,
      size: "small",
      useVirtual: true,
      fixedHeader: true,
      loading: loading,
      maxBodyHeight: 300,
      rowSelection: {
        onChange: function onChange() {}
      },
      onRowMouseEnter: function onRowMouseEnter(record, index, e) {
        _this5.onRowMouseEnter(record, index, e);
      },
      onRowMouseLeave: function onRowMouseLeave(record, index, e) {
        _this5.onRowMouseLeave(record, index, e);
      }
    }, /*#__PURE__*/React.createElement(_Table.Column, {
      className: "common-table-column"
      // lock="right"
      ,
      width: 60,
      cell: function cell(value, index, record) {
        var sum = (_this5.state.current - 1) * pageSize + index + 1;
        return sum;
      }
      // console.log(record);
      //自定义表格头部标题
      ,
      title: "\u5E8F\u53F7",
      dataIndex: "index"
    }), this.renderColumns(), this._renderActionColumn()), isPagination && mode === 'browse' && /*#__PURE__*/React.createElement(_Pagination, {
      className: "common-table-pagination",
      current: this.state.current,
      showJump: false,
      onChange: this.onChange,
      pageSize: pageSize,
      total: total
    }));
  };
  return CommonTable;
}(React.Component);
CommonTable.displayName = 'CommonTable';
export default CommonTable;