import { defineStore } from 'pinia';
import type { UserState } from './types';

// import { localStorage } from '@/utils/storage';
import { loginApi, logoutApi } from '@/api/auth';

import { resetRouter } from '@/router';
import {ElMessage, ElMessageBox} from "element-plus";


const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    ut: '',
    userInfo: ''

  }),
  actions: {
    async RESET_STATE() {
      this.$reset();
    },
    /**
     * 登录
     */
    login(data: any) {
      //const { userId, passWord } = data;
      return new Promise((resolve, reject) => {
        loginApi(data)
          .then(res => {
            console.log(res)
            if (res.status != "success") {
              ElMessage({
                message: res.message,
                type: 'fail',
              })
              return
            }
            const accessToken: any = res.data;
            //转为json
            let userinfo = JSON.parse(accessToken)
            console.info(userinfo)
            localStorage.setItem('userId', userinfo.USERNAME);
            localStorage.setItem('userName', userinfo.USERNAME || "");
            localStorage.setItem('session', userinfo.session);
            localStorage.setItem('token', userinfo.token);
            this.ut = userinfo.userId;
            this.userInfo = userinfo
            resolve(accessToken);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /**
     * 登出
     * */
    logout() {
      return new Promise((resolve, reject) => {
        logoutApi()
          .then(() => {
            localStorage.removeItem('token');
            this.RESET_STATE();
            resetRouter();
            resolve(null);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /**
     * 获取token
     * */
    getToken() {
      return localStorage.getItem('token');
    },
    /**
     * 获取userId
     * */
    getUserId() {
      return localStorage.getItem('userId');
    }
  }
});

export default useUserStore;
