user.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import { defineStore } from 'pinia'
  2. import { setToken, removeToken, setRefreshToken, getToken } from '@/utils/auth'
  3. import {
  4. smsLogin,
  5. passwordLogin,
  6. getBaseInfo,
  7. switchLoginOfEnterprise,
  8. getEnterprisingUserInfo,
  9. logoutToken,
  10. logout
  11. } from '@/api/common'
  12. import { getUserInfo } from '@/api/personal/user'
  13. import { getEntUpdatePasswordCheck } from '@/api/recruit/enterprise/information'
  14. import { getEnterpriseUserAccount, getAccountBalance, getUserAccount, userRegister } from '@/api/common'
  15. import { getEnterpriseBaseInfo } from '@/api/enterprise'
  16. import Snackbar from '@/plugins/snackbar'
  17. import { timesTampChange } from '@/utils/date'
  18. import { updateEventList } from '@/utils/eventList'
  19. import { getBaseInfoDictOfName } from '@/utils/getText'
  20. import { checkPersonBaseInfo } from '@/utils/check'
  21. import { getStudentInfo } from '@/api/recruit/personal/resume'
  22. import { getSchoolInformation } from '@/api/school'
  23. import router from '@/router'
  24. // import Confirm from '@/plugins/confirm'
  25. // import { useIMStore } from './im'
  26. // const useIM = useIMStore()
  27. export const useUserStore = defineStore('user',
  28. {
  29. state: () => ({
  30. token: getToken(),
  31. accountInfo: localStorage.getItem('accountInfo') ? JSON.parse(localStorage.getItem('accountInfo')) : {}, // 登录返回的信息
  32. userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}, // 当前登录账号信息
  33. baseInfo: localStorage.getItem('baseInfo') ? JSON.parse(localStorage.getItem('baseInfo')) : {}, // 人才信息
  34. entBaseInfo: localStorage.getItem('entBaseInfo') ? JSON.parse(localStorage.getItem('entBaseInfo')) : {}, // 企业个人信息
  35. userAccount: {}, // 用户账户信息
  36. enterpriseUserAccount: {}, // 企业账户信息
  37. studentInfo: localStorage.getItem('studentInfo') ? JSON.parse(localStorage.getItem('studentInfo')) : {}, // 学生信息
  38. schoolInfo: localStorage.getItem('schoolInfo') ? JSON.parse(localStorage.getItem('schoolInfo')) : {}, // 学校信息
  39. }),
  40. actions: {
  41. // 个人用户注册并登录
  42. handleUserRegister (data) {
  43. return new Promise((resolve, reject) => {
  44. userRegister(data).then(async res => {
  45. setToken(res.accessToken)
  46. setRefreshToken(res.refreshToken)
  47. this.accountInfo = res
  48. localStorage.setItem('accountInfo', JSON.stringify(res))
  49. localStorage.setItem('expiresTime', res.expiresTime) // token过期时间
  50. updateEventList(true) // 获取规则配置跟踪列表
  51. await this.getUserInfos()
  52. await this.getUserBaseInfos()
  53. resolve()
  54. }).catch(err => { reject(err) })
  55. })
  56. },
  57. // 短信登录
  58. handleSmsLogin (data) {
  59. return new Promise((resolve, reject) => {
  60. smsLogin(data).then(async res => {
  61. this.token = res.accessToken
  62. setToken(res.accessToken)
  63. setRefreshToken(res.refreshToken)
  64. this.accountInfo = res
  65. localStorage.setItem('accountInfo', JSON.stringify(res))
  66. localStorage.setItem('expiresTime', res.expiresTime) // token过期时间
  67. updateEventList(true) // 获取规则配置跟踪列表
  68. await this.getUserInfos()
  69. await this.getUserBaseInfos('', { chooseRole: data.chooseRole })
  70. if (data?.schoolRegister) await this.getSchoolInfo(true)
  71. resolve(res)
  72. }).catch(err => { reject(err) })
  73. })
  74. },
  75. // 密码登录
  76. async handlePasswordLogin(data) {
  77. return new Promise((resolve, reject) => {
  78. data.account = data.phone
  79. passwordLogin(data).then(async res => {
  80. if (data.isEnterprise) { // 企业邮箱登录
  81. localStorage.setItem('emailLoginInfo', JSON.stringify(res))
  82. window.location.href = '/enterpriseVerification'
  83. } else {
  84. // 个人手机号登录
  85. setToken(res.accessToken)
  86. setRefreshToken(res.refreshToken)
  87. this.accountInfo = res
  88. localStorage.setItem('accountInfo', JSON.stringify(res))
  89. localStorage.setItem('expiresTime', res.expiresTime) // token过期时间
  90. updateEventList(true) // 获取规则配置跟踪列表
  91. await this.getUserInfos()
  92. await this.getUserBaseInfos()
  93. }
  94. resolve()
  95. }).catch(err => {
  96. reject(err)
  97. })
  98. })
  99. },
  100. // 获取当前登录账户信息
  101. async getUserInfos () {
  102. try {
  103. const data = await getUserInfo({ id: this.accountInfo.userId })
  104. this.userInfo = data
  105. localStorage.setItem('userInfo', JSON.stringify(data))
  106. this.getUserAccountInfo()
  107. } catch (error) {
  108. Snackbar.error(error.msg)
  109. }
  110. },
  111. // 获取当前登录账户的基本信息(人才信息)
  112. async getUserBaseInfos (userId = null, option) {
  113. try {
  114. let data = await getBaseInfo({ userId: userId || this.accountInfo.userId })
  115. data = data || {}
  116. this.baseInfo = await this.getFieldText(data)
  117. localStorage.setItem('baseInfo', JSON.stringify(this.baseInfo))
  118. localStorage.setItem('necessaryInfoReady', !option?.chooseRole || checkPersonBaseInfo(this.baseInfo) ? 'ready' : 'fddeaddc47868b')
  119. if (option?.chooseRole && import.meta.env.VITE_NODE_ENV !== 'production') {
  120. // // 刚注册时让用户选择学生用户还是求职者用户,角色不同填写的基本信息不同。
  121. localStorage.setItem('chooseRole', 'showChooseRole')
  122. }
  123. // 当前角色若为学生则获取学生信息
  124. if (data?.type && Number(data.type) === 1) this.getStudentInformation()
  125. } catch (error) {
  126. Snackbar.error(error)
  127. }
  128. },
  129. // 字典对应中文
  130. async getFieldText (data) {
  131. if (!data || !Object.keys(data).length) return {}
  132. if (data.birthday && data.birthday !== 0) data.birthdayText = timesTampChange(data.birthday, 'Y-M-D') // 出生日期
  133. if (data.firstWorkTime && data.firstWorkTime !== 0) data.firstWorkTimeText = timesTampChange(data.firstWorkTime, 'Y-M-D') // 首次工作时间
  134. if (data.areaId && data.areaId !== 0) await getBaseInfoDictOfName(0, data, data.areaId, 'areaName') // 现居住地text
  135. if (data.areaId && data.areaId !== 0) await getBaseInfoDictOfName(0, data, data.regId, 'regName') // 户籍地text
  136. if (data.eduType && data.eduType !== 0) await getBaseInfoDictOfName(1, data, data.eduType, 'eduTypeText') // 学历
  137. if (data.expType && data.expType !== 0) await getBaseInfoDictOfName(2, data, data.expType, 'expTypeText') // 工作经验
  138. if (data.sex && data.sex !== 0) await getBaseInfoDictOfName(3, data, data.sex, 'sexTypeText') // 性别
  139. if (data.jobType && data.jobType !== 0) await getBaseInfoDictOfName(4, data, data.jobType, 'jobTypeText') // 求职类型
  140. if (data.jobStatus && data.jobStatus !== 0) await getBaseInfoDictOfName(5, data, data.jobStatus, 'jobStatusText') // 求职状态
  141. if (data.maritalStatus && data.maritalStatus !== 0) await getBaseInfoDictOfName(6, data, data.maritalStatus, 'maritalText') // 婚姻状况
  142. return data
  143. },
  144. // 退出登录
  145. async userLogout (type) {
  146. // type: 1求职端 2招聘端
  147. if (type === 1) {
  148. await logout()
  149. } else await logoutToken(getToken(1))
  150. this.handleClearStorage()
  151. },
  152. // 清除缓存
  153. handleClearStorage () {
  154. removeToken()
  155. this.token = ''
  156. this.userInfo = {}
  157. this.baseInfo = {}
  158. this.accountInfo = {}
  159. // 商城模版数据不清除缓存
  160. const mallTemplate = localStorage.getItem('mallTemplate')
  161. localStorage.clear()
  162. localStorage.setItem('mallTemplate', mallTemplate)
  163. },
  164. // 切换为招聘者
  165. async changeRole (res) {
  166. // 切换企业时需将个人的账户信息另外储存起来,以防企业账户有角色无菜单权限返回首页清除企业信息时个人账户信息丢失
  167. const perAccountData = JSON.parse(localStorage.getItem('accountInfo'))
  168. localStorage.setItem('perAccountInfo', JSON.stringify(perAccountData))
  169. let data
  170. if (res?.type === 'emailLogin') {
  171. data = res
  172. } else {
  173. const enterpriseId = localStorage.getItem('enterpriseId') || ''
  174. if (!enterpriseId) return Snackbar.error('切换失败,请重新登录!')
  175. data = await switchLoginOfEnterprise({ enterpriseId })
  176. }
  177. setToken(data.accessToken, 1) // 个人切换企业->存放企业token
  178. setRefreshToken(data.refreshToken, 1) // 个人切换企业->存放企业refreshToken
  179. localStorage.setItem('accountInfo', JSON.stringify(data))
  180. localStorage.setItem('expiresTime', data.expiresTime)
  181. updateEventList(false)
  182. // 企业受邀加入企业,只保存token等操作。
  183. if (res?.onlySetToken) return
  184. await this.updatePasswordCheck() // 检查密码是否需要修改
  185. await this.getEnterpriseInfo()
  186. await this.getEnterpriseUserAccountInfo()
  187. Snackbar.success(res?.type === 'emailLogin' ? '登录成功' : '切换成功')
  188. let href = '/recruit/enterprise'
  189. // 是否存在重定向
  190. if (localStorage.getItem('enterpriseRedirect')) {
  191. href = localStorage.getItem('enterpriseRedirect')
  192. localStorage.setItem('enterpriseRedirect', '')
  193. }
  194. // 人才推荐不需要跳转
  195. if (!res.noJump) {
  196. setTimeout(() => { window.location.href = href }, 1000)
  197. }
  198. },
  199. // 获取当前登录的企业用户信息
  200. async getEnterpriseInfo (check) {
  201. const result = await getEnterprisingUserInfo()
  202. this.entBaseInfo = result
  203. // 是否为企业账号管理员
  204. const isAdmin = result.userType === '1'
  205. localStorage.setItem('isAdmin', isAdmin)
  206. if (isAdmin && !check) await this.checkEnterpriseBaseInfo() // 校验企业必填信息
  207. localStorage.setItem('entBaseInfo', JSON.stringify(result))
  208. },
  209. // 获取企业账户信息
  210. async getEnterpriseUserAccountInfo () {
  211. const data = await getEnterpriseUserAccount()
  212. if (!data) return
  213. this.enterpriseUserAccount = data
  214. localStorage.setItem('enterpriseUserAccount', JSON.stringify(data))
  215. return data // 方便直接获取
  216. },
  217. // 获取《企业基本信息》
  218. async checkEnterpriseBaseInfo () {
  219. try {
  220. const data = await getEnterpriseBaseInfo()
  221. if (data?.first === null || data?.first === false) { // null或者为false才弹
  222. localStorage.setItem('checkEnterpriseBaseInfoFalseHref', '/recruit/enterprise/entInfoSetting')
  223. }
  224. if (!data?.bizFlag) { // 企业登录免费职位广告提示,除了true都弹窗
  225. localStorage.setItem('positionAd', 'showPositionAd')
  226. }
  227. } catch (error) {
  228. }
  229. },
  230. // 获取用户账户信息
  231. async getUserAccountInfo () {
  232. const data = await getUserAccount()
  233. if (!data) return
  234. this.userAccount = data
  235. this.getUserAccountBalance()
  236. },
  237. // 获取账户余额
  238. async getUserAccountBalance () {
  239. const data = await getAccountBalance()
  240. const obj = Object.assign(this.userAccount, data)
  241. localStorage.setItem('userAccount', JSON.stringify(obj))
  242. },
  243. // 检查密码是否需要修改
  244. async updatePasswordCheck () {
  245. const bool = await getEntUpdatePasswordCheck()
  246. if (bool) {
  247. // 强制修改密码
  248. localStorage.setItem('entUpdatePassword', bool ? 'needChange' : 'doNotNeedChange')
  249. }
  250. },
  251. // 获取学生信息
  252. async getStudentInformation () {
  253. const data = await getStudentInfo()
  254. this.studentInfo = data
  255. localStorage.setItem('studentInfo', data ? JSON.stringify(data) : '{}')
  256. router.push('/recruit/personal/personalCenter/student/information')
  257. },
  258. // 获取学校基本信息
  259. async getSchoolInfo (isRegister = false) {
  260. const data = await getSchoolInformation()
  261. this.schoolInfo = data || {}
  262. localStorage.setItem('schoolInfo', data ? JSON.stringify(data) : '{}')
  263. // 注册时执行下方内容
  264. if (!isRegister) return
  265. if (!data || !Object.keys(data).length) {
  266. // console.log('没有注册过,直接跳转到学校注册页面')
  267. router.push({ path: '/register/schoolIndex' })
  268. }
  269. else if (data?.authStatus === '0' || data?.authStatus === '2') {
  270. // console.log('审核中,等待审核 || 审核不通过,重新填写信息提交', data.authStatus)
  271. localStorage.setItem('registerSchoolInfo', JSON.stringify(data))
  272. router.push({ path: '/register/school/inReview' })
  273. }
  274. else if (data?.authStatus === '1') {
  275. // console.log('审核通过直接进入老师页面')
  276. router.push('/recruit/teacher/studentList/index')
  277. }
  278. }
  279. }
  280. },
  281. {
  282. persist: true,
  283. devtools: true
  284. }
  285. )