<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="queryParams.categoryName" placeholder="请输入分类名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button  type="primary" plain icon="Plus" @click="handleAdd()">新增分类</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="productCategoryTableRef"
        v-loading="loading"
        :data="productCategoryList"
        row-key="id"
        border
        lazy
        :load="loadChildren"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="categoryName" label="分类名称" width="260"></el-table-column>
        <el-table-column prop="classLevel" align="center" label="分类级别" width="150">
          <template #default="scope">
            <span>{{ scope.row.classLevel }}级</span>
          </template>
        </el-table-column>



        <el-table-column fixed="right" align="center" label="操作">
          <template #default="scope">
            <el-tooltip content="新增分类" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改产品分类对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="700px">
      <el-form ref="productCategoryFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col v-if="form.parentId !== 0" :span="24">
            <el-form-item label="上级分类" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="categoryOptions"
                :props="{ value: 'id', label: 'categoryName', children: 'children' } as any"
                value-key="id"
                placeholder="选择上级分类"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类编号" prop="categoryNo">
              <el-input v-model="form.categoryNo" placeholder="请输入分类编号" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 认</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductCategory" lang="ts">
import { listProductCategory, getProductCategory, delProductCategory, addProductCategory, updateProductCategory, listProductCategoryExcludeChild } from '@/api/external/productCategory';
import { ProductCategoryVO, ProductCategoryQuery, ProductCategoryForm } from '@/api/external/productCategory/types';
import cache from '@/plugins/cache';

interface CategoryOptionsType {
  id: number | string;
  categoryName: string;
  children: CategoryOptionsType[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const productCategoryList = ref<ProductCategoryVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const categoryOptions = ref<CategoryOptionsType[]>([]);
// 存储懒加载的子节点加载状态和 resolve 函数
const lazyTreeNodeMap = ref<Map<string | number, { tree: any; treeNode: any; resolve: (data: ProductCategoryVO[]) => void }>>(new Map());

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const productCategoryTableRef = ref<ElTableInstance>();
const queryFormRef = ref<ElFormInstance>();
const productCategoryFormRef = ref<ElFormInstance>();

const initFormData: ProductCategoryForm = {
  id: undefined,
  categoryName: undefined,
  categoryNo: undefined,
  parentId: undefined,
  platform: undefined,
  classDescription: undefined
}
const data = reactive<PageData<ProductCategoryForm, Partial<ProductCategoryQuery>>>({
  form: {...initFormData},
  queryParams: {
    categoryName: undefined,
    itemId: undefined
  },
  rules: {
    categoryName: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询产品分类列表（只加载顶级分类） */
const getList = async () => {
  loading.value = true;
  // 清空懒加载缓存
  lazyTreeNodeMap.value.clear();
  // 只加载顶级分类（parentId = 0）
  const params = {
    ...queryParams.value,
    parentId: 0
  };
  const res = await listProductCategory(params);
  const data = (res as any).rows || res.data || [];
  // 根据 hasChildren 字段标记是否有子节点
  productCategoryList.value = data.map((item: ProductCategoryVO) => ({
    ...item,
    hasChildren: item.hasChildren ?? (item.classLevel < 3) // 如果后端没返回 hasChildren，根据 classLevel 判断
  }));
  loading.value = false;
}

/** 初始化项目Key（从缓存获取） */
const initProjectKey = () => {
  const currentProject = cache.local.getJSON('currentProject');
  if (currentProject && currentProject.id) {
    queryParams.value.itemId = currentProject.id;
    form.value.itemId = currentProject.id;
  }
}

/** 懒加载子节点 */
const loadChildren = async (row: ProductCategoryVO, treeNode: any, resolve: (data: ProductCategoryVO[]) => void) => {
  // 存储加载状态，便于刷新时重新加载
  lazyTreeNodeMap.value.set(row.id, { tree: row, treeNode, resolve });
  try {
    const res = await listProductCategory({ parentId: row.id, itemId: queryParams.value.itemId });
    const data = (res as any).rows || res.data || [];
    // 标记子节点是否还有子级
    const children = data.map((item: ProductCategoryVO) => ({
      ...item,
      hasChildren: item.hasChildren ?? (item.classLevel < 3)
    }));
    resolve(children);
  } catch (error) {
    resolve([]);
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  productCategoryFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 刷新已展开的懒加载节点 */
const refreshLazyNodes = () => {
  lazyTreeNodeMap.value.forEach(async ({ tree, treeNode, resolve }, key) => {
    // 重置已加载状态
    if (treeNode.loaded) {
      treeNode.loaded = false;
    }
    // 重新加载
    await loadChildren(tree, treeNode, resolve);
  });
};

/** 新增按钮操作 */
const handleAdd = async (row?: ProductCategoryVO) => {
  reset();
  const res = await listProductCategory({ itemId: queryParams.value.itemId });
  const responseData = (res as any).rows || res.data || [];
  const data = proxy?.handleTree<CategoryOptionsType>(responseData, 'id');
  if (data) {
    categoryOptions.value = data;
    if (row && row.id) {
      form.value.parentId = row?.id;
    }
    dialog.visible = true;
    dialog.title = '添加产品分类';
  }
}

/** 修改按钮操作 */
const handleUpdate = async (row: ProductCategoryVO) => {
  reset();
  const res = await getProductCategory(row.id, queryParams.value.itemId);
  form.value = res.data;
  const response = await listProductCategory({ itemId: queryParams.value.itemId });
  // 根据后端返回结构，如果是 TableDataInfo 则用 rows，如果是直接数组则用 data
  const responseData = (response as any).rows || response.data || [];
  const data = proxy?.handleTree<CategoryOptionsType>(responseData, 'id');
  if (data) {
    categoryOptions.value = data;
  }
  dialog.visible = true;
  dialog.title = '修改产品分类';
}

/** 提交按钮 */
const submitForm = () => {
  productCategoryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.itemId = cache.local.getJSON('currentProject').id;
      form.value.id ? await updateProductCategory(form.value) : await addProductCategory(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row: ProductCategoryVO) => {
  await proxy?.$modal.confirm('是否确认删除名称为"' + row.categoryName + '"的数据项?');
  await delProductCategory(row.id, queryParams.value.itemId);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
}

onMounted(() => {
  // 从缓存获取项目Key并初始化
  initProjectKey();
  if (queryParams.value.itemId) {
    getList();
  }
});
</script>
