import { defineStore } from 'pinia'
import { nanoid } from 'nanoid'

export interface State {
  groups: GroupState[]
}

export interface GroupState {
  id: string
  name: string
  type: number
}

export const useGroupStore = defineStore('group', {
  state: (): State => {
    return {
      groups: []
    }
  },
  getters: {
    staticGroups(state) {
      return state.groups.filter(item => item.type == 1)
    },
    dynamicGroups(state) {
      return state.groups.filter(item => item.type == 2)
    }
  },
  actions: {
    setData(data: State) {
      if (!data?.groups) return
      this.setGroups(data.groups)
    },
    setGroups(list: GroupState[]) {
      this.groups = list
    },
    addGroup(group: Omit<GroupState, 'id'>) {
      this.groups.push({ id: nanoid(4), ...group })
    },
    updateGroup(group: GroupState) {
      const index = this.groups.findIndex(item => item.id === group.id)
      this.groups[index] = group
    },
    removeGroup(id: string) {
      this.groups = this.groups.filter(item => item.id !== id)
    }
  }
})
