import { defineStore } from 'pinia';
import { api } from 'boot/axios';
import {router} from 'src/router';
import {IDomainInfo} from '../types/ActionTypes';


export interface IUserState{
  token?:string;
  returnUrl:string;
  currentDomain:IDomainInfo;
  LeftDrawer:boolean;
}

export const useAuthStore = defineStore({
    id: 'auth',
    state: ():IUserState =>{
      const token=localStorage.getItem('token')||'';
      if(token!==''){
        api.defaults.headers["Authorization"]='Bearer ' + token;
      }
      return {
          token,
          returnUrl: '',
          LeftDrawer:false,
          currentDomain: JSON.parse(localStorage.getItem('currentDomain')||"{}")
        }
    },
    getters:{
      toggleLeftDrawer():boolean{
          return this.LeftDrawer;
      }
    },
    actions: {
        toggleLeftMenu(){
          this.LeftDrawer=!this.LeftDrawer;
        },
        async login(username:string, password:string) {
          const params = new URLSearchParams();
          params.append('username', username);
          params.append('password', password);
          try{
              const result = await api.post(`api/token`,params);
              console.info(result);
              this.token =result.data.access_token;
              localStorage.setItem('token', result.data.access_token);
              api.defaults.headers["Authorization"]='Bearer ' + this.token;
              this.currentDomain=await this.getCurrentDomain();
              localStorage.setItem('currentDomain',JSON.stringify(this.currentDomain));
              this.router.push(this.returnUrl || '/');
              return true;
          }catch(e)
          {
              console.info(e);
              return false;
          }
        },
        async getCurrentDomain():Promise<IDomainInfo>{
          const activedomain = await api.get(`api/activedomain`);
          return {
            id:activedomain.data.id,
            domainName:activedomain.data.name,
            kintoneUrl:activedomain.data.url
          }
        },
        async getUserDomains():Promise<IDomainInfo[]>{
          const resp = await api.get(`api/domain`);
          const domains =resp.data as any[];
          return domains.map(data=>{
            return {
              id:data.id,
              domainName:data.name,
              kintoneUrl:data.url
            }
          });
        },
        logout() {
            this.token = undefined;
            localStorage.removeItem('token');
            localStorage.removeItem('currentDomain');
            router.push('/login');
        },
        async setCurrentDomain(domain:IDomainInfo){
          if(domain.id===this.currentDomain.id){
            return;
          }
          await api.put(`api/activedomain/${domain.id}`);
          this.currentDomain=domain;
          localStorage.setItem('currentDomain',JSON.stringify(this.currentDomain));
        }
    }
});
