import { api, type HelpDoc } from "@/api/help";
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";

export function useHelp() {
  const menuItems = ref<Array<HelpDoc>>([]);
  const docInfo = ref({
    id: undefined,
    label: "",
    content: "",
    status: 1,
    sort: 1,
    parentId: 0
  });

  function initForm() {
    docInfo.value = {
      id: undefined,
      label: "",
      content: "",
      status: 1,
      parentId: 0,
      sort: 1
    };
  }

  function resetForm(pid) {
    docInfo.value = {
      id: 0,
      label: "",
      content: "",
      parentId: pid || 0,
      status: 1,
      sort: 1
    };
  }

  function save() {
    if (docInfo.value.id === 0) {
      api.save(docInfo.value).then(() => {
        ElMessage.success("添加成功");
        getMenuItems();
      });
    } else {
      api.update(docInfo.value).then(() => {
        ElMessage.success("修改成功");
        getMenuItems();
      });
    }
  }

  function del() {
    api.del(docInfo.value).then(() => {
      ElMessage.success("删除成功");
      initForm();
      getMenuItems();
    });
  }

  const getMenuItems = async () => {
    const res = await api.listHelpTree({});
    // console.log(res);
    menuItems.value = res.data;
  };

  const loadDocData = async (id: any) => {
    const res = await api.getDoc(id);
    // console.log(res);
    const data = res.data;
    docInfo.value = data;
    return data;
  };

  onMounted(async () => {
    await getMenuItems();
  });

  return {
    menuItems,
    loadDocData,
    docInfo,
    save,
    del,
    resetForm
  };
}
