import { defineStore } from 'pinia'
import DadaApi from '@/api/dada'
import type { LoginRequest } from '@/api/dada'

export interface userStateTypes {
    nickName: string,
    id: string | number,
    token: string // maxkb token
    dadaTenantId: string // 租户id
    dadaTenantName: string // 租户id
    dadaToken: string
    isHiddenSidebar: boolean // 是否隐藏侧边栏
}

const useDadaStore = defineStore({
  id: 'dada',
  state: (): userStateTypes => ({
    nickName: '',
    id: '',
    token: '',  // maxkb token
    dadaTenantId: '',
    dadaTenantName: '',
    dadaToken: '',
    isHiddenSidebar: false
  }),
  actions: {

    getPermissions() {
    
    },
    getRole() {
    
    },

    getDadaToken(): String | null {
      return this.dadaToken || localStorage.getItem('dadaToken')
    },

    getTenantId(): String | null {
      return this.dadaTenantId || localStorage.getItem('dadaTenantId')
    },

    async getUserInfo() {
      return DadaApi.getUserInfo().then((ok) => {
        const { nickName, id, tenantId } = ok;
        this.id = id;
        this.nickName = nickName;
        DadaApi.findCompanyDept(tenantId || localStorage.getItem('dadaTenantId')).then((ok) => {
          this.dadaTenantName = ok?.currentTenantName
        })
        return ok;
      })
    },

    async login(data: LoginRequest) {
      return DadaApi.login(data).then((ok: any): any => {
        const { maxToken, tenantId, token } = ok
        this.token = maxToken
        this.dadaTenantId = tenantId
        this.dadaToken = token
        localStorage.setItem('dadaTenantId', tenantId)
        localStorage.setItem('dadaToken', token)
        localStorage.setItem('token', maxToken)
        return this.getUserInfo()
      })
    },


    async logout() {
      return DadaApi.logout().then(() => {
        localStorage.removeItem('dada-tenantId');
        localStorage.removeItem('dadaTenantId');
        localStorage.removeItem('dadaToken');
        document.cookie = 'token=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;';
        this.nickName = ''
        this.id = ''
        this.token = ''  // maxkb token
        this.dadaTenantId = ''
        this.dadaToken = ''
        return true
      })
    },

    async setSidebar(status: boolean) {
      this.isHiddenSidebar =  status || !this.isHiddenSidebar
    }
  }
})

export default useDadaStore
