'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _VIEW$EDIT;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _constant = require('../../constant');

var _dictCodes = require('../../../../constant/dictCodes');

var _util = require('../../../list/util');

var _mxa = require('../../../../../components/mxa');

var _ParamHelper = require('../../../../utils/ParamHelper');

var _ModalWrapper = require('../../../../pageContainer/ModalWrapper');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                * Created by baoyinghai on 4/20/17.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */


var InnerList = function (_React$Component) {
  _inherits(InnerList, _React$Component);

  function InnerList(props) {
    _classCallCheck(this, InnerList);

    var _this = _possibleConstructorReturn(this, (InnerList.__proto__ || Object.getPrototypeOf(InnerList)).call(this, props));

    _this._onChange = function () {
      if (!_this.mainEntityKey) {
        console.error('mainEntityKey can not be null');
      } else {
        var onChange = _this.props.onChange;

        onChange && onChange(_this.state.dataSource.map(function (r) {
          return r[_this.mainEntityKey];
        }));
      }
    };

    _this._onRowClick = function (record, index) {
      if (_this.state.selectedType === _dictCodes.LIST_SELECTTYPE.INLINE) return;
      console.log('onRowClick ==> ', record, index);

      var selectedIndex = _this.state.selectedRowKeys.indexOf(record.key);
      if (selectedIndex > -1) {
        _this.setState({
          selectedRowKeys: _this.state.selectedRowKeys.filter(function (item) {
            return item !== record.key;
          }),
          selectedRows: _this.state.selectedRows.filter(function (item) {
            return item.key !== record.key;
          })
        });
      } else if (_this.state.selectedType === _dictCodes.LIST_SELECTTYPE.RADIO) {
        _this.setState({
          selectedRowKeys: [record.key],
          selectedRows: [record]
        });
      } else {
        _this.setState({
          selectedRowKeys: _this.state.selectedRowKeys.concat(record.key),
          selectedRows: _this.state.selectedRows.concat(record)
        });
      }
      // TODO: 触发onchange事件
    };

    _this._getParamFromQuery = function (bindParameters) {
      return (0, _ParamHelper.getParamByBindParameters)(_this.props.query || [], bindParameters);
    };

    _this._getParamFromDetail = function (bindParameters) {
      return (0, _ParamHelper.getParamByBindParameters)(_this.props.formDataSource.detailResult || [], bindParameters);
    };

    _this._createParam = function (bindParameters) {
      return Object.assign({}, _this._getParamFromQuery(bindParameters), _this._getParamFromDetail(bindParameters));
    };

    _this._renderColumn = function (text, fieldContent) {
      var temp = (0, _util.renderColumn)(text, fieldContent);
      var tdRender = _react2.default.createElement(
        'span',
        null,
        temp
      );
      if (typeof temp === 'string' && temp.length > 20) {
        tdRender = _react2.default.createElement(
          _mxa.Tooltip,
          { title: temp, placement: 'top' },
          _react2.default.createElement(
            'span',
            null,
            temp.substring(0, 18) + '...'
          )
        );
      }
      return tdRender;
    };

    _this._processColumns = function (fields) {
      var columns = [];
      if (fields && fields.length > 0) {
        (function () {
          var fieldsObject = (0, _util.arr2obj)(fields, 'name');
          fields.forEach(function (item, index) {
            if (item.isMainEntityKey) _this.mainEntityKey = item.name;
            columns.push({
              width: (item.displayColumnLength || 18) * 12,
              key: index,
              title: item.description,
              dataIndex: item.name,
              render: function render(text) {
                return _this._renderColumn(text, fieldsObject[item.name]);
              }
            });
          });
        })();
      }
      return columns;
    };

    _this._addKey = function (dataSource) {
      return dataSource && dataSource.map(function (item, index) {
        return _extends({}, item, { key: index });
      });
    };

    _this._processRowSelection = function (selectType) {
      return {
        type: _dictCodes.LIST_SELECTTYPE.INLINE,
        onChange: function onChange(selectedRowKeys, selectedRows) {
          console.log('onChange ==> ', 'selectedRowKeys: ' + selectedRowKeys, 'selectedRows: ', selectedRows);
          _this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
        },
        onSelect: function onSelect(record, selected) {
          console.log('onSelect ==> ', record, selected);
          // this.setState({ selectedRows });
        },
        onSelectAll: function onSelectAll(selected, selectedRows, changeRows) {
          console.log('onSelectAll ==> ', selected, selectedRows, changeRows);
          var selectedRowKeys = [];
          if (selected) {
            selectedRowKeys = selectedRows.map(function (row) {
              return row.key;
            });
          }
          _this.setState({ selectedRows: selectedRows, selectedRowKeys: selectedRowKeys });
        },
        selectedRowKeys: _this.state.selectedRowKeys
      };
    };

    _this._appendNoPaggingParams = function (param) {
      return _extends({}, param, { listInstruction: _dictCodes.LIST_PATTERN.NOPAGING });
    };

    _this._callback = function (value, selectType) {
      _this.setState({
        dataSource: value
      }, function () {
        return _this._onChange();
      });
    };

    _this._initExtraData = function () {
      if (_this.mainEntityKey && _this.state.dataSource) {
        return _this.state.dataSource.map(function (item) {
          return item[_this.mainEntityKey];
        });
      }
      return null;
    };

    _this._showModal = function () {
      var allItemAction = _this.props.allItemAction;

      var p = { requestParamsBean: { listInstruction: _dictCodes.LIST_PATTERN.NOPAGING } };
      p.isModalInput = true;
      (0, _ModalWrapper.showModal)(Object.assign({}, _this._createParam(allItemAction.bindParameters), p), allItemAction.templateType, allItemAction.actionLink, _this._callback, _this._initExtraData());
    };

    _this._renderToolBar = function () {
      return _react2.default.createElement(
        'div',
        { className: 'inner-table-tool-bar' },
        _react2.default.createElement(
          'a',
          { onClick: _this._showModal },
          '\u4FEE\u6539'
        )
      );
    };

    _this.state = {
      columns: [],
      dataSource: [],
      selectedRows: [],
      selectedRowKeys: [],
      rowSelection: {}
    };
    // this.mainEntityKey  主键
    return _this;
  }

  _createClass(InnerList, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var _this2 = this;

      var selectedItemAction = this.props.selectedItemAction;

      this.props.exec(function () {
        return _this2.props.fetch(_this2.props.selectedItemAction.actionLink, _this2._appendNoPaggingParams(_this2._createParam(selectedItemAction.bindParameters))).then(function (response) {
          var pageResult = response.pageResult,
              fields = response.fields,
              selectType = response.selectType;

          var dataSource = pageResult.contentList;
          var columns = _this2._processColumns(fields);
          _this2.setState({
            columns: columns,
            dataSource: _this2._addKey(dataSource),
            selectType: selectType
          }, function () {
            return _this2._onChange();
          });
        });
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var rowSelection = this._processRowSelection(this.state.selectType);
      return _react2.default.createElement(
        'div',
        null,
        this._renderToolBar(),
        _react2.default.createElement(_mxa.Table, {
          rowSelection: rowSelection,
          locale: { emptyText: '无符合条件的相关数据' },
          columns: this.state.columns,
          dataSource: this.state.dataSource,
          onChange: this._onChange,
          onRowClick: this._onRowClick,
          prefixCls: 'inner-table',
          isInner: true
        })
      );
    }
  }]);

  return InnerList;
}(_react2.default.Component);

var compRender = function compRender(config) {
  var _config$record = config.record,
      record = _config$record === undefined ? {} : _config$record,
      props = config.props;
  var actions = record.displayComponent.actions;

  var selectedItemAction = actions.filter(function (i) {
    return i.type === 'SelectedItemAction';
  })[0];
  var allItemAction = actions.filter(function (i) {
    return i.type === 'AllItemAction';
  })[0];
  return _react2.default.createElement(InnerList, {
    query: props.query,
    formDataSource: props.dataSource,
    exec: props.exec,
    fetch: props.fetch,
    selectedItemAction: selectedItemAction,
    allItemAction: allItemAction
  });
};

exports.default = (_VIEW$EDIT = {}, _defineProperty(_VIEW$EDIT, _constant.VIEW, function () {
  return _react2.default.createElement(
    'span',
    null,
    '\u672A\u5B9A\u4E49'
  );
}), _defineProperty(_VIEW$EDIT, _constant.EDIT, compRender), _VIEW$EDIT);