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'

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 => {
              this.token = res.data.access_token
              setToken(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') {
            // 勤策登录
            const { code } = data
            qcLogin({ code }).then(res => {
              setToken(res.access_token)
              this.token = res.access_token
              resolve()
            }).catch(error => {
              reject(error)
            })
          }
        })
      },
      // 获取用户信息
      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: {
      /**
       * 获取促销系统身份 （0 null 为职能角色，1 为城市经理）
       * @param {*} state 
       * @returns （true 城市经理）（false 职能角色）
       */
      promotionIdentity(state) {
        return state.userInfo.privilegeId === 1
      },
      // 员工关键信息
      empInfo(state) {
        return {
          empId: state.userInfo.userId, // 员工 id
          empNo: state.userInfo.userName, // 员工工号
          empName: state.userInfo.nickName, // 员工昵称名字
        }  
      }
    }
  })

