<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="name">
                <el-input v-model="formInline.name" placeholder="请输入分类名称" clearable />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="formInline.status" 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: 0px">批量删除</el-button>
          <el-button type="primary" icon="plus" @click="addCategory">添加分类</el-button>
        </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 #level="slotProps">
            {{ slotProps.row.level }}级分类
          </template>

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

          <!-- 自定义-操作 -->
          <template #action="slotProps">
            <el-button text v-if="slotProps.row.status == 2" class="el-button-custom"
              @click="enableAndDisable(slotProps.row, 1)">启用</el-button>
            <el-button text v-if="slotProps.row.status == 1" class="el-button-custom"
              @click="enableAndDisable(slotProps.row, 2)">禁用</el-button>
            <el-button text class="el-button-custom" @click="handleEdit(slotProps.row)">编辑</el-button>
            <el-button text class="el-button-delete" @click="handleDelete(slotProps.row)">删除</el-button>
          </template>
        </tableComponent>
      </div>
    </div>

    <!-- 添加分类 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" :close-on-click-modal="false">
      <el-form :model="dialogForm" :label-width="'80'" :rules="dialogFormRules" ref="dialogRef">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="dialogForm.name" autocomplete="off" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId">
          <el-cascader v-model="dialogForm.parentId" :options="goodsOptions" :props="cascaderProps"
            placeholder="请选择父级分类" clearable style="width: 100%" @change="handleCascaderChange" />
        </el-form-item>
        <el-form-item label="是否禁用" prop="status" required>
          <el-radio-group v-model="dialogForm.status" style="margin-top: -3px">
            <el-radio value="1" size="large">启用类别</el-radio>
            <el-radio value="2" size="large">禁用类别</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onSaveCategory">
            保存
          </el-button>
          <el-button @click="cancelDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from "vue";
import tableComponent from "@/components/tableComponent.vue";
import Mock from "mockjs";
import {
  getGoodCategoryInfo,
  getGoodType,
  categoryAdd, categoryEdit,
  categoryRemove, enableAndDisableCategory
} from "@/api/goods/info";
import { ca } from "element-plus/es/locales.mjs";
const { proxy } = getCurrentInstance();
import { ElMessage } from 'element-plus'

const formInline = reactive({
  name: "",
  status: "",
  startDate: "",
  endDate: "",
  current: 1,
  size: 10,
});
const statusList = ref([
  { name: "未启用", id: "2" },
  { 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 = () => {
  formInline.current = 1;
  formInline.status = formInline.status == undefined ? "" : formInline.status;
  if (formInline.startDate && !formInline.endDate) {
    ElMessage.warning("请选择结束日期！");
    return;
  }
  if (formInline.endDate && !formInline.startDate) {
    ElMessage.warning("请选择开始日期！");
    return;
  }
  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: "id", label: "ID" },
  { prop: "name", label: "类别名称" },
  { prop: "level", label: "分类级别", slotName: "level" },
  { prop: "createTime", label: "添加时间" },
  { prop: "status", label: "状态", slotName: "status" },
  { prop: "action", label: "操作", slotName: "action", width: 150,fixed: "right" },
]);

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

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

  }
  tableLoading.value = false;
};

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

// 启用禁用
const enableAndDisable = async (row, num) => {
  nowClickRow.value = row;
  try {
    tableLoading.value = true;
    let res = await enableAndDisableCategory({
      id: row.id,
      status: num,
    });
    tableLoading.value = false;
    if (res.code == 200) {
      onSubmit();
      if (num == 1) {
        ElMessage.success("启用成功！");
      } else {
        ElMessage.success("禁用成功！");
      }
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    tableLoading.value = false;
  }
};
// 添加分类
const addCategory = () => {
  dialogTitle.value = "添加分类";
  getGoodTypeList();
  Object.assign(dialogForm, { // 保持响应性，手动清空字段
    id: "",
    type: 1,
    name: "",
    level: "",
    parentId: "",
    status: "1",
  });
  dialogFormVisible.value = true;
};
// 编辑操作
const handleEdit = async (row) => {
  nowClickRow.value = row;
  dialogTitle.value = "编辑分类";
  getGoodTypeList();
  dialogForm.id = row.id;
  dialogForm.type = row.type;
  dialogForm.name = row.name;
  dialogForm.level = row.level;
  dialogForm.parentId = row.parentId;
  dialogForm.status = row.status?.toString() ?? '1';

  dialogForm.selectedNode = findNodeById(goodsOptions.value, row.parentId);
  dialogFormVisible.value = true;
};
// 删除操作
const handleDelete = (row) => {
  deleteGoods(row.id);
};
// 批量删除
const batchDelete = () => {
  deleteGoods(selectedIds.value.join(","));
};
const deleteGoods = async (ids) => {
  try {
    tableLoading.value = true;
    let res = await categoryRemove({ id: ids });
    tableLoading.value = false;
    if (res.code == 200) {
      onSubmit();
      ElMessage.success("删除成功");
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    tableLoading.value = false;
  }
};

const dialogFormVisible = ref(false);
const dialogRef = ref(null);
const dialogTitle = ref("添加分类");
const dialogForm = reactive({
  type: null, //分类类型归属，类型1->农资交易,2->供应商服务，3->采购商服务,4->土地交易
  name: "", //分类名字
  parentId: "", //父级id
  level: "", //分类层级,parentId的长度
  sort: "", //排序值
  status: "1", //分类状态(1-启用 2-禁用)
});
const dialogFormRules = ref({
  name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  parentId: [
    { required: true, message: "请选择父级分类", trigger: ["blur", "change"] },
  ],
  status: [{ required: true, message: "请选择分类状态", trigger: "change" }],
});
// 级联选择器配置
const cascaderProps = ref({
  label: "name", // 选项标签字段名
  value: "id", // 选项值字段名
  children: "children", // 子选项字段名
  emitPath: false, // 只返回当前节点值，不返回路径
  checkStrictly: true, //可以点击任意层级节点直接选中（不再需要展开到最后一级）
  expandTrigger: "hover", // 展开触发方式，默认为点击，可选值为 hover
  selectedNode: {},
});
const goodsOptions = ref([]);
const getGoodTypeList = async () => {
  try {
    let response = await getGoodType();
    if (response.code == 200) {
      goodsOptions.value = response.data;
    }
  } catch (error) {

  }
};
// 递归查找节点对象
const findNodeById = (options, id) => {
  for (const node of options) {
    if (node.id === id) return node
    if (node.children) {
      const found = findNodeById(node.children, id)
      if (found) return found
    }
  }
  return null
}
const handleCascaderChange = (selectedId) => {
  const selectedNode = findNodeById(goodsOptions.value, selectedId)
  dialogForm.selectedNode = selectedNode
}
const onSaveCategory = () => {
  dialogRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        proxy.$modal.loading("正在保存...");
        let param = { ...dialogForm };
        param.level = dialogForm.selectedNode.level ?? "";
        param.type = dialogForm.selectedNode.type ?? "";
        let response;
        if (dialogTitle.value == "添加分类") {
          response = await categoryAdd(param);
        } else {
          response = await categoryEdit(param);
        }
        proxy.$modal.closeLoading();
        if (response.code == 200) {
          cancelDialog();
          onSubmit();
          if (dialogTitle.value == "添加分类") {
            ElMessage.success("添加成功!");
          } else {
            ElMessage.success("编辑成功!");
          }
        } else {
          ElMessage.error(response.msg);
        }
      } catch (error) {
        proxy.$modal.closeLoading();
      }
    }
  });
};
const cancelDialog = () => {
  Object.assign(dialogForm, { // 保持响应性，手动清空字段
    id: "",
    type: null,
    name: "",
    level: "",
    parentId: "",
    status: "1",
  });
  dialogFormVisible.value = false;
};

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;
};
// 组件挂载时加载数据
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>
