<template>
  <el-table
    ref="table"
    :height="height"
    class="bg-table"
    :data="rows"
    :stripe="stripe"
    :row-class-name="stripe ? tableRowClassName : ''"
    tooltip-effect="light"
    @selection-change="selectAction"
    @select="selectActionRow"
    @select-all="selectActionAll">
    <template #empty>
      <div class="empty_container">
        <img src="./imgs/img-no-data.png" alt="" />
        <div class="text">暂无数据</div>
      </div>
    </template>
    <el-table-column v-if="paddingLeft > 10" :width="paddingLeft - 10" />
    <el-table-column
      v-if="select"
      type="selection"
      :selectable="selectable"
      width="38">
      <!-- checkbox -->
    </el-table-column>
    <el-table-column
      v-if="isIndex"
      type="index"
      :label="indexLabel"
      :width="indexWidth"
      align="left">
      <!-- 序号 -->
    </el-table-column>
    <el-table-column v-if="sort" width="54" align="center">
      <template #header>
        <p style="width: 100%; text-align: center">排名</p>
      </template>
      <template #default="{ row, $index }">
        <p
          style="
            width: 100%;
            text-align: center;
            display: flex;
            align-items: center;
          ">
          <bg-icon
            v-if="row.sort == 1"
            style="font-size: 12px; color: #429e8a; margin-right: 9px"
            icon="#bg-ic-arrow-up-2" />
          <bg-icon
            v-else-if="row.sort == 2"
            style="font-size: 12px; color: #d75138; margin-right: 9px"
            icon="#bg-ic-arrow-down-2" />
          <bg-icon
            v-else
            style="font-size: 12px; color: #909bb6; margin-right: 9px"
            icon="#bg-ic-minus" />
          <span>{{ $index + 1 }}</span>
        </p>
      </template>
    </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"
      :fixed="header.fixed"
      show-overflow-tooltip>
      <template #header>
        <template v-if="$slots[`header-${header.prop}`]">
          <slot :name="`header-${header.prop}`"></slot>
        </template>
        <p v-else class="text-clip">{{ header.label }}</p>
      </template>
      <template #default="{ row, $index }">
        <slot
          v-if="$slots[header.prop]"
          :name="header.prop"
          :index="$index"
          :row="row"></slot>

        <template v-else>
          <col-node
            :val="row[header.prop]"
            :empty-col-placeholder="emptyColPlaceholder" />
          <!-- {{ row[header.prop] | ellipsis(header.max) }} -->
        </template>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { h, watch, ref } from "vue";
import { selectTableMixin } from "./hook/mixin-select-table";
let {
  nowSelectData,
  allSelectData,
  selectData,
  initSelectTableData,
  runPage,
  dealSelectData,
} = selectTableMixin();

const props = defineProps({
  height: {
    type: [Number, String],
    default: "auto",
  },
  headers: {
    type: Array,
    require: true,
    default: () => [],
  },
  rows: {
    type: Array,
    default: () => [],
  },
  select: {
    type: Boolean,
    default: false,
  },
  // selectable: {
  //   type: Function,
  // },
  isIndex: {
    type: Boolean,
    default: false,
  },
  indexLabel: {
    type: String,
    default: "序号",
  },
  stripe: {
    type: Boolean,
    default: false,
  },
  paddingLeft: {
    type: [Number, String],
    default: () => 12,
  },
  canEdit: {
    type: Boolean,
    default: false,
  }, // 多选框是否禁用
  canEditFlag: {
    type: Boolean,
    default: false,
  }, // 决定多选框是否禁用的字段
  sort: {
    type: Boolean,
    default: false,
  }, // 排名
  emptyColPlaceholder: {
    type: [String, Function],
    default: "-",
  }, // 后端行数据某列为空时显示的占位符号
  indexWidth: {
    type: Number,
    default: 54,
  },
});

const table = ref(null);

const emit = defineEmits(["selectAc", "select"]);
watch(
  () => props.rows,
  (n, o) => {
    if (n.length && props.select) {
      runPage();
      initSelectTableData(n).then((selectData) => {
        if (selectData.length) {
          setTimeout(() => {
            toggleRowArrSelection(selectData);
          });
        }
      });
    }
  }
);

const toggleRowSelection = (row, flag = true) => {
  table.value.toggleRowSelection(row, flag);
};
const selectAction = (selection) => {
  emit("selectAc", {
    allLength: Object.keys(allSelectData).length + nowSelectData.length,
    selection,
  });
};
const clearSelection = () => {
  table.value.clearSelection();
  emit("select", {
    allLength: Object.keys(allSelectData).length + nowSelectData.length,
    selection: [],
  });
};
const setSelectedRow = (row) => {
  toggleRowSelection(row);
};
const toggleRowArrSelection = (arr, flag = true) => {
  arr.forEach((e) => {
    toggleRowSelection(e, flag);
  });
};
const selectActionRow = (selection, row) => {
  selectData(selection);
  emit("select", {
    allLength: Object.keys(allSelectData).length + nowSelectData.length,
    selection,
  });
};
const selectActionAll = (selection) => {
  selectData(selection);
  emit("select", {
    allLength: Object.keys(allSelectData).length + nowSelectData.length,
    selection,
  });
};
const clearTable = () => {
  //清除选中数据,在页面状态更新时使用
  allSelectData = {};
  nowSelectData = [];
  clearSelection();
};
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 == 0) {
    return "white-row";
  } else {
    return "stripe-row";
  }
};
const selectable = (row, index) => {
  if (props.canEdit) {
    if (row[props.canEditFlag] && row[props.canEditFlag] == 1) {
      return false;
    } else {
      return true;
    }
  } else {
    return true;
  }
};

/**
 * 该功能用于表格数据某行的列数据后端未处理返回空字符串的情况，前端展示需要灵活处理的解决方案；
 * 改内部组件val参数为默认的原始数据，emptyColPlaceholder是自定义的类型
 * 一般情况下默认空则渲染为占位符 "-"
 * 当然也可以写渲染函数特殊处理此处，以满足特别需求，但是父组件传递的函数必须是渲染函数！
 */
const colNode = (props) => {
  if (props.val === "") {
    if (typeof props.emptyColPlaceholder === "string") {
      return h("span", props.emptyColPlaceholder);
    }
    if (typeof props.emptyColPlaceholder === "function") {
      return props.emptyColPlaceholder();
    }
  }
  return h("span", props.val);
};
defineExpose({
  clearTable,
  toggleRowSelection,
});
</script>
