<template>
  <el-form
    :model="formData"
    label-width="100px"
    inline
    style="padding-bottom: 20px">
    <el-form-item label="服务分类名称">
      <el-input
        v-model="formData.name"
        placeholder="请输入服务分类名称"></el-input>
    </el-form-item>
    <el-form-item label="备注">
      <el-input v-model="formData.remark" placeholder="请输入备注"></el-input>
    </el-form-item>
    <el-row>
      <el-form-item label="分类" style="width: 100%">
        <el-tree-select
          check-strictly
          :check-on-click-node="true"
          v-model="formData.parentId"
          :props="{ label: 'name', value: 'id' }"
          :data="categoryOptions"
          :render-after-expand="false"
          style="width: 240px" />
      </el-form-item>
    </el-row>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import api from "@/lib/request";

// 表单数据
const formData = defineModel({
  default: {
    name: "", // 服务项目名称
    remark: "", // 备注
    parentId: 0, // 分类ID
  },
});

// 分类选项数据
const categoryOptions = ref<{ id: number; name: string }[]>([]);

// 获取分类树并转换为下拉框选项
const loadCategoryTree = async () => {
  try {
    const res = await api().get("/service-category/list");
    if (res.data.list.length) {
      categoryOptions.value = [{ id: 0, name: "无" }, ...res.data.list];
    } else {
      categoryOptions.value = [{ id: 0, name: "无" }];
    }
  } catch (err) {
    ElMessage.error("获取分类树失败");
  }
};

// 页面加载时获取分类树
onMounted(() => {
  loadCategoryTree();
});
</script>
