import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { getInfo } from '@/api/login'
import { listEmployee } from '@/api/basic/employee'
import { getDepartment } from '@/api/basic/department'

const employee = {
	state: {
		empId: storage.get(constant.empId),
		empCode: storage.get(constant.code),
		empName: storage.get(constant.empName),
		deptId: storage.get(constant.empDeptId),
		deptName: storage.get(constant.empDeptName)
	},
	mutations: {
		SET_ID: (state, empId) => {
			state.empId = empId
			storage.set(constant.empId, empId)
		},
		SET_EMP_NAME: (state, empName) => {
			state.empName = empName
			storage.set(constant.empName, empName)
		},
		SET_CODE: (state, empCode) => {
			state.empCode = empCode
			storage.set(constant.code, empCode)
			storage.set(constant.empCode, empCode)
		},
		SET_DEPT_ID: (state, deptId) => {
			state.deptId = deptId
			storage.set(constant.empDeptId, deptId)
		},
		SET_DEPT_NAME: (state, deptName) => {
			state.deptName = deptName
			storage.set(constant.empDeptName, deptName)
		}
	},
	actions: {
	  // 获取用户信息
	  async GetEmpInfo({ commit, state }) {
	    try {
	      // 1. 获取登录用户信息
	      const res = await getInfo()
	      const user = res.user
	      const empCode = (!user || !user.employeeCode) ? "" : user.employeeCode
	      commit('SET_CODE', empCode)
	
	      // 2. 根据 empCode 查询员工
	      const empRes = await listEmployee({ empCode })
	      if (empRes.total !== 1) {
	        console.warn('未找到员工信息')
	        return
	      }
	
	      const { id, name, deptId } = empRes.rows[0]
	      commit('SET_ID', id)
	      commit('SET_EMP_NAME', name)
	      commit('SET_DEPT_ID', deptId)
	
	      if (!deptId) {
	        console.warn('该人员未绑定部门')
	        return
	      }
	
	      // 3. 获取部门信息
	      const deptRes = await getDepartment(deptId)
	      if (deptRes.data) {
	        commit('SET_DEPT_NAME', deptRes.data.departmentTitle)
	      } else {
	        console.warn(`未查询到该人员所属部门: ${deptId}`)
	      }
	
	      return deptRes
	    } catch (error) {
	      console.error('获取员工信息失败:', error)
	      throw error
	    }
	  }
	}
}

export default employee