import { login, fsLogin, getInfo, qcLogin } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'
import { getPromotionRole } from '@/dicts'
import { CITY_MANAGER } from '@/dicts'

export default defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      userInfo: ''
    }),
    actions: {
      /**
       * 登录
       * @param {*} param { type: 登录方式 data: 登录数据，code / 工号密码 }
       * @returns {Promise}
       */
      login({ type, data }) {
        return new Promise((resolve, reject) => {
          if (type === 'upass') {
            const { username, password } = data
            login({ username, password }).then(res => {
              setToken(res.data.access_token)
              this.token = res.data.access_token
              resolve()
            }).catch(error => {
              reject(error)
            })
          } else if (type === 'fs') {
            const { code } = data
            fsLogin({ code }).then(res => {
              setToken(res.access_token)
              this.token = res.access_token
              resolve()
            }).catch(error => {
              reject(error)
            })
          } else if (type === 'qc') {
            // 勤策登录
            qcLogin(data).then(res => {
              setToken(res.access_token)
              this.token = res.access_token
              resolve() 
            })
          }
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.user
            let avatar = user.avatar || ""
            if (!isHttp(avatar)) {
              avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
            }
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.userId
            this.name = user.nickName
            this.avatar = avatar
            this.userInfo = user
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          // logout(this.token).then(() => {
          this.token = ''
          this.roles = []
          this.permissions = []
          removeToken()
          resolve()
          // }).catch(error => {
          //   reject(error)
          // })
        })
      }
    },
    getters: {
      // 获取促销系统身份（true 城市经理）
      getPromotionIdentity(state) {
        return getPromotionRole(state.userInfo.privilegeId) === CITY_MANAGER
      },
      // 获取员工工号，姓名，id
      getEmployeeInfo(state) {
        return {
          operNo: state.userInfo.userName,
          operName: state.userInfo.nickName,
          operId: state.userInfo.userId
        }
      },
      // 获取员工工号
      getEmployeeNo(state) {
        return state.userInfo.userName
      },
      // 获取员工姓名
      getEmployeeName(state) {
        return state.userInfo.nickName
      }
    }
  })

