import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray';
import _regeneratorRuntime from 'babel-runtime/regenerator';
import _asyncToGenerator from 'babel-runtime/helpers/asyncToGenerator';
import _extends from 'babel-runtime/helpers/extends';
import { defaultProps } from './props';
// import ColumnsSetterModal from './src/components/columns_setter_modal.vue'
// import SearchForm from './src/components/search_form.vue'
// import Sorter from './src/components/sorter.vue'
// import RenderComponent from './src/components/render.vue'
// import { SearchForm, Sorter, RenderComponent, ColumnsSetterModal } from './components/index'
import { isFunction, isPromise, transformArrToMap } from './src/utils/tools';
import './src/assets/index.less';

var ProTable = {
  name: 'AProTable',
  components: {
    // Button,
    // Table,
    // Form,
    // Row,
    // Col,
    // Input,
    // SearchForm,
    // ColumnsSetterModal,
    // Sorter,
    // RenderComponent
  },
  props: _extends({}, defaultProps),
  data: function data() {
    return {
      searchItems: [], //  查询表单的配置项
      columnsItems: [], // 表格列配置
      dataSource: [],
      paginationConfig: {}, // 分页配置
      tableLoading: false,
      validProps: [], // 权限，有效的权限列
      showColumns: [], // 可展示的列
      sortParams: {},
      exporting: false, // 表格导出ing,
      constance: this,
      summaryData: null,
      realRowKey: this.rowKey || 'rowKey'
    };
  },

  computed: {
    columnsWidth: function columnsWidth() {
      return this.showColumns.reduce(function (res, item) {
        res += item.width;
        return res;
      }, 0);
    },
    sorterColumns: function sorterColumns() {
      return this.showColumns.filter(function (item) {
        return !!item.sortTitle;
      });
    },
    scopedSlotList: function scopedSlotList() {
      return this.showColumns.filter(function (item) {
        return !!item.scopedSlots;
      });
    }
  },
  created: function created() {
    if (this.pagination) {
      this.paginationConfig = this.pagination;
    }
    this.initData();
  },
  mounted: function mounted() {},

  methods: {
    initData: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var _ref2, props;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!this.queryPermissionFn) {
                  _context.next = 19;
                  break;
                }

                // 需要请求权限数据
                this.tableLoading = true;
                _context.prev = 2;
                _context.next = 5;
                return this.queryPermissionFn();

              case 5:
                _ref2 = _context.sent;
                props = _ref2.props;

                this.validProps = props;
                this.tableLoading = false;
                this.initConfigData();
                _context.next = 17;
                break;

              case 12:
                _context.prev = 12;
                _context.t0 = _context['catch'](2);

                this.tableLoading = false;
                this.validProps = [];
                this.initConfigData();

              case 17:
                _context.next = 21;
                break;

              case 19:
                this.validProps = this.columns.map(function (_ref3) {
                  var dataIndex = _ref3.dataIndex;
                  return dataIndex;
                });
                this.initConfigData();

              case 21:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this, [[2, 12]]);
      }));

      function initData() {
        return _ref.apply(this, arguments);
      }

      return initData;
    }(),
    initConfigData: function initConfigData(data) {
      data = data || this.columns;
      var propsMap = transformArrToMap(this.validProps, 'permission');

      var _data$reduce = data.reduce(function (res, item) {
        var hideInTable = item.hideInTable,
            hideInSearch = item.hideInSearch,
            valueEnum = item.valueEnum;

        !hideInTable && propsMap[item.dataIndex] && res.columnsItems.push(item);
        if (!hideInSearch) {
          res.searchItems.push(item);
          if (!valueEnum) return res;
          if (Array.isArray(valueEnum)) {
            item.valueEnum = new Map([].concat(_toConsumableArray(valueEnum)));
          } else if (isFunction(valueEnum)) {
            if (isPromise(valueEnum())) {
              item.valueEnum = new Map();
              valueEnum().then(function (res) {
                item.valueEnum = new Map([].concat(_toConsumableArray(res)));
              });
            } else {
              item.valueEnum = valueEnum();
            }
          }
        }
        return res;
      }, {
        columnsItems: [],
        searchItems: []
      }),
          columnsItems = _data$reduce.columnsItems,
          searchItems = _data$reduce.searchItems;

      this.columnsItems = columnsItems;
      this.searchItems = searchItems;
    },
    handleQuery: function handleQuery(_ref4) {
      var _this = this;

      var searchParams = _ref4.searchParams,
          sortParams = _ref4.sortParams,
          cb = _ref4.cb;

      if (!searchParams) {
        searchParams = this.getSearchFormValues();
      }

      var _ref5 = this.paginationConfig || {},
          current = _ref5.current,
          pageSize = _ref5.pageSize;

      if (this.summeryFn) {
        pageSize -= 1;
      }

      // 处理排序，排序相关参数没有 则清空所有排序的active状态
      if (!sortParams) {
        this.sortParams = {};
        this.resetSortActiveItem();
      }
      var params = _extends({}, searchParams, sortParams, {
        pageNo: current,
        pageSize: pageSize
      });

      this.queryTableDataFn(params).then(function (_ref6) {
        var flag = _ref6.flag,
            data = _ref6.data,
            msg = _ref6.msg;

        // eslint-disable-next-line no-throw-literal
        if (flag !== 'S') throw '\u67E5\u8BE2\u5217\u8868\u6570\u636E\u5931\u8D25\uFF1A' + msg;

        var _ref7 = data || {},
            rows = _ref7.rows,
            total = _ref7.total;

        rows = rows || [];

        _this.paginationConfig.total = total || 0;
        // 请求汇总数据
        if (total > 0 && _this.summeryFn) {
          if (_this.summaryData) {
            // 从缓存取
            rows.unshift(_this.summaryData);
            _this.dataSource = _this.setDataRowKeyValue(rows);
          } else {
            // 请求
            _this.summeryFn(params, function (summaryRes) {
              _this.summaryData = summaryRes;
              rows.unshift(summaryRes);
              _this.dataSource = _this.setDataRowKeyValue(rows);
            });
          }
        }
        cb && cb();
      })['catch'](function (error) {
        _this.$message.error(error);
        cb && cb();
      });
    },
    setDataRowKeyValue: function setDataRowKeyValue() {
      var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

      if (!this.rowKey) {
        // 如果没有传入rowkey 则自定义
        data = data.map(function (item, index) {
          item.rowKey = index;
          return item;
        });
      }
      return data;
    },
    updateColumns: function updateColumns(cols) {
      this.showColumns = cols.map(function (item) {
        var sortable = item.sortable,
            title = item.title,
            width = item.width,
            others = _objectWithoutProperties(item, ['sortable', 'title', 'width']);

        width = width || 120;
        if (sortable) {
          return _extends({
            sortable: sortable,
            sortTitle: title,
            slots: { title: 'custom-' + others.dataIndex },
            ellipsis: true,
            width: sortable ? width + 25 : width
          }, others);
        }
        return item;
      });
    },
    handleTableChange: function handleTableChange(_ref8) {
      var current = _ref8.current,
          pageSize = _ref8.pageSize;

      if (this.pagination.pageSize !== pageSize) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = 1;
        this.handleQuery({ sortParams: this.sortParams });
      } else if (this.pagination.current !== current) {
        this.pagination.current = current;
        this.handleQuery({ sortParams: this.sortParams });
      }
    },
    handleSortChange: function handleSortChange(orderColumn, orderRule) {
      this.resetSortActiveItem(orderColumn);
      this.sortParams = {
        orderColumn: orderColumn,
        orderRule: orderRule
      };
      this.handleQuery({ sortParams: this.sortParams });
    },
    resetSortActiveItem: function resetSortActiveItem(orderColumn) {
      // 清除其他排序数据
      var sortColList = this.$refs.sortCol;
      this.sorterColumns.forEach(function (_ref9, index) {
        var dataIndex = _ref9.dataIndex;

        if ((dataIndex !== orderColumn || !orderColumn) && sortColList[index]) {
          sortColList[index].reset();
        }
      });
    },
    handleExport: function handleExport() {
      var _this2 = this;

      this.exporting = true;
      var searchParams = this.getSearchFormValues();
      this.exportTableFn(searchParams, function () {
        _this2.exporting = false;
      });
    },
    getColumnsKey: function getColumnsKey() {
      return this.showColumns.map(function (item) {
        return item.dataIndex;
      });
    },
    handleTabOpen: function handleTabOpen() {
      this.openTabFn && this.openTabFn.apply(this, arguments);
    },
    getSearchFormValues: function getSearchFormValues() {
      return this.$refs.searchForm ? this.$refs.searchForm.getFieldsValue() : {};
    },
    onTdItemClick: function onTdItemClick(bindHandler, dataIndex, record) {
      if (!bindHandler) return;
      this.$emit('tdItemClick', dataIndex, record);
    },
    renderColumns: function renderColumns() {
      return;
      // if(this.columnsSettable) {
      //   return (
      //     <ColumnsSetterModal
      //       propList={columnsItems}
      //       localStorageKey={localStorageKey}
      //       onChangeCoumns={updateColumns}
      //     ></ColumnsSetterModal>
      //   )
      // }
    },
    renderSlot: function renderSlot(customSlots, scopedSlots, record, text, bindHandler, dataIndex, ellipsis, formatter) {
      var h = this.$createElement;

      if (customSlots) {
        return h('slot', {
          attrs: { name: scopedSlots.customRender, 'slot-scope': record }
        });
      } else if (text) {
        if (ellipsis) {
          return h(
            'span',
            { key: scopedSlots.customRender, on: {
                'click': this.onTdItemClick(bindHandler, dataIndex, record)
              }
            },
            [h(
              'a-tooltip',
              {
                attrs: { placement: 'topLeft' }
              },
              [h(
                'template',
                { slot: 'title' },
                [h('span', [text])]
              ), this.renderContent(renderFn, formatter, text, record)]
            )]
          );
        }
        return h(
          'span',
          { key: scopedSlots.customRender, on: {
              'click': this.onTdItemClick(bindHandler, dataIndex, record)
            }
          },
          [this.renderContent(renderFn, formatter, text, record)]
        );
      }
      return h(
        'template',
        {
          directives: [{
            name: 'else',
            value: true
          }]
        },
        ['--']
      );
    },
    renderContent: function renderContent(renderFn, formatter, text, record) {
      var h = this.$createElement;

      if (renderFn) {
        return;
        //  (
        //   // <span key={scopedSlots.customRender} onClick={this.onTdItemClick(bindHandler, dataIndex, record)}>
        //     // <RenderComponent renderFn={renderFn} infoData={{text, record}} />
        //   // </span>
        // )
      } else if (formatter) {
        return (
          // <span key={scopedSlots.customRender} onClick={this.onTdItemClick(bindHandler, dataIndex, record)}>
          h('template', [formatter(text)])
          // </span>

        );
      }
      return (
        // <span key={scopedSlots.customRender} onClick={this.onTdItemClick(bindHandler, dataIndex, record)}>
        h('div', [text || '--'])
        // </span>

      );
    }
  },
  render: function render() {
    var h = arguments[0];

    return h('template', [h(
      'div',
      { 'class': 'pro-table' },
      [h('div', { 'class': 'search-form' }), h(
        'slot',
        {
          attrs: { name: 'actionBar' }
        },
        [h(
          'div',
          { 'class': 'actions-bar' },
          [h(
            'a-row',
            { style: 'padding-left: 16px; padding-right: 16px;' },
            [h(
              'a-col',
              {
                attrs: { span: 12 },
                style: 'text-align: left' },
              [h(
                'a-button',
                {
                  attrs: { type: 'primary', loading: exporting },
                  on: {
                    'click': handleExport
                  }
                },
                ['\u5BFC\u51FA']
              )]
            ), h(
              'a-col',
              {
                attrs: { span: 12 },
                style: 'text-align: right' },
              [this.renderColumns()]
            )]
          )]
        )]
      ), h(
        'a-table',
        {
          attrs: { rowKey: realRowKey,
            loading: tableLoading,
            columns: showColumns,
            'data-source': dataSource,
            scroll: { x: columnsWidth },
            pagination: paginationConfig
          },
          on: {
            'change': handleTableChange
          },

          'class': 'white-bg',
          ref: 'table' },
        [sorterColumns.map(function (_ref10) {
          var dataIndex = _ref10.dataIndex,
              sortTitle = _ref10.sortTitle,
              slots = _ref10.slots;

          return;
          // return <sorter key={dataIndex}
          // slot={slots.title} title={sortTitle} ref="sortCol"
          // onHandleChange={direction => this.handleSortChange(dataIndex, direction)}
          // />
        }), scopedSlotList.map(function (_ref11) {
          var dataIndex = _ref11.dataIndex,
              customSlots = _ref11.customSlots,
              scopedSlots = _ref11.scopedSlots,
              renderFn = _ref11.renderFn,
              ellipsis = _ref11.ellipsis,
              bindHandler = _ref11.bindHandler,
              formatter = _ref11.formatter;

          return h(
            'template',
            { slot: scopedSlots.customRender, attrs: { 'slot-scope': 'text, record' }
            },
            [renderSlot()]
          );
        })]
      )]
    )]);
  }
};

/* istanbul ignore next */
ProTable.install = function (Vue) {
  // Vue.use(Base);
  Vue.component(ProTable.name, ProTable);
};

export default ProTable;