"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _pagination = _interopRequireDefault(require("@alifd/next/lib/pagination"));
var _table = _interopRequireDefault(require("@alifd/next/lib/table"));
var _balloon = _interopRequireDefault(require("@alifd/next/lib/balloon"));
var _icon = _interopRequireDefault(require("@alifd/next/lib/icon"));
var _button = _interopRequireDefault(require("@alifd/next/lib/button"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _react = _interopRequireDefault(require("react"));
var _variables = require("../../variables");
var _api = require("./api");
var _checkboxDialog = _interopRequireDefault(require("./components/checkbox-dialog"));
var _renderChild = _interopRequireDefault(require("./components/render-child"));
var _api2 = require("../../utils/api");
var _events = _interopRequireDefault(require("../../utils/events"));
require("./index.scss");
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; }
//这是基础通用表格组件
//查询条件
var CommonTable = /*#__PURE__*/function (_React$Component) {
  (0, _inheritsLoose2["default"])(CommonTable, _React$Component);
  function CommonTable(_props) {
    var _this;
    _this = _React$Component.call(this, _props) || this;
    //获取表格数据
    _this.getData = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
      var _this$props, pageInfo, pageSize, isPagination, __designMode, fieldList, mode, children, dataSource, obj, _iterator, _step, item, designTableData, current, referList, customList, enitiyFieldList, customReferList, referFields, enitiyFields, list, gridVOs, _obj, data, _data, records, total, tableData;
      return _regenerator["default"].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, children = _this$props.children, dataSource = _this$props.dataSource;
            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 = 41;
              break;
            }
            current = _this.state.current; // const { fieldList } = this.props;
            //获取参照字段数组
            referList = fieldList.filter(function (item) {
              return item.bizType == 'quote';
            }); //获取自定义字段数组
            customList = fieldList.filter(function (item) {
              return item.isCustom;
            }); //获取实体字段数组
            enitiyFieldList = fieldList.filter(function (item) {
              return !item.isCustom && item.bizType != 'quote';
            }); //自定义字段请求数据数组
            customReferList = []; //参照请求数据数组
            referFields = []; //获取参照请求字段数组
            referList.forEach(function (item) {
              var _children$find;
              var childProps = (_children$find = children.find(function (child) {
                return child.key == item.id;
              })) === null || _children$find === void 0 ? void 0 : _children$find.props;
              var refer = childProps === null || childProps === void 0 ? void 0 : childProps.refer;
              var referShowField = refer === null || refer === void 0 ? void 0 : refer.referShowField;
              var selectedRefer = refer === null || refer === void 0 ? void 0 : refer.selectedRefer;
              var currentFieldList = (refer === null || refer === void 0 ? void 0 : refer.currentFieldList) || [];
              var bizId = item.bizId;
              var fieldName = item.fieldName;
              var fieldItem = {
                displayName: item.displayName,
                fieldName: fieldName,
                referCode: selectedRefer === null || selectedRefer === void 0 ? void 0 : selectedRefer.code,
                referEnitiyId: bizId,
                referFieldName: 'id'
              };
              if (item.fieldName.indexOf('_id') >= 0) {
                fieldItem.showFlag = true;
                fieldItem.referFieldName = (referShowField === null || referShowField === void 0 ? void 0 : referShowField.fieldName) || '';
                currentFieldList.forEach(function (current) {
                  var field = customList.find(function (custom) {
                    return custom.fieldName == current.fieldName;
                  });
                  // console.log(field)
                  if (field) {
                    customReferList.push({
                      displayName: field.displayName,
                      fieldName: current.fieldName,
                      referCode: selectedRefer === null || selectedRefer === void 0 ? void 0 : selectedRefer.code,
                      referEnitiyId: bizId,
                      referFieldName: current.referFieldName
                    });
                  }
                });
              }
              referFields.push(fieldItem);
            });

            //实体字段请求数据数组
            enitiyFields = [];
            enitiyFields = enitiyFieldList.map(function (item) {
              return {
                displayName: item.displayName,
                fieldName: item.fieldName
              };
            });
            list = referFields.concat(customReferList).concat(enitiyFields); // fields.concat(customReferList)
            //参照字段数据
            gridVOs = [{
              entityId: dataSource,
              fields: list
            }];
            _obj = {
              pageCode: pageInfo.code,
              gridVOs: gridVOs,
              commonVOs: _this.state.commonVOs || []
            };
            data = null;
            _this.setState({
              loading: true
            });
            _context.prev = 22;
            if (!isPagination) {
              _context.next = 29;
              break;
            }
            _context.next = 26;
            return (0, _api2.getUniFormList)(_obj, current, pageSize);
          case 26:
            data = _context.sent;
            _context.next = 32;
            break;
          case 29:
            _context.next = 31;
            return (0, _api2.getUniFormList)(_obj, 1, 1000000);
          case 31:
            data = _context.sent;
          case 32:
            _context.next = 37;
            break;
          case 34:
            _context.prev = 34;
            _context.t0 = _context["catch"](22);
            console.log(_context.t0);
          case 37:
            _context.prev = 37;
            _this.setState({
              loading: false
            });
            return _context.finish(37);
          case 40:
            if (data) {
              _data = data, records = _data.records, total = _data.total;
              tableData = records;
              console.log(tableData);
              _this.setState({
                tableData: tableData,
                total: total
              });
            }
          case 41:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[22, 34, 37, 40]]);
    }));
    //数据初始化
    _this.init = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
      var _this$props2, __designMode, id, pageInfo, children, mode, data, defaultColumns;
      return _regenerator["default"].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, 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 (0, _api.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 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(commonVOs) {
        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              // console.log(commonVOs);
              _this.setState({
                commonVOs: commonVOs,
                current: 1
              });

              // await this.getData(commonVOs);
            case 1:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }));
      return function (_x) {
        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["default"].createElement(_checkboxDialog["default"], {
        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["default"].createElement("div", {
        className: "action-btn"
      }, /*#__PURE__*/_react["default"].createElement(_button["default"], {
        // onClick={}
        className: "btn",
        size: "small",
        text: true,
        warning: true,
        type: "normal"
      }, "\u7F16\u8F91"), /*#__PURE__*/_react["default"].createElement(_button["default"], {
        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["default"].createElement(_table["default"].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["default"].createElement("div", {
            className: "action"
          }, /*#__PURE__*/_react["default"].createElement(_balloon["default"], {
            arrowPointToCenter: true,
            autoFocus: false,
            v2: true,
            visible: _this.state.balloonVisible,
            trigger: /*#__PURE__*/_react["default"].createElement("span", {
              onClick: function onClick() {
                onClickBalloon();
              }
            }, /*#__PURE__*/_react["default"].createElement(_icon["default"], {
              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,
      commonVOs: []
    };
    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 || prevState.commonVOs !== this.state.commonVOs) {
      this.getData();
    }
  };
  _proto.componentDidMount = /*#__PURE__*/function () {
    var _componentDidMount = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
      var _this2 = this;
      return _regenerator["default"].wrap(function _callee4$(_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            _events["default"].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["default"].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.find(function (item) {
          var props = item.props;
          return props.fieldName === column.fieldName;
        });
        childrenDom.push(child);
      };
      for (var i = 0; i < showColumns.length; i++) {
        _loop2();
      }
    } else {
      childrenDom = children.filter(function (item) {
        var props = item.props;
        return props.isShow;
      });
    }
    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["default"].Children.map(childrenDom, function (child, index) {
      var props = child.props;
      return /*#__PURE__*/_react["default"].createElement(_table["default"].Column, {
        className: "common-table-column",
        dataIndex: props.fieldName,
        colSpan: props.colSpan,
        width: 150,
        key: 'child' + index,
        cell: function cell(value, index, record) {
          //不可编辑只返回值
          if (!props.isEdit) return value;
          //当页面是编辑态或者是添加状态时
          if ((mode == 'add' || mode == 'edit') && editRowIndex == index) {
            return /*#__PURE__*/_react["default"].createElement(_renderChild["default"], {
              key: index,
              pageInfo: pageInfo,
              mode: mode,
              componentType: props.componentType
              // props={child.props}
              ,
              value: value || '',
              onChange: function onChange(data) {
                return cellChange(data, props.fieldName, index);
              }
            });
          }
          return value;
        },
        title: /*#__PURE__*/_react["default"].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["default"].createElement("div", {
      className: _variables.bizCssPrefix + '-common-table',
      style: style
    }, /*#__PURE__*/_react["default"].createElement(_table["default"], {
      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["default"].createElement(_table["default"].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["default"].createElement(_pagination["default"], {
      className: "common-table-pagination",
      current: this.state.current,
      showJump: false,
      onChange: this.onChange,
      pageSize: pageSize,
      total: total
    }));
  };
  return CommonTable;
}(_react["default"].Component);
CommonTable.displayName = 'CommonTable';
var _default = CommonTable;
exports["default"] = _default;