<template>
  <el-table :data="tableData.dataSource" v-bind="getBindValues" v-loading="getBindValues.loading" ref="tableElRef"
    @selection-change="selectionChange">
    <template v-if="getBindValues.rowSelection">
      <el-table-column type="selection" width="55" />
    </template>
    <template v-for="item in tableData.columns" :key="item.prop">
      <el-table-column v-bind="item" :prop="item.prop" :width="item.width" :label="item.label">
        <template #header v-if="item.slotHeader">
          <slot :name="`header-${item.slotName}`" v-bind="item"></slot> 
        </template>
        <template #default="scope" v-if="item.slot">
          <slot :name="item.slotName" v-bind="scope"></slot>
        </template>
      </el-table-column>
    </template>
  </el-table>
</template>

<script lang="ts" setup>
import { ref, reactive, unref, computed, useAttrs } from "vue";
import { BaseTableProps, TableActionType, TableColumns, TableRef } from "./types";
import { useLoading } from "./hooks/useLoading";

// 定义的一些基础数据
const innerPropsRef = ref<Partial<BaseTableProps>>();
const selectedRowRef = ref<Recordable[]>([]);
const tableElRef = ref<TableRef>();
const tableData: Partial<BaseTableProps> = reactive({
  columns: [],
  dataSource: [],
  rowSelection: false
});

// 获取一些设置的参数
const getProps = computed(() => {
  return { ...unref(innerPropsRef) } as BaseTableProps;
});

// loading
const { getLoading, setLoading } = useLoading(getProps);

// 获取属性穿透属性
const attrs = useAttrs()
// 用于属性穿透
const getBindValues = computed(() => {
  // 默认属性
  const propsData: Recordable = {
    ...unref(getProps),
    loading: unref(getLoading),
    ...attrs,
  }

  return propsData;
});

// 事件处理
function setProps(props: Partial<BaseTableProps>) {
  if (!props) return;
  innerPropsRef.value = { ...unref(innerPropsRef), ...props };
  tableData.columns = props.columns;
  tableData.dataSource = props.dataSource;
}
const setColumns = (props: TableColumns[]) => {
  if (unref(props).length === 0) return;
  tableData.columns = props
};
const setDataSource = (props: Recordable[]) => tableData.dataSource = props;
const getDataSource = <T = Recordable>() => tableData.dataSource as T[];
const selectionChange = (rowData: Recordable[]) => selectedRowRef.value = rowData;
const clearSelectedRow = () => selectedRowRef.value = [];
const getSelectRows = <T = Recordable>() => unref(selectedRowRef) as T[];

// 用于外部操作table
const tableAction: TableActionType = {
  setColumns, //设置表头
  setProps, //设置表格内容
  setDataSource,//设置表格数据
  getDataSource,//获取表格数据
  setLoading,//设置表格loading
  clearSelectedRow, // 清除表格选中的内容
  getSelectRows, //获取表格选中的内容
  tableElRef,// 定义的DOM节点
};
const emit = defineEmits(["register"]);
emit("register", tableAction);
</script>
