import { defineStore } from 'pinia'
import { OfficeListItem, CategoriedStaffItem, OfficeListParams } from '/@/api/sys/model/officeModel'
import { getOfficeList } from '/@/api/sys/office'
import { store } from '/@/store'

interface OfficeState {
  categoryList: OfficeListItem[]
  staffList: CategoriedStaffItem[]
}
export const useOfficeStore = defineStore({
  id: 'app-office',
  state: (): OfficeState => ({
    categoryList: [],
    staffList: []
  }),
  getters: {
    getCategories(): OfficeListItem[] {
      return this.categoryList
    },
    getCategoriedStaff(): CategoriedStaffItem[] {
      return this.staffList
    },
    getCategoryOptions(): { label: string; value: string }[] {
      return this.categoryList.map(category => ({
        value: category.cid,
        label: category.title
      }))
    }
  },
  actions: {
    setCategoryList(category: OfficeListItem[]) {
      this.categoryList = category
    },
    setStaffList(staff: CategoriedStaffItem[]) {
      this.staffList = staff
    },
    // 获取办事处列表
    async getOfficesAction() {
      const { category = [] } = await getOfficeList()
      this.setCategoryList(category)
    },
    // 获取办事处对应员工列表
    async getStaffWithCategoryIdAction(params: OfficeListParams) {
      const { staff = [] } = await getOfficeList(params)
      this.setStaffList(staff.map(item => ({ value: item.username, label: item.username })))
    },
    checkStaffList() {
      if (!this.getCategories.length) {
        this.getOfficesAction()
      }
    }
  }
})

// Need to be used outside the setup
export function useOfficeStoreWidthOut() {
  return useOfficeStore(store)
}
