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

export interface State {
  types: TypeState[]
  labels: LabelState[]
}

export interface TypeState {
  id: string
  name: string
}

export interface LabelState {
  id: string
  type_name: string
  name: string
}

export const useLabelStore = defineStore('label', {
  state: (): State => {
    return {
      types: [
        { id: '1', name: '基础标签' },
        { id: '2', name: '行为标签' },
        { id: '3', name: '业务标签' },
        { id: '4', name: '订单标签' },
        { id: '5', name: '渠道标签' }
      ],
      labels: []
    }
  },
  getters: {
    treeLabels: state => {
      return state.types.map(item => {
        const children = state.labels.filter(child => child.type_name === item.name)
        return { ...item, children }
      })
    }
  },
  actions: {
    setData(data?: State) {
      if (!data?.labels) return
      this.setLabels(data.labels)
    },
    setLabels(list: LabelState[]) {
      this.labels = list
    },
    addLabel(label: Omit<LabelState, 'id'>) {
      this.labels.push({ id: nanoid(4), ...label })
    },
    updateLabel(label: LabelState) {
      const index = this.labels.findIndex(item => item.id === label.id)
      this.labels[index] = label
    },
    removeLabel(id: string) {
      this.labels = this.labels.filter(item => item.id !== id)
    }
  }
})
