import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getPriv, getTokenByMobile } from '@/api/loginAPI';

export const useUserStore = defineStore('user', () => {
  const accessToken = ref('');

  function setToken(token) {
    accessToken.value = token;
  }

  function getLogin(userInfo) {
    return new Promise((resolve, reject) => {
      getTokenByMobile(userInfo)
        .then((res) => {
          if (res.success) {
            const userid = res.data.guid;
            const loginName = res.data.persName;
            const guid = res.data.orgId;
            const orgNm = res.data.orgNm;
            const isAdmin = res.data.permission;
            const allNode = JSON.stringify(res.data.allNode);
            const allOrg = JSON.stringify(res.data.allOrg);
            const persType = res.data.persType;
            const token = res.accessToken;
            localStorage.setItem('userid', userid);
            localStorage.setItem('persId', userid);
            localStorage.setItem('account1', loginName);
            localStorage.setItem('guid', guid);
            localStorage.setItem('orgNm', orgNm);
            localStorage.setItem('isAdmin', isAdmin);
            localStorage.setItem('persType', persType);
            localStorage.setItem('ownApp', '1');
            localStorage.setItem('accessToken', token);
            const orgId = res.data.orgId;
            localStorage.setItem('orgId', orgId);
            localStorage.setItem('allOrg', allOrg);
            localStorage.setItem('currentOrgId', res.data.defaultOrg.orgId);
            localStorage.setItem('currentRlcode', res.data.defaultOrg.rlcode);
            localStorage.setItem('currentAdCode', res.data.defaultOrg.adCode);
            localStorage.setItem('currentOrgNm', res.data.defaultOrg.orgNm);
            localStorage.setItem('allNode', allNode);
            setToken(token);
            var params = {
              userId: localStorage.getItem('persId'),
              ownApp: localStorage.getItem('ownApp'),
            };
            getPriv(params).then(async (res) => {
              if (res.success && res.data) {
                sessionStorage.setItem(
                  'privCollect',
                  JSON.stringify(res.data.priv),
                );
              }
            });
            resolve();
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  return {
    accessToken,
    setToken,
    getLogin,
  };
});
