<template>
  <div class="app-container customer-control">
    <div class="container-custom">
      <!-- 搜索栏 -->
      <div ref="searchBarRef" class="search-box">
        <div class="search-bar">
          <div class="search-bar-left">
            <el-form
              ref="searchForm"
              :inline="true"
              :model="formInline"
              class="demo-form-inline"
              :label-width="'auto'"
            >
              <el-form-item label="分类名称" prop="categoryName">
                <el-input
                  v-model="formInline.categoryName"
                  placeholder="请输入分类名称"
                  clearable
                />
              </el-form-item>
              <el-form-item label="状态" prop="categoryStatus">
                <el-select
                  v-model="formInline.categoryStatus"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in statusList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>
              <br>
              <el-form-item
                label="添加时间"
                prop="startDate"
                style="margin-right: 0"
              >
                <el-date-picker
                  v-model="formInline.startDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择起始日期"
                  clearable
                  :disabled-date="disableStartDate"
                  style="width: 160px"
                />
                <span
                  style="width: 30px; text-align: center; display: inline-block"
                >
                  -
                </span>
                <el-date-picker
                  v-model="formInline.endDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择截止日期"
                  clearable
                  :disabled-date="disableEndDate"
                  style="width: 160px"
                />
              </el-form-item>
            </el-form>
          </div>
          <div class="search-bar-right">
            <el-button type="primary" icon="Search" @click="onSubmit"
              >查询</el-button
            >
            <el-button
              icon="Refresh"
              style="margin: 16px 0 0 0"
              @click="resetForm"
              >重置</el-button
            >
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-cont" :style="{ height: tableViewportHeight + 'px' }">
        <div class="table-toolbar">
          <el-button
            icon="delete"
            @click="batchDelete"
            :disabled="btnStatus"
            style="margin-right: 10px"
            >批量删除</el-button
          >
          <router-link to="/goods/addGoods">
            <el-button type="primary" icon="plus" @click="onSubmit"
              >添加分类</el-button
            >
          </router-link>
        </div>
        <tableComponent
          :table-data="tableData"
          :columns="columns"
          :show-border="false"
          :show-selection="true"
          :header-cell-class-name="getHeaderClass"
          @page-change="handlePaginationChange"
          :loading="tableLoading"
          @selection-change="handleSelectionChange"
          :total="tableTotal"
          :current-page="formInline.current"
          :page-size="formInline.size"
          :showSort="true"
        >
          <!-- 自定义-状态 -->
          <template #goodsUrl="slotProps">
            <div class="table-cell-img-box">
              <img
                :src="slotProps.row.goodsUrl"
                class="table-cell-img"
                alt=""
              />
            </div>
          </template>

          <!-- 自定义-状态 -->
          <template #categoryStatus="slotProps">
            <span v-if="slotProps.row.categoryStatus == '已启用'" class="color-green"
              >已启用</span
            >
            <span v-else class="color-gray">未启用</span>
          </template>

          <!-- 自定义-操作 -->
          <template #action="slotProps">
            <el-tooltip effect="dark" placement="bottom-end">
              <template #content>
                <div class="custom-tooltip-content">
                  <el-icon
                    class="el-icon-custom"
                    @click="seeDetails(slotProps.row)"
                  >
                    <View />
                  </el-icon>
                  <el-icon
                    class="el-icon-custom"
                    @click="toUpload(slotProps.row)"
                  >
                    <Upload />
                  </el-icon>
                  <el-icon
                    class="el-icon-custom"
                    @click="toDownload(slotProps.row)"
                  >
                    <Download />
                  </el-icon>
                  <el-icon
                    class="el-icon-custom"
                    @click="handleEdit(slotProps.row)"
                  >
                    <Edit />
                  </el-icon>
                  <el-icon
                    class="el-icon-custom"
                    @click="handleDelete(slotProps.row)"
                  >
                    <Delete />
                  </el-icon>
                </div>
              </template>

              <span class="el-dropdown-link">
                <el-icon>
                  <More />
                </el-icon>
              </span>
            </el-tooltip>
          </template>
        </tableComponent>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from "vue";
import tableComponent from "@/components/tableComponent.vue";
import Mock from "mockjs";
import { getGoodManageInfo } from "@/api/goods/info";
import { ca } from "element-plus/es/locales.mjs";

const formInline = reactive({
  categoryName: "",
  categoryStatus: "",
  startDate: "",
  endDate: "",
  current: 1,
  size: 10,
});
const statusList = ref([
  { name: "未启用", id: '0'},
  { name: "已启用", id: '1' },
]);
// 禁用开始日期的逻辑（不能晚于已选的结束日期）
const disableStartDate = (time) => {
  if (!formInline.endDate) return false;
  const endDate = new Date(formInline.endDate);
  return time.getTime() > endDate.getTime();
};

// 禁用结束日期的逻辑（不能早于已选的开始日期）
const disableEndDate = (time) => {
  if (!formInline.startDate) return false;
  const startDate = new Date(formInline.startDate).setHours(0, 0, 0, 0);
  const currentDate = new Date(time).setHours(0, 0, 0, 0);
  return currentDate < startDate;
};

const searchForm = ref(null);
const onSubmit = () => {
  console.log("submit!");
  formInline.current = 1;
  formInline.categoryStatus = formInline.categoryStatus == undefined ? '' : formInline.categoryStatus;
  console.log(formInline);
  loadData();
};
const resetForm = () => {
  searchForm.value.resetFields();
};

// 表格数据
const tableData = ref([]);
const selectedIds = ref([]);
const btnStatus = computed(() => {
  return selectedIds.value.length <= 0;
});
const tableLoading = ref(false);
const tableTotal = ref(0);
let nowClickRow = ref({});
// 列配置
const columns = ref([]);
const columns1 = ref([
   { prop: "sort", label: "排序" },
  { prop: "id", label: "ID" },
  { prop: "categoryName", label: "类别" },
  { prop: "addTime", label: "添加时间" },
  { prop: "categoryStatus", label: "状态", slotName: "categoryStatus" },
  { prop: "action", label: "操作", slotName: "action" },
]);

// 生成食物主题昵称
const generateFoodNickname = () => {
  // 食物名词（仅限食物）
  const foods = [
    "辣椒",
    "西瓜",
    "土豆",
    "番茄",
    "黄瓜",
    "苹果",
    "蛋糕",
    "面包",
    "披萨",
    "冰淇淋",
    "奶茶",
    "咖啡",
    "啤酒",
    "炸鸡",
  ];

  // 随机组合：形容词 + 食物
  return Mock.mock(`@pick(${foods})`);
};
// 生成模拟数据
const generateMockData = () => {
  return Mock.mock({
    "list|10": [
      {
        "id|+1": 10000,
        "sort|+1": 1,
        categoryName: '@pick(["种子", "化肥", "农药"])', //分类名称
        addTime: "@datetime", //添加时间
        categoryStatus: '@pick(["已启用", "未启用"])', //状态
      },
    ],
  }).list;
};
// 加载数据
const loadData = async () => {
  tableLoading.value = true;
  tableData.value = generateMockData();
  tableTotal.value = tableData.value.length;
  // try {
  //   let response = await getGoodManageInfo(formInline);
  //   console.log(response);
  //   if (response.code == 200) {
  //     tableData.value = response.data.records;
  //     tableTotal.value = response.data.total;
  //   }
  // } catch (error) {
  //   console.log(error);
  // }
  tableLoading.value = false;
};

// 自定义表头类名,也可以在columns指定列中添加headerClassName: 'custom-header'
const getHeaderClass = ({ column }) => {
  return "custom-header";
};
// 分页变化
const handlePaginationChange = ({ page, pageSize }) => {
  console.log("分页变化:", page, pageSize);
  formInline.current = page;
  formInline.size = pageSize;
  // 这里可以调用API获取新数据
  loadData();
};
// 多选框变化
const handleSelectionChange = (selection, ids) => {
  console.log("选中项:", selection, ids);
  selectedIds.value = ids;
};

// 查看详情
const seeDetails = (row) => {
  nowClickRow.value = row;
  console.log("要查看详情的行:", row);
};
const toUpload = () => {
  console.log("向上移动:");
};
const toDownload = () => {
  console.log("向下移动:");
};
// 编辑操作
const handleEdit = (row) => {
  nowClickRow.value = row;
  console.log("要编辑的行:", row);
};
// 删除操作
const handleDelete = (row) => {
  nowClickRow.value = row;
  console.log("要删除的行:", row);
};
// 批量删除
const batchDelete = () => {
  console.log("要删除的行:", selectedIds.value);
};

const titleRef = ref(null);
const searchBarRef = ref(null);
const tableViewportHeight = ref(0);
// 精确计算可用高度
const calculateTableHeight = () => {
  // 获取窗口总高度
  const windowHeight = window.innerHeight;

  // 获取各组件高度
  const headerHeight = titleRef.value?.$el?.offsetHeight || 0;
  const searchBarHeight = searchBarRef.value?.offsetHeight || 0;

  // 计算容器内边距补偿（根据实际样式调整）
  const paddingCompensation = 130;

  // 最终计算
  tableViewportHeight.value =
    windowHeight - headerHeight - searchBarHeight - paddingCompensation;
  // console.log(tableViewportHeight.value);
};
// 组件挂载时加载数据
onMounted(() => {
  columns.value = columns1.value;
  loadData();

  calculateTableHeight();

  // 添加响应式监听
  window.addEventListener("resize", calculateTableHeight);

  // 监听DOM变化（适用于动态变化的header/searchbar）
  const observer = new ResizeObserver(calculateTableHeight);
  if (titleRef.value?.$el) observer.observe(titleRef.value.$el);
  if (searchBarRef.value) observer.observe(searchBarRef.value);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", calculateTableHeight);
});
</script>
<style lang="scss" scoped>
.table-toolbar {
  width: 300px;
  height: 50px;
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  justify-content: end;
  padding: 14px 16px 0 0;
}
</style>
