import { IOrgProjectCombine } from '@/api/common'

interface IProjectState {
  project: Partial<IOrgProjectCombine>
}

const lsName = 'project'

const getDefaultProjectData = (): IProjectState => {
  try {
    const data = JSON.parse(localStorage.getItem(lsName))
    if (data) return data
  } catch (error) {
    console.log(error)
  }
  return { project: {} }
}

const state = getDefaultProjectData()
const getters = {
  info: (state: IProjectState) => {
    const { id: projectId, name: projectName, code: projectCode } = state.project || {}
    return { projectId, projectName, projectCode }
  },
  id: (state: IProjectState) => ({ projectId: (state.project || {}).id })
}
const mutations = {
  UPDATE: (state: IProjectState, data: IOrgProjectCombine) => {
    state.project = { ...data }
    localStorage.setItem(lsName, JSON.stringify(state))
  },
  RESET: (state: IProjectState) => {
    state = getDefaultProjectData()
    localStorage.setItem(lsName, JSON.stringify({}))
  }
}
const actions = {}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
