<script setup name="table">
import {outExportExcel} from '@/utils/exportExcel.js'
import {ref, computed} from 'vue'
const props = defineProps({
  height: {
    type: String,
    default: '800px'
  },
  data: {
    type: Array,
    default: () => ([]),
  },
  column: {
    type: Array,
    default: () => ([]),
  },
  tableName: {
    type: String,
    default: '',
  },
  tableId: {
    type: String,
    default: '',
  },
  loading: {
    type: Boolean,
    default: false,
  },
  showSummary:{
    type: Boolean,
    default: false,
  },
  summaryMethod: {
    type: Function,
    default: () => () => {}
  }
})
const emits = defineEmits(['export'])
const funExport = () => {
  const columns = props.column.map(o => {
    return {
      ...o,
      property: o.prop
    }
  })
  let summary = []
  const summaryObj = {}
  const tHeader = []
  const tHeaderKeys = []
  const tableData = []
  if(props.showSummary && props.summaryMethod){
    summary = props.summaryMethod({columns,data: props.data})
  }
  for(const key in props.column){
    tHeader.push(props.column[key].label)
    tHeaderKeys.push(props.column[key].prop)
    if(props.showSummary && props.summaryMethod){
      summaryObj[props.column[key].prop] = summary[key] 
    }
  }
  const exportName = props.tableName
  tableData.push(...props.data)
  if(props.showSummary && props.summaryMethod){
    tableData.push(summaryObj)
  }
  outExportExcel(tHeader,tHeaderKeys,tableData,exportName)
}
const tableRef = ref('')
const tableHeight =  computed(() => {
  return tableRef.value.offsetHeight? tableRef.value.offsetHeight - 46 : 705
})
</script>
<template>
  <div ref="tableRef" class="p-[10px]"
    :style="{ height: typeof props.height === 'string' ? props.height : props.height + 'px' }">
    <div class="flex justify-between items-center pb-[10px]">
      <h3>{{props.tableName}}</h3>
      <el-button size="small" type="primary" @click="funExport" :disabled="!props.tableId">数据导出</el-button>
    </div>
    <el-table :data="props.data"
      stripe
      size="small" v-loading="props.loading"
      :max-height="tableHeight"
      :style="{ width: '100%'}">
      <el-table-column align="center" show-overflow-tooltip v-for="item in props.column" :prop="item.prop" :label="item.label" sortable resizable :min-width="item.width? item.width : 80" />
    </el-table>
  </div>
</template>