import { defineStore } from 'pinia'
import { setToken, removeToken, setRefreshToken, getToken } from '@/utils/auth'
import {
  smsLogin,
  passwordLogin, 
  getBaseInfo, 
  passwordLoginOfEnterprise, 
  smsLoginOfEnterprise, 
  switchLoginOfEnterprise, 
  getEnterprisingUserInfo, 
  logoutToken, 
  logout 
} from '@/api/common'
import { getUserInfo } from '@/api/personal/user'
import { getEnterpriseUserAccount, getUserAccount } from '@/api/common'
import Snackbar from '@/plugins/snackbar'
import { timesTampChange } from '@/utils/date'
import { updateEventList } from '@/utils/eventList'
import { getBaseInfoDictOfName } from '@/utils/getText'
// import { useIMStore } from './im'

// const useIM = useIMStore()


export const useUserStore = defineStore('user',
  {
    state: () => ({
      // loginType: null, // 登录类型 // 330为企业登录
      accountInfo: localStorage.getItem('accountInfo') ? JSON.parse(localStorage.getItem('accountInfo')) : {}, // 登录返回的信息
      userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}, // 当前登录账号信息
      baseInfo: localStorage.getItem('baseInfo') ? JSON.parse(localStorage.getItem('baseInfo')) : {}, // 人才信息
      userAccount: {}, // 用户账户信息
      enterpriseUserAccount: {} // 企业账户信息
    }),
    actions: {
      // 短信登录
      handleSmsLogin (data) {
        return new Promise((resolve, reject) => {
          const loginApi = data.loginType === 330 ? smsLoginOfEnterprise : smsLogin
          loginApi(data).then(async res => {
            // this.loginType = data.loginType
            setToken(res.accessToken)
            setRefreshToken(res.refreshToken)
            this.accountInfo = res
            localStorage.setItem('accountInfo', JSON.stringify(res))
            localStorage.setItem('expiresTime', res.expiresTime) // token过期时间
            localStorage.setItem('loginType', 'personal')
            await this.getUserInfos()
            this.getUserBaseInfos()
            resolve()
          }).catch(err => { reject(err) })
        })
      },

      // 密码登录
      async handlePasswordLogin(data) {
        return new Promise((resolve, reject) => {
          const loginApi = data.loginType === 330 ? passwordLoginOfEnterprise : passwordLogin
          loginApi(data).then(res => {
            setToken(res.accessToken)
            setRefreshToken(res.refreshToken)
            this.accountInfo = res
            localStorage.setItem('accountInfo', JSON.stringify(res))
            localStorage.setItem('expiresTime', res.expiresTime) // token过期时间
            localStorage.setItem('loginType', 'personal')
            this.getUserInfos()
            this.getUserBaseInfos()
            resolve()
          }).catch(err => { reject(err) })
        })
      },
      // 获取当前登录账户信息
      async getUserInfos () {
        try {
          const api = this.loginType ? getEnterprisingUserInfo : getUserInfo
          const data = await api({ id: this.accountInfo.userId })
          this.userInfo = data
          localStorage.setItem('userInfo', JSON.stringify(data))
          // 获取密钥
          // this.getChatKey()
          // useIM.init()
          updateEventList(true) // 获取规则配置跟踪列表
          this.getUserAccountInfo()
        } catch (error) {
          Snackbar.error(error.msg)
        }
      },
      // 获取当前登录账户的基本信息（人才信息）
      async getUserBaseInfos (userId = null) {
        try {
          const api = this.loginType ? null : getBaseInfo
          if (!api) return
          const data = await api({ userId: userId || this.accountInfo.userId })
          if (!data) return localStorage.setItem('baseInfo', '{}')
          this.baseInfo = await this.getFieldText(data)
          localStorage.setItem('baseInfo', JSON.stringify(this.baseInfo))
        } catch (error) {
          Snackbar.error(error)
        }
      },
      // 字典对应中文
      async getFieldText (data) {
        if (data.birthday && data.birthday !== 0) data.birthdayText = timesTampChange(data.birthday, 'Y-M-D') // 出生日期
        if (data.firstWorkTime && data.firstWorkTime !== 0) data.firstWorkTimeText = timesTampChange(data.firstWorkTime, 'Y-M-D') // 首次工作时间
        if (data.areaId && data.areaId !== 0) await getBaseInfoDictOfName(0, data, data.areaId, 'areaName') // 现居住地text
        if (data.eduType && data.eduType !== 0) await getBaseInfoDictOfName(1, data, data.eduType, 'eduTypeText') // 学历
        if (data.expType && data.expType !== 0) await getBaseInfoDictOfName(2, data, data.expType, 'expTypeText') // 工作经验
        if (data.sex && data.sex !== 0) await getBaseInfoDictOfName(3, data, data.sex, 'sexTypeText') // 性别
        if (data.jobType && data.jobType !== 0) await getBaseInfoDictOfName(4, data, data.jobType, 'jobTypeText') // 求职类型
        if (data.jobStatus && data.jobStatus !== 0) await getBaseInfoDictOfName(5, data, data.jobStatus, 'jobStatusText') // 	求职状态
        if (data.maritalStatus && data.maritalStatus !== 0) await getBaseInfoDictOfName(6, data, data.maritalStatus, 'maritalText') // 	婚姻状况
        return data
      },
      // 退出登录
      async userLogout (type) {
        // type: 1求职端 2招聘端
        if (type === 1) {
          await logout()
        } else await logoutToken(getToken())
        removeToken()
        this.userInfo = {}
        this.baseInfo = {}
        this.accountInfo = {}
        localStorage.clear()
      },
      // 切换为招聘者
      async changeRole (enterpriseId) {
        // 先退出个人登录
        await logout()

        const data = await switchLoginOfEnterprise({ enterpriseId })
        setToken(data.accessToken)
        setRefreshToken(data.refreshToken)
        localStorage.setItem('loginType', 'enterprise')
        localStorage.setItem('accountInfo', JSON.stringify(data))
        localStorage.setItem('expiresTime', data.expiresTime)
        localStorage.setItem('currentRole', 'enterprise')
        await this.getEnterpriseInfo()
        await this.getEnterpriseUserAccountInfo()
        updateEventList(false)
        Snackbar.success('切换成功')
      },
      // 获取当前登录的企业用户信息
      async getEnterpriseInfo () {
        const result = await getEnterprisingUserInfo()
        this.baseInfo = result
        
        // 是否为企业账号管理员
        const isAdmin = result.userType === '1'
        localStorage.setItem('isAdmin', isAdmin)

        localStorage.setItem('baseInfo', JSON.stringify(result))
      },
      // 获取企业账户信息
      async getEnterpriseUserAccountInfo () {
        const data = await getEnterpriseUserAccount()
        if (!data) return
        this.enterpriseUserAccount = data
        localStorage.setItem('enterpriseUserAccount', JSON.stringify(data))
      },
      // 获取用户账户信息
      async getUserAccountInfo () {
        const data = await getUserAccount()
        if (!data) return
        this.userAccount = data
        localStorage.setItem('userAccount', JSON.stringify(data))
      }
    }
  },
  {
    persist: true,
    devtools: true
  }
)

