<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 v-hasPermi="['product:category:add']" 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="categoryTableRef"
        v-loading="loading"
        :data="categoryList"
        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 prop="sort" align="center" label="排序" width="150"></el-table-column>
        <el-table-column prop="platform" align="center" label="平台" width="150">
          <template #default="scope">
            <span>{{ scope.row.platform === 0 ? '工业品' : scope.row.platform === 1 ? 'PC端' : '未知' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isShow" align="center" label="是否提示" width="150">
          <template #default="scope">
            <span>{{ scope.row.isShow === 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作">
          <template #default="scope">
            <el-tooltip content="新增分类" placement="top">
              <el-button v-hasPermi="['product:category:add']" link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['product:category:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['product:category:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
            <el-tooltip v-if="scope.row.classLevel === 3" content="设置审核员" placement="top">
              <el-button v-hasPermi="['product:category:edit']" link type="primary" icon="User" @click="handleSetReviewer(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="categoryFormRef" :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="12">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类编号" prop="categoryNo">
              <el-input v-model="form.categoryNo" placeholder="请输入分类编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签1" prop="oneLable1">
              <el-input v-model="form.oneLable1" placeholder="请输入标签1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接1" prop="oneLink1">
              <el-input v-model="form.oneLink1" placeholder="请输入链接1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签2" prop="oneLable2">
              <el-input v-model="form.oneLable2" placeholder="请输入标签2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接2" prop="oneLink2">
              <el-input v-model="form.oneLink2" placeholder="请输入链接2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平台" prop="platform">
              <el-select v-model="form.platform" placeholder="请选择所属平台" style="width: 100%">
                <el-option label="工业品" :value="0" />
                <el-option label="PC端" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否提示" prop="isShow">
              <el-switch v-model="form.isShow" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否导航" prop="isShowGps">
              <el-switch v-model="form.isShowGps" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="classDescription">
              <el-input v-model="form.classDescription" type="textarea" placeholder="请输入内容" :rows="3" />
            </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>

    <!-- 用户选择组件 -->
    <UserSelect ref="userSelectRef" :multiple="false" @confirmCallBack="handleReviewerSelected" />
  </div>
</template>

<script setup name="Category" lang="ts">
import { listCategory, getCategory, delCategory, addCategory, updateCategory, listCategoryExcludeChild, setCategoryReviewer } from '@/api/product/category';
import UserSelect from '@/components/UserSelect/index.vue';
import { UserVO } from '@/api/system/user/types';
import { CategoryVO, CategoryQuery, CategoryForm } from '@/api/product/category/types';

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

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const categoryList = ref<CategoryVO[]>([]);
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: CategoryVO[]) => void }>>(new Map());

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

const categoryTableRef = ref<ElTableInstance>();
const queryFormRef = ref<ElFormInstance>();
const categoryFormRef = ref<ElFormInstance>();
const userSelectRef = ref<InstanceType<typeof UserSelect>>();

// 当前设置审核员的分类
const currentReviewerCategory = ref<CategoryVO | null>(null);

const initFormData: CategoryForm = {
  id: undefined,
  categoryName: undefined,
  categoryNo: undefined,
  parentId: undefined,
  sort: 0,
  platform: undefined,
  isShow: 1,
  isShowGps: 0,
  oneLable1: undefined,
  oneLable2: undefined,
  oneLink1: undefined,
  oneLink2: undefined,
  classDescription: undefined
}
const data = reactive<PageData<CategoryForm, Partial<CategoryQuery>>>({
  form: {...initFormData},
  queryParams: {
    categoryName: undefined
  },
  rules: {
    categoryName: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "显示排序不能为空", trigger: "blur" }
    ]
  }
});

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

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

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

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

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  categoryFormRef.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?: CategoryVO) => {
  reset();
  const res = await listCategory();
  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: CategoryVO) => {
  reset();
  const res = await getCategory(row.id);
  form.value = res.data;
  const response = await listCategoryExcludeChild(row.id);
  // 根据后端返回结构，如果是 TableDataInfo 则用 rows，如果是直接数组则用 data
  const responseData = (response as any).rows || response.data || [];
  const data = proxy?.handleTree<CategoryOptionsType>(responseData, 'id');
  if (data) {
    categoryOptions.value = data;
    if (data.length === 0) {
      const noResultsOptions: CategoryOptionsType = {
        id: res.data.parentId,
        categoryName: res.data.parentName || '无',
        children: []
      };
      categoryOptions.value.push(noResultsOptions);
    }
  }
  dialog.visible = true;
  dialog.title = '修改产品分类';
}

/** 提交按钮 */
const submitForm = () => {
  categoryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.id ? await updateCategory(form.value) : await addCategory(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
}

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

/** 设置审核员按钮操作 */
const handleSetReviewer = (row: CategoryVO) => {
  currentReviewerCategory.value = row;
  userSelectRef.value?.open();
};

/** 审核员选择回调 */
const handleReviewerSelected = async (users: UserVO[]) => {
  if (!currentReviewerCategory.value || users.length === 0) return;
  
  const user = users[0];
  try {
    await setCategoryReviewer(currentReviewerCategory.value.id, user.userId);
    proxy?.$modal.msgSuccess(`已将 ${user.nickName} 设置为 ${currentReviewerCategory.value.categoryName} 的审核员`);
  } catch (error) {
    console.error('设置审核员失败:', error);
  }
};

onMounted(() => {
  getList();
});
</script>
