import { defineStore } from "pinia";
import { ref } from "vue";
import { getAllDeptList } from "@/api";

export const useDeptStore = defineStore('dept', () => {
  const deptList = ref([])
  const deptTree = ref([])

  const buildTree = (data) => {
    const map = data.reduce((acc, item) => {
      acc[item.id] = { ...item, children: [] };
      return acc;
    }, {});

    const tree = [];

    data.forEach(item => {
      if (item.parentId && map[item.parentId]) {
        map[item.parentId].children.push(map[item.id]);
      } else if (item.parentId === 0) {
        tree.push(map[item.id]);
      }
    });

    return tree;
  }

  const loadDeptList = async () => {
    // const locale = uni.getLocale()
    // const list = (await getAllDeptList()).data.map((item) => {
    //   if (item.name.includes('~~') && item.name.includes('**')) {
    //     const s = item.name.split('~~')
    //     if (locale.startsWith('zh')) {
    //       item.name = s[0]
    //     } else if (locale.startsWith('ru')) {
    //       const s2 = s[2].split('**')
    //       item.name = s2[1]
    //     } else {
    //       const s1 = s[1].split('**')
    //       item.name = s1[1]
    //     }
    //   }
    //   return JSON.parse(JSON.stringify(item))
    // })
    const list = (await getAllDeptList()).data
    deptList.value = list
    deptTree.value = buildTree(list)
  }

  return { deptList, deptTree, loadDeptList }
})