import { ref } from 'vue'
import { defineStore } from 'pinia'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { loginWithMessage, logout } from '@/api/login'
import { useAppStore } from '@/stores/app'

export const useUserStore = defineStore('user', () => {
  const userId = ref(localStorage.getItem('userid'))
  const nickname = ref(localStorage.getItem('account'))
  const orgName = ref(localStorage.getItem('orgNm'))
  const avatar = ref('')
  const roles = ref(localStorage.getItem('allNode'))

  const token = ref(getToken())

  function setUserInfo(data) {
    userId.value = data.userId
  }

  function Login(phone, captcha, smsCode) {
    return new Promise((resolve, reject) => {
      loginWithMessage(phone, captcha, smsCode)
        .then((res) => {
          let userid = res.data.guid;
          let loginName = res.data.persName;
          let guid = res.data.orgId;
          let orgNm = res.data.orgNm;
          let isAdmin = res.data.permission;
          let allNode = JSON.stringify(res.data.allNode);//当前用户所在组信息
          let allOrg = JSON.stringify(res.data.allOrg);
          let persType = res.data.persType;
          let accessToken = res.accessToken;  //token是否过期
          localStorage.setItem('userid', userid);
          localStorage.setItem('account', loginName);
          localStorage.setItem('guid', guid);
          localStorage.setItem('orgNm', orgNm);
          localStorage.setItem('isAdmin', isAdmin);
          localStorage.setItem('persType', persType);
          localStorage.setItem('accessToken', accessToken);
          let orgId = res.data.orgId;
          localStorage.setItem('orgId', orgId);
          localStorage.setItem('allOrg', allOrg);
          localStorage.setItem("currentOrgId", res.data.defaultOrg.orgId);  //省级当前的机构id
          localStorage.setItem("currentRlcode", res.data.defaultOrg.rlcode);  //省级当前的行政区划编码
          localStorage.setItem("currentOrgNm", res.data.defaultOrg.orgNm);  //省级当前的机构名称
          localStorage.setItem('allNode', allNode);

          userId.value = userid;
          nickname.value = loginName;
          orgName.value = orgNm;
          setToken(res.accessToken);
          token.value = res.accessToken;

          const appStore = useAppStore()
          appStore.setCurrentOrgId(res.data.defaultOrg.orgId)

          
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
  // 查询用户信息
  // function getInfo() {
  //   return new Promise((resolve, reject) => {
  //     getInfo()
  //       .then((res) => {
  //         const user = res.user;
  //         const avatar =
  //           user.avatar == ""
  //             ? require("@/assets/images/default-user-img.jpg")
  //             : process.env.VUE_APP_BASE_API + user.avatar;
  //         if (res.roles && res.roles.length > 0) {
  //           // 验证返回的roles是否是一个非空数组
  //           commit("SET_ROLES", res.roles);
  //           commit("SET_PERMISSIONS", res.permissions);
  //         } else {
  //           commit("SET_ROLES", ["ROLE_DEFAULT"]);
  //         }
  //         commit("SET_USER_ID", user.userId);
  //         commit("SET_NAME", user.userName);
  //         commit("SET_NICKNAME", user.nickName);
  //         commit("SET_AVATAR", avatar);
  //         resolve(res);
  //       })
  //       .catch((error) => {
  //         reject(error);
  //       });
  //   });
  // }

  // 退出系统
  function LogOut() {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        localStorage.clear()
        token.value = ""
        removeToken();
        resolve();
      })
        .catch((error) => {
          reject(error);
        });
    });
  }

  return { userId, nickname, orgName, setUserInfo, Login, LogOut }
})
