import { defineStore } from 'pinia';
import { login, logout, getInfo } from '@/jtools/api/login';
import { queryVip, getVipList } from '@/jtools/api/vip';
import constants from '@/jtools/constants';
import storage from '@/jtools/storage';

const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    token: storage.get('token'),
    isLogin: storage.get('isLogin'), // 是否登陆
    userInfo: storage.get('userInfo'), // 用户信息
    currentCartype: storage.get('carType') || '1001',
    vipOnList: [],
    vipAllList: []
  }),

  actions: {
    login(params) {
      return new Promise(async (resolve, reject) => {
        const resp = await login(params);
        if (resp.code === '0000') {
          // 保存登录信息，用于重新登录
          this.isLogin = true;
          this.token = resp.data.token;
          this.userInfo = resp.data;
          storage.set('isLogin', true);
          storage.set('token', resp.data.token);
          storage.set('userInfo', resp.data);
          storage.remove('companyId');
          resolve(resp.data);
        } else {
          reject();
        }
      });
    },
    // 登出
    logout(force = false) {
      return new Promise((resolve, reject) => {
        this.resetUserData();
        uni.redirectTo({
          url: '/pages/login/login'
        });
        resolve();
      });
    },
    //过期登出
    logoutWithoutToken(force = false) {
      return new Promise((resolve, reject) => {
        this.resetUserData();
        resolve();
      });
    },
    // 获取用户信息
    getUserInfo() {
      getInfo().then(resp => {
        if (resp.code == '0000') {
          this.userInfo = resp.data;
          storage.set('userInfo', resp.data);
        }
      });
    },
    resetUserData() {
      this.isLogin = false;
      this.token = '';
      this.userInfo = {};
      this.vipOnList = [];
      storage.remove('isLogin');
      storage.remove('token');
      storage.remove('userInfo');
    },
    // 查询当前用户的vip开通情况
    async searchUserVip() {
      this.currentCartype = storage.get('carType') || '1001';
      const resp = await queryVip({ carTypeId: this.currentCartype, memberId: null, subject: '' });
      if (resp.code == '0000') {
        this.vipOnList = resp.data;
      }
    },
    // 查询所有的vip
    queryVipList() {
      this.currentCartype = storage.get('carType') || '1001';
      getVipList({ carTypeId: this.currentCartype, memberId: null, subject: '' }).then(resp => {
        if (resp.code == '0000') {
          this.vipAllList = resp.data;
        }
      });
    }
  }
});

export default useUserStore;
