import {
  accountLogin,
  validateToken,
} from '~/service/login';
import type { IaccountLogin } from '~/service/login';

import { local } from '~/utils/Storage';
import { defineStore } from 'pinia';
import router from '~/router';
import { callback } from 'wangeditor/dist/utils/observer/mutation';

export const TOKEN = 'token';

export default defineStore('login', {
  getters: {
    headers() {
      return {
        [TOKEN]: this.token
      };
    },
    // true 登录超时 false 正常
    isLoginTimeout(): boolean {
      if (!this.exp_time) {
        return true
      }
      return new Date(this.exp_time).getTime() - Date.now() <= 0;
    }
  },
  state: () => {
    return {
      token: '',
      exp_time: ''
    };
  },
  actions: {
    setExpTime(payload: string): void {
      this.exp_time = payload;
    },
    setToken(payload: string): void {
      this.token = payload;
    },
    // 退出登录
    login(): void {
      router.replace('/')
    },
    // 退出登录
    logout(): void {
      this.token = '';
      this.exp_time = '';

      router.replace('/login')
    },
    // true token无效 false token有效
    async validateToken(): Promise<boolean> {
      const { code, data } = await validateToken();
      if (code !== 0) {
        this.setExpTime('');
        this.setToken('');
        return true;
      }
      this.setExpTime(data.exp_time);
      return false;
    },
    // true 登录超时 false 正常
    async checkLoginIsExp(): Promise<boolean> {
      if (this.isLoginTimeout) {
        await this.validateToken()
      }
      return this.isLoginTimeout;
    },
    async accountLogin(payload: IaccountLogin): Promise<void> {
      const { code, data } = await accountLogin(payload);
      if (code == 0) {
        this.setExpTime(data.exp_time)
        this.setToken(data.token)
        this.login()
      }else{

      }

    }
  },
  persist: {
    enabled: true,
    strategies: [{
      storage: local,
      paths: ['token', 'exp_time']
    }]
  }
});
