import { login, fsLogin, getInfo, qcLogin, refreshTokenAPI } from '@/api'
import { getToken, setToken, removeToken, getRefreshToken, setRefreshToken, removeRefreshToken, isMobile } from '@/utils'
import useAppStore from '@/store/modules/app'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'

export default defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      refreshToken: getRefreshToken(),
      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
              // this.refreshToken = res.data.refresh_token
              setToken(res.data.access_token)
              // setRefreshToken(res.data.refresh_token)
              useAppStore().setBelongSys(0) // 0 链路中心
              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
              useAppStore().setBelongSys(0) // 0 链路中心
              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
              useAppStore().setBelongSys(isMobile() ? 1 : 0) // 移动端保存 1 勤策，PC 网页保存 0 链路中心
              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)
          // })
        })
      },
      // 刷新token
      async refreshTokenFn() {
        const res = await refreshTokenAPI(this.refreshToken)
        this.token = res.data.access_token
        setToken(res.data.access_token)
      },
    },
    getters: {
      /**
       * 获取促销系统身份 （null 2 为职能角色，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, // 员工昵称名字
        }
      }
    }
  })

