// 列设置用jsx实现起来较为困难
import ColumnSetting from './column'

export default {
  props: {
    pageIndex: {
      default: 1,
      type: Number,
    },
    pageSize: {
      default: 10,
      type: Number,
    },
    loadData: {
      type: Function,
      require: true,
    },
    columns: {
      type: Array,
      require: true,
    },
    moreQuery: {
      type: Function
    },
    autoLoad: {
      type: Boolean,
      default: true
    }
  },

  data() {
    return {
      loading: false,

      type: '',

      data: [],

      pagination: {
        current: this.pageIndex,
        pageSize: this.pageSize,
        total: 0,
        size: 'small',
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `总共${total}条数据`
      },

      sorter: {
        sortField: '',
        sortOrder: '',
      },

      columnSettingVisible: false
    };
  },

  created() {
    if (this.autoLoad)
      this.onLoadData()
  },

  methods: {

    renderColumnSetting() {

      const props = {
        visible: this.columnSettingVisible,
        placement: 'bottomRight'
      }

      const on = {
        visibleChange: (visible) => {
          this.columnSettingVisible = visible
        }
      }

      return (
        <a-dropdown {...{ props, on }}>
          <a-button onClick={() => this.columnSettingVisible = true}>设置列</a-button>
          <a-menu slot="overlay" onClick={() => { return false }}>
            {
              this.columns.map(column => {
                return (
                  <a-menu-item key={column.dataIndex || column.key}>
                    <a-checkbox checked={column.hidden} onChange={() => { column.hidden = !column.hidden }}>{column.title}</a-checkbox>
                  </a-menu-item>
                )
              })
            }
          </a-menu>
        </a-dropdown>
      )
    },

    onLoading() {
      this.loading = {
        indicator: <a-icon type="loading" spin />
      }
    },

    onLoaded() {
      this.loading = false
    },

    onLoadData() {
      this.onLoading()

      this.loadData({
        pageIndex: this.pagination.current,
        pageSize: this.pagination.pageSize,
        ...this.sorter
      }).then((res) => {
        if (res.rows || res.data || res.items) {
          // 普通表格
          this.type = 'table'
          this.data = res.rows || res.data || res.items
          this.pagination.total = res.totalCount
        } else if (res) {
          // 树形表格
          this.type = 'tree'
          this.data = this.onClearChildren(res)
          this.pagination = false
        }
      }).finally(() => {
        this.onLoaded()
      })
    },

    onReloadData(refresh = false) {
      if (refresh && refresh.constructor === Boolean && this.pagination.constructor === Object) {
        this.pagination.current = this.pageIndex
        this.pagination.pageSize = this.pageSize
      }
      this.onLoadData()
    },

    onTableChange(pagination, filters, sorter) {
      this.pagination = pagination
      this.sorter = {
        sortField: sorter.field,
        sortOrder: sorter.order,
      }
      this.onLoadData()
    },

    /**
     * 清除没有子节点内容的子节点位置
     */
    onClearChildren(data) {
      data.forEach(p => {
        if (p.children) {
          if (p.children.length) {
            p.children = this.onClearChildren(p.children)
          } else {
            delete p.children
          }
        }
      })
      return data
    },

    onQuery() {
      this.$emit('query')
    },

    onResetQuery() {
      this.$emit('resetQuery')
      this.$emit('reset-query')
    },

    onAddRow(row = {}) {
      if (!this.data.find(p => !p.id))
        this.data.push(row)
    },

    onDeleteRow(row) {
      if (row && this.data.indexOf(row) > -1) {
        this.data.splice(this.data.indexOf(row), 1)
      }
    },

    getData() {
      return this.data
    },
  },

  render() {
    const props = {
      loading: this.loading,
      pagination: this.pagination,
      dataSource: this.data,
      columns: this.columns.filter(p => !p.hidden),
      bordered: true,
      size: 'middle',
      rowKey: record => record.id || Math.random().toString(16).slice(2),
      scroll: { x: 'max-content' },
      ...this.$attrs
    }

    const on = {
      change: this.onTableChange,
      ...this.$listeners
    }

    const queryOn = {
      'submit.native.prevent': () => { }
    }

    return (
      <section>
        {
          this.$scopedSlots.query &&
          <div class="yo-query-bar">
            <a-form-model layout="inline" {...{ on: queryOn }}>
              {this.$scopedSlots.query()}
              <a-form-model-item>
                <a-button-group class="mr-xs">
                  <a-button onClick={this.onQuery} html-type="submit" type="primary">查询</a-button>
                  <a-button onClick={this.onResetQuery}>重置</a-button>
                </a-button-group>
                {
                  this.moreQuery && <a-button onClick={this.moreQuery}>更多查询条件</a-button>
                }
              </a-form-model-item>
            </a-form-model>
          </div>
        }
        <div class="yo-action-bar">
          <div class="yo-action-bar--actions">
            {this.$scopedSlots.operator && this.$scopedSlots.operator()}
          </div>
          <div class="yo-action-bar--actions">
            <a-button-group>
              <a-button onClick={this.onReloadData}>刷新</a-button>
              {
                this.type === 'table' && <ColumnSetting {...{ props: { columns: this.columns } }} />
              }
            </a-button-group>
          </div>
        </div>
        <a-table class="yo-table" {...{ props, on, scopedSlots: { ...this.$scopedSlots } }}>
          {Object.keys(this.$slots).map((name) => (
            <template slot={name}>{this.$slots[name]}</template>
          ))}
        </a-table>
      </section>
    )
  },
}