<template>
  <div class="app-table" v-loading="loading">
    <div class="app-table__header" v-if="showHeader">
      <div>
        <slot name="header"></slot>
      </div>
      <div>
        <el-button-group>
          <el-button icon="Refresh" @click="refresh" />
          <el-button icon="Setting" @click="showTableSetting = true" />
        </el-button-group>
      </div>
    </div>
    <div class="app-table__container">
      <el-table ref="tableRef" v-bind="$attrs" highlight-current-row scrollbar-always-on border>
        <!-- 展开行 -->
        <el-table-column type="expand" v-if="$slots.expand">
          <template #default="{ row, $index }">
            <slot name="expand" :row="row" :index="$index"></slot>
          </template>
        </el-table-column>
        <!-- 数据列 -->
        <template v-for="(item, index) in columns" :key="index">
          <el-table-column :class-name="item.className" :align="item.align ?? 'left'" :min-width="120"
            :width="item.width" :label="item.label" :prop="item.prop" :fixed="item.fixed || false"
            :sortable="item.sortable" v-if="item.show">
            <template #default="{ row, $index }">
              <slot :name="item.prop" :row="row" :value="row[item.prop]" :index="$index">
                {{ handleNoneValue(row[item.prop]) }}
              </slot>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <div class="app-table__footer">
      <slot name="footer"></slot>
    </div>
    <app-table-setting :columns="columns" @update="updateColumn" @closed="showTableSetting = false"
      v-if="showTableSetting" />
  </div>
</template>

<script lang="ts">
import { defineComponent, shallowRef, PropType } from 'vue'
import { handleNoneValue } from '@/filters'
import AppTableSetting from '../table-setting/index.vue'

export default defineComponent({
  inheritAttrs: false,
  components: {
    AppTableSetting
  },
  emits: ['refresh', 'update:columns'],
  props: {
    columns: {
      type: Array as PropType<Model.TableColumn[]>,
      default: () => ([])
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    loading: {
      type: Boolean,
      default: false
    },
  },
  setup(props, { emit, expose }) {
    const tableRef = shallowRef()
    const showTableSetting = shallowRef(false)
    const refresh = () => emit('refresh')
    const updateColumn = (value: Model.TableColumn[]) => emit('update:columns', value)

    expose({
      elTable: tableRef
    })

    return {
      tableRef,
      showTableSetting,
      handleNoneValue,
      refresh,
      updateColumn,
    }
  },
})
</script>

<style lang="less">
@import './index.less';
</style>