import { defineStore } from "pinia";
import { categoryActions } from "./actions";
import { ListController } from "@/controllers/ListController";
import { request } from "../../objects";
import loading from "@/components/Provider/Loading";
import { message } from "ant-design-vue";
import Modal from "@/components/Provider/Modal";

function parseTreeData(categoryList: any) {
  const list = [...categoryList];

  let roots = list.filter((item) => item.pid == "top");
  function findChild(root: CategoryItem, list: CategoryItem[]) {
    root.children = [];
    list.forEach((it) => {
      if (it.pid == root._id) {
        root.children?.push(it);
      }
    });
    root.children.forEach((child) => findChild(child, list));
  }
  roots.forEach((item) => findChild(item, list));

  function parseTreeItem(item: CategoryItem) {
    let ret: any = {
      _id: item._id,
      name: item.name,
      subName: item.subName,
      type: item.type,
      pid: item.pid,
      cover: item.cover,
      sort: item.sort,
      isHome: item.isHome,
    };
    if (item.children?.length) {
      ret.children = [];
      item.children.forEach((it) => {
        ret.children.push(parseTreeItem(it));
      });
    }
    return ret;
  }
  return roots.map((item) => parseTreeItem(item));
}
export const useCategory = defineStore("category", {
  state: () => ({
    // categories: [],
    listController: new ListController<CategoryItem, any>(request),
  }),
  getters: {
    categories(state) {
      return state.listController.state.list;
    },
    categoryTree() {
      const tree = parseTreeData(this.categories);
      return tree;
    },
  },
  actions: {
    async initCategories() {
      this.listController.setCrudPrefix("/category");
      await this.listController.loadPage(1, 200);
    },
    async addCategoryItem(pid = "top", key = 0) {
      const base = await categoryActions.EditCategoryItem({}, key + 1);
      const item = { pid, ...base };
      loading.show("保存中");
      await this.listController.addItem(item);
      loading.hidden();
      message.success("添加成功");
    },
    async updateCategoryItem(item: any, key = 0) {
      const res = await this.listController.itemDetail(item._id);
      if (res.errorNo != 200) {
        message.warn("未查询到数据！");
        return;
      }
      const base = await categoryActions.EditCategoryItem(res.result, key);
      loading.show("保存中");
      await this.listController.saveItem(base);
      loading.hidden();
      message.success("更新成功");
    },
    async deleteCategoryItem(item: any) {
      const ok = await Modal.confirm({
        title: "删除确认",
        content: `删除后数据无法恢复，确认删除菜单：${item.name}？`,
        type: "danger",
      });
      if (ok) {
        loading.show("删除中");
        await this.listController.deleteItem(item._id);
        loading.hidden();
        message.success("删除成功");
      }
    },
  },
});
