import * as express from "express";
import { getConnection } from "typeorm";
import User from "../../entity/User";
import { Role } from "@/entity/Role";

import ServiceCategory from "@/entity/ServiceCategory"; // 请确保路径正确

const router = express.Router();

router.get("/guide", async (req, res) => {
  let roleRep = getConnection().getRepository(Role);
  let guide1ID = (await roleRep.findOne({ name: "服务部" })).id;

  let guideIds = [guide1ID]
    .filter((item) => item)
    .map((item) => item.toString());
  let userList = await getConnection()
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.role IN (:...ids)", {
      ids: guideIds,
    })
    .getMany();

  return res.send({
    code: 200,
    data: userList.map((item) => {
      return {
        value: item.name,
        label: item.name,
      };
    }),
  });
});

router.get("/service-categories", async (req, res) => {
  try {
    // 获取服务分类Repository
    const categoryRepo = getConnection().getRepository(ServiceCategory);

    // 查询所有分类（可按需要添加排序）
    const categories = await categoryRepo.find({
      order: { createDate: "DESC" }, // 按创建时间倒序
    });

    // 格式化返回数据
    return res.status(200).json({
      code: 200,
      data: categories.map((item) => ({
        value: item.id, // 使用ID作为值
        label: item.name, // 显示分类名称
        // 可根据需要添加额外字段
        name: item.name,
        // parentId: item.parentId
      })),
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      msg: "获取服务分类失败，请稍后重试",
    });
  }
});

export default router;
