<template>
  <!-- <el-affix :offset="65" v-if="props.showToolsBar">
   
  </el-affix> -->
  <BaseToolBar
    @refresh="refresh"
    style="background-color: #fff; padding: 15px 0; margin-top: -15px">
    <!-- <download-excel :data="tableData.data" :fields="fields">
      <el-button size="small" style="margin-left: 15px"
        ><template #icon>
          <el-tooltip placement="top" effect="light">
            <template #content>导出当前</template>
            <el-icon>
              <Download />
            </el-icon>
          </el-tooltip>
        </template>
      </el-button>
    </download-excel>
    <download-excel :fetch="requestAllData" :fields="fields">
      <el-tooltip placement="top" effect="light">
        <template #content>导出全部</template>
        <el-button size="small" style="margin-left: 15px"
          ><template #icon
            ><i class="base-system base-system-rizhixiazai-xiazaisuoyou"></i>
          </template>
        </el-button> </el-tooltip
    ></download-excel> -->

    <div style="margin-left: 15px"><slot name="toolsBar"></slot></div>

    <template #rightContent>
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        v-if="showPagination"
        :page-size="tableData.pageSize"
        :total="tableData.total"
        :current-page="tableData.pageNumber"
        size="small"
        @current-change="currentPageChange" />
    </template>
  </BaseToolBar>

  <el-table
    ref="dataTable"
    :data="tableData.data"
    style="
      width: 100%;
      min-height: 130px;
      padding-top: 15px;
      padding-bottom: 20px;
    "
    v-loading="tableLoadingData.show"
    empty-text="暂无数据"
    highlight-current-row
    :element-loading-text="tableLoadingData.text"
    v-bind="$attrs">
    <slot></slot>
    <slot name="colunm"></slot>
  </el-table>
</template>

<script lang="ts" setup>
import {
  reactive,
  ref,
  onMounted,
  watch,
  nextTick,
  onBeforeUnmount,
} from "vue";
import api from "@/lib/request";
import { ElMessage } from "element-plus";
import BaseToolBar from "./toolBar/baseToolBar.vue";
import { tableOptionType, tableDataType } from "@/types/table";
let tableLoadingData = reactive({
  show: false,
  text: "正在加载数据...",
});

const tableData = ref<tableDataType>({
  data: [],
  total: 0,
  pageNumber: 1,
  pageSize: 10,
});
const dataTable = ref<any>(null);
const executeType = ref("");

const methods = {
  async setDataType(type: "reset" | "list" | "search") {
    nextTick(async () => {
      if (executeType.value !== type) {
        tableData.value.pageNumber = 1;
        tableData.value.pageSize = 10;
      }
      executeType.value = type;

      if (type === "list") await initData();
      if (type === "search") await queryData();
      if (type === "reset") {
        tableData.value.pageNumber = 1;
        tableData.value.pageSize = 10;
        await initData();
      }
      emits("update");
    });
  },
};
defineExpose({ methods, tableData });
const props = withDefaults(
  defineProps<{
    option: tableOptionType;
    showPagination?: boolean;
    showToolsBar?: boolean;
    resize?: boolean;
    fields?: string[];
  }>(),
  {
    option: () => {
      return {
        url: "",
        searchParams: () => {
          return {};
        },
        searchUrl: "",
        executeType: "list",
      };
    },
    showToolsBar: true,
    showPagination: true,
    resize: true,
  }
);

const emits = defineEmits(["tableUpdate", "searchUpdate", "update"]);

let tableHeight = ref(300);
const updateTableHeight = () => {
  // 计算高度，减去 header 和分页器的高度
  const headerHeight = 55; // 你的标题栏高度
  const toolBarHeight = 147; // 你的分页器高度
  const padding = 150; // 额外的间距

  tableHeight.value =
    window.innerHeight - headerHeight - toolBarHeight - padding;
};

// watch(
//   () => tableData.value.pageNumber,
//   () => {
//     nextTick(() => {
//       methods.setDataType(executeType.value);
//     });
//   }
// );

// watch(
//   () => tableData.value.pageSize,
//   () => {
//     nextTick(() => {
//       methods.setDataType(executeType.value);
//     });
//   }
// );

onBeforeUnmount(() => {
  window.removeEventListener("resize", updateTableHeight);
});

onMounted(async () => {
  await initData();
  updateTableHeight();
  window.addEventListener("resize", updateTableHeight);
});

async function initData() {
  tableLoadingData.show = true;
  let dataList = await api().get(props.option.url, {
    params: {
      pageSize: tableData.value.pageSize,
      pageNumber: tableData.value.pageNumber,
    },
  });
  if (dataList.code === 200) {
    tableData.value.data = dataList.data.list;
    tableData.value.total = dataList.data.total;
    emits("tableUpdate", tableData.value.data);
  }
  tableLoadingData.show = false;
}

async function queryData() {
  tableLoadingData.show = true;

  let { pageNumber, pageSize } = tableData.value;
  let dataList = await api().post(props.option.searchUrl, {
    ...props.option.searchParams,
    pageSize,
    pageNumber,
  });

  if (dataList.code === 200) {
    tableData.value.data = dataList.data.list;
    tableData.value.total = dataList.data.total;
    emits("searchUpdate", tableData.value.data);
  } else {
    ElMessage.error("查询出错了，请稍后重试！");
  }
  tableLoadingData.show = false;
}

function currentPageChange(newVal: number) {
  tableData.value.pageNumber = newVal;
  if (executeType.value === "search") queryData();
  if (["list", "reset"].includes(executeType.value)) initData();
  if (!executeType.value) initData();
}

async function requestAllData() {
  let dataList = await api().get(props.option.url, {
    params: {
      pageSize: 999999,
      pageNumber: 1,
      ...props.option.searchParams,
    },
  });
  return dataList.data.list;
}

function refresh() {
  if (executeType.value === "search") queryData();
  if (["list", "reset"].includes(executeType.value)) initData();
  if (!executeType.value) queryData();
}
</script>
<style lang="scss" scoped></style>
