<template>
  <el-table
    ref="bgTable"
    :data="tablerows"
    style="width: 100%"
    class="bg-table"
    :height="height"
    stripe
    tooltip-effect="light"
    :border="border"
    @selection-change="selectAction"
    @sort-change="sortChange"
  >
    <!-- 多选框 -->
    <el-table-column
      v-if="isSelect"
      type="selection"
      :selectable="selectables"
      width="50"
      align="center"
    >
    </el-table-column>
    <el-table-column
      v-if="isIndex"
      type="index"
      :label="indexLabel"
      width="50"
    >
      <!-- 序号 -->
    </el-table-column>
    <el-table-column
      v-for="(header, index) in headers"
      :key="'col_' + index"
      :width="header.width"
      :min-width="header.minWidth"
      :align="header.align"
      :show-overflow-tooltip="showOverflowTooltip"
      :sortable="header.sortable ? 'custom' : null"
      :prop="header.prop"
    >
      <template #header>
        <p class="text-header">{{ header.label }}</p>
      </template>
      <template #default="scope">
        <slot
          v-if="$slots[header.prop]"
          :index="scope.$index"
          :name="header.prop"
          :row="scope.row"
          :header="header"
        />
        <template v-else>
          {{ scope.row[header.prop] || "-" }}
        </template>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import {
  defineProps,
  onMounted,
  computed,
  defineEmits,
  watch,
  getCurrentInstance,
} from "vue";
const { proxy } = getCurrentInstance();

let props = defineProps({
  headers: { type: Array, default: () => [] }, // 表头
  rows: { type: Array, default: () => [] }, // 表格数据
  //标签列是要展开所有内容
  showOverflowTooltip: {
    type: Boolean,
    default: true,
  },
  //table高度
  height: {
    type: String,
    default: undefined,
  },
  // 是否有多选列
  isSelect: {
    type: Boolean,
    default: false,
  },
  // 是否有border
  border: {
    type: Boolean,
    default: false,
  },
  isIndex: {
    type: Boolean,
    default: false,
  },
  indexLabel: {
    type: String,
    default: "序号",
  },
});
const emits = defineEmits(["select", "sortchange"]);

// 权限展示列的时候计算属性
let tablerows = computed(() => {
  return props.rows;
});

watch(
  props.rows,
  (newValue) => {
    toggleRowSelection(newValue);
  },
  { immediate: false, deep: true }
);
// ***********多选框功能start
// 选中项
const selectAction = (selection) => {
  emits("select", selection);
};
// 后端返回数据带选中内容
const toggleRowSelection = (rows) => {
  rows.forEach((row) => {
    if (row.isSelet == true) {
      proxy.$nextTick(function () {
        proxy.$refs.bgTable.toggleRowSelection(row, true);
      });
    }
  });
};
// *********多选是否禁用**********
const selectables = (row) => {
  if (row.state !== 2) {
    return true;
  }
};
// ***********多选框功能end
const clearSelection = () => {
  proxy.$refs.bgTable.clearSelection();
};

const sortChange = (column) => {
  emits("sortchange", column);
};

defineExpose({ clearSelection });
</script>
