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

export const useDeviceStore = defineStore('device', () => {
  const deviceTypeList = ref([])
  const deviceTypeTree = 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 loadDeviceTypeList = async () => {
    const locale = uni.getLocale()
    const list = (await getAllDeviceTypeList()).data
    // const list = (await getAllDeviceTypeList()).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))
    // })
    deviceTypeList.value = list
    deviceTypeTree.value = buildTree(list)
  }

  return { deviceTypeList, deviceTypeTree, loadDeviceTypeList }
})