user.ts 15.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
import useRouteStore from './route'
import useMenuStore from './menu'
import router from '@/router'
import { ElMessage } from 'element-plus'
import apiUser from '@/api/modules/user'
import { getCurrentTime } from '@/utils/common'
import { getSystemMenu, getUserInfo, getTokenByCode, loginOut, refreshToken, editPasswordInterface, getCurrentUserInfo, getTenantDetailInfo } from '@/api/modules/queryService'
import { getConnectorStatus } from '@/api/modules/dataRequire'
import { getCurrentTenantCache } from '@/api/modules/dataIdentify'

const useUserStore = defineStore(
  // 唯一ID
  'user',
  () => {
    const routeStore = useRouteStore()
    const menuStore = useMenuStore()
    const currentTime = getCurrentTime()
    const account = ref(localStorage.account ?? '')
    const userId = ref(localStorage.userId ?? '')
    const userName = ref(localStorage.userName ?? '')
    const userData = ref(localStorage.userData ?? '{}')
    const currentTenantGuid = ref(localStorage.currentTenantGuid ?? '');
    const userInfoData = ref(JSON.parse(localStorage.userInfoData ?? "[]"))
    const token = ref(localStorage.token ?? '')
    const tabbarMap: any = ref({})
    const tabbar = ref([])
    const permissions = ref<string[]>([])
    const isLoginOut = ref(false);
    const isLogin = ref(token.value ? true : false);//退出登录。
    //当前连接器是否已注销
    const isLogOutConnector = ref(localStorage.isLogOutConnector ?? 'N');
    const getTokenPromise: any = ref(null);
    /* idass的登录页面url,退出登录需要跳转到登录页。*/
    const idassLoginUrl = import.meta.env.VITE_IDASS_BASEURL;
    const timer: any = ref(null);
    const isGetCurrUserInfo = ref(false); //记录登录时是否已经获取登录用户的信息,根据用户信息展示角色选择对话框。
    //获取token.
    function getToken(data, state) {
          data.platformGuid = "7f16f697aec111ef8656fa163e60becd";
          data.userType = 2;
         // data.appKey = '691689d8e4b0f359c04d204a';
          data.validateUri = location.origin == 'http://localhost:9000' ? 'http://localhost:9000/' : location.origin + '/';
          return getTokenPromise.value = getTokenByCode(data).then((res: any) => {
            getTokenPromise.value = null;
            console.log(res);
            if (res.code == '00000') {
              console.log(res.data);
              isLogin.value = true;
              localStorage.setItem('code', `${data.code}`);
              localStorage.setItem('state', state);
              localStorage.setItem('token', res.data.token || "");
              token.value = res.data.access_token;
              localStorage.setItem('refresh_token', res.data.refreshToken || "");
              const expiresIn = (Date.now() + 1700000) + "";
              localStorage.setItem('expiresIn', expiresIn);
              refreshUserToken(false);
              //获取用户信息
              account.value = res.data.logonUser
              userId.value = res.data.userId;
              let exec = (currTenantGuid) => {
                currentTenantGuid.value = currTenantGuid ? currTenantGuid : (
                  res.data.tenantInfoList && res.data.tenantInfoList.length
                    ? res.data.tenantInfoList[0].guid
                    : "");
                localStorage.setItem(
                  "currentTenantGuid",
                  currentTenantGuid.value,
                );
                getTenantDetailInfo(currentTenantGuid.value).then(
                  (res: any) => {
                    if (res.code == "00000") {
                      localStorage.setItem(
                        "tenantInfo",
                        JSON.stringify(res.data),
                      );
                    } else {
                      ElMessage.error(res.msg);
                    }
                  },
                );
                getConnectorStatus().then((res: any) => {
                  if (res.code == "00000") {
                    isLogOutConnector.value = res.data?.isLogOut || "N";
                    localStorage.setItem(
                      "isLogOutConnector",
                      isLogOutConnector.value,
                    );
                  } else {
                    // 暂不弹错误提示
                  }
                });
                return getCurrentUserInfo({
                  tenantGuid: currentTenantGuid.value,
                }).then((res: any) => {
                  console.log(res, "getCurrentUserInfo");
                  if (res.code == "00000") {
                    userName.value = res.data.staffName;
                    localStorage.setItem("userName", res.data?.staffName);
                    localStorage.setItem("userData", JSON.stringify(res.data));
                    userData.value = localStorage.getItem("userData");
                    isGetCurrUserInfo.value = true;
                    // return getSystemMenu({ tenantGuid: currentTenantGuid.value }, res.data?.isAdmin == 'Y' && (!res.data?.superTubeFlag || res.data?.superTubeFlag == 'Y')).then((info: any) => { //解决页面调用流程接口传递staffGuid,为空的问题
                    //   if (info.code == '00000') {
                    //     localStorage.setItem('userInfoData', JSON.stringify(info.data));
                    //     userInfoData.value = info.data;
                    //   //  window.location.href = location.origin + info.data[0].menuList[0].path
                    //   } else {
                    //     ElMessage.error(info.msg)
                    //   }
                    // })
                  } else {
                    ElMessage.error(res.msg);
                  }
                });
              };
              getCurrentTenantCache().then((res: any) => {
                if (res?.code == '00000') {
                  exec(res.data || null);
                } else {
                  exec(null);
                  res?.msg && ElMessage.error(res.msg);
                }
              }).catch(() => {
                exec(null);
              })
            } else {
              isLogin.value = false;
              isGetCurrUserInfo.value = false;
             // ElMessage.error(res.msg);//授权码被重复使用,不抛出异常。
            }
          });
    }

    /** 根据选择的角色获取用户菜单 */
    function getUserSystemMenuByRole(role) {
      let data = localStorage.getItem('userData');
      let userData = data && JSON.parse(data);
      return getSystemMenu(
        { tenantGuid: localStorage.getItem('currentTenantGuid'),
          roleGuid: role == 'use' ? '33cc6290689249a28004b591a2daac25' : (role == 'provider' ? '0ad4985055fa4007aca9e2782ccd23d2' : '')
         }, false
        // role != 'operation' ? false : (userData?.isAdmin == "Y" && (!userData?.superTubeFlag || userData?.superTubeFlag == "Y"))
      ).then((info: any) => {
        //解决页面调用流程接口传递staffGuid,为空的问题
        if (info.code == "00000") {
          localStorage.setItem("userInfoData", JSON.stringify(info.data));
          userInfoData.value = info.data;
          //  window.location.href = location.origin + info.data[0].menuList[0].path
          return info.data || [];
        } else {
          ElMessage.error(info.msg);
          return false;
        }
      });
    }

    async function refreshUserToken(isExec = true) {
      let expiresIn = localStorage.getItem('expiresIn');
      if (!expiresIn || (parseInt(expiresIn) - Date.now()) < 0) {
        return;
      }
      const process = async () => {
        if (parseInt(expiresIn) - Date.now() < 600000) {
          const refreshing = localStorage.getItem('refreshing');
          let now = new Date();
          if (!refreshing || new Date(refreshing) < now) {//确保多个页面只刷新一次。
            localStorage.setItem('refreshing', now.toISOString());
            await refresh();
            localStorage.removeItem('refreshing');
          }
        }
      }
      if (isExec) {
        await process();
      }
      /** 轮询是否需要刷新token。如果是同步多个调用,则不处理错误的信息。 */
      timer.value = setInterval(async () => {
        process();
      }, 600000);
    }

    function refresh() {
      return getTokenPromise.value = refreshToken({
        refreshToken: localStorage.getItem('refresh_token')
      }).then((resInfo: any) => {
        getTokenPromise.value = null;
        if (resInfo.code == '00000') {
          localStorage.setItem('token', resInfo.data.accessToken);
          token.value = resInfo.data.accessToken;
          localStorage.setItem('refresh_token', resInfo.data.refreshToken);
          const expiresIn = (Date.now() + 1700000) + "";
          localStorage.setItem('expiresIn', expiresIn);
        } else {
          //会出现同步刷新token就退出登录的问题,去掉这个代码。
          //logout(true)
        }
      }).catch(() => {
        localStorage.removeItem('refreshing');
      });
    }

    // 登录
    async function login(data: {
      logonUser: string
      pwd: string
      userType: number
      platformGuid: string
    }) {
      // 通过 mock 进行登录
      const res = await apiUser.login(data)
      //等菜单返回之后再设置已登录状态,否则会出现菜单还未请求到,但是动态路由已经显示。
      const resData = res.data
      isLogin.value = true;
      localStorage.setItem('account', data.logonUser)
      localStorage.setItem('userId', resData.userId)
      localStorage.setItem('userName', resData.userName)
      localStorage.setItem('token', resData.token)
      /** 非idaas code登录的,清除code */
      localStorage.setItem('code', '')
      localStorage.setItem('userData', JSON.stringify(resData.data))
      account.value = data.logonUser
      userId.value = resData.userId
      userName.value = resData.userName
      token.value = resData.token
      userData.value = JSON.stringify(resData.data)
      return getUserInfo().then((info: any) => {
        if (info.code == '00000') {
          localStorage.setItem('userInfoData', JSON.stringify(info.data))
          userInfoData.value = info.data
        } else {
          ElMessage.error(info.msg)
        }
      })
    }
    // 登出
    async function logout(isErrorReturn = false, redirect = router.currentRoute.value.fullPath) {
      if (!isErrorReturn && localStorage.getItem('code')) {
        isLoginOut.value = true;
        loginOut().then(() => {
          localStorage.clear()
          account.value = ''
          userId.value = ''
          userName.value = ''
          userData.value = ''
          token.value = '';
          timer.value && clearInterval(timer.value);
          isLogin.value = false;
          isGetCurrUserInfo.value = false;
          userInfoData.value = [];
          routeStore.removeRoutes()
          menuStore.setActived(0)
          tabbar.value = []
          tabbarMap.value = {}
          window.location.href = idassLoginUrl + '?logout=1';
        });
      } else {
        let hasCode = localStorage.getItem('code');
        isLoginOut.value = true;
        localStorage.clear()
        account.value = ''
        userId.value = ''
        userName.value = ''
        userData.value = ''
        token.value = '';
        timer.value && clearInterval(timer.value);
        isLogin.value = false;
        isGetCurrUserInfo.value = false;
        userInfoData.value = [];
        routeStore.removeRoutes()
        menuStore.setActived(0)
        tabbar.value = []
        tabbarMap.value = {}
        if (hasCode) {
          window.location.href = idassLoginUrl + '?logout=1';
        } else {
          router.push({
            name: 'login',
            query: {
              ...(router.currentRoute.value.path !== '/' && router.currentRoute.value.name !== 'login' && { redirect }),
            },
          })
        }
      }
    }
    // 获取我的权限
    async function getPermissions() {
      // 通过 mock 获取权限
      // const res = await apiUser.permission()
      permissions.value = [account.value]
      return permissions.value
    }
    // 修改密码
    async function editPassword(data) {
      await editPasswordInterface(data).then((info: any) => {
        if (info.code == '00000') {
          ElMessage.success('密码修改成功,请重新登录')
        } else {
          ElMessage.error(info.msg)
        }
      });
    }
    // 根据路由设置tabbar
    async function setTabbarInfo(list) {
      let obj: any = {}
      list.map(item => {
        let mark = item.path.split('/')[1];
        obj.activePath = ''
        obj.tabbar = []
        tabbarMap.value[mark] = obj
        // let mark = ''
        // if (item.meta.title == '数据标准') {
        //   mark = 'data-standards'
        // } else if (item.meta.title == '元数据') {
        //   mark = 'data-meta'
        // } else if (item.meta.title == '数据目录') {
        //   mark = 'data-catalog'
        // } else if (item.meta.title == '数据同步') {
        //   mark = 'data-sync'
        // } else if (item.meta.title == '数据质量') {
        //   mark = 'data-quality'
        // } else if (item.meta.title == '数据盘点') {
        //   mark = 'data-inventory'
        // } else if (item.meta.title == '数据资产看板') {
        //   mark = 'data-asset-index'
        // } else if (item.meta.title == '数据资产登记') {
        //   mark = 'data-asset-register'
        // }  else if (item.meta.title == '数据产品管理') {
        //   mark = 'data-asset'
        // } else if (item.meta.title == '入表交易融资') {
        //   mark = 'data-transaction'
        // } else if (item.meta.title == '入表融资指南') {
        //   mark = 'data-guide'
        // } else if (item.meta.title == '入表服务管理') {
        //   mark = 'data-entry'
        // } else if (item.meta.title == '数据资产入表') {
        //   mark = 'data-entry'
        // } else if (item.meta.title == '法律风险意见') {
        //   mark = 'data-security'
        // } else if (item.meta.title == '金融服务') {
        //   mark = 'data-finance'
        // } else if (item.meta.title == '系统管理') {
        //   mark = 'system-manage'
        // } else {
        //   mark = 'app-scenes'
        // }
        // obj.activePath = ''
        // obj.tabbar = []
        // tabbarMap.value[mark] = obj
      })
    }
    function setTabbar(val: any = null) {
      if (val == 'menu') {
        tabbar.value.map((item: any) => {
          item.visible = false
        })
      } else {
        tabbar.value = val
      }
    }
    function setActiveTabbar(mark, val) {
      const tMap = JSON.parse(JSON.stringify(tabbarMap.value))
      if (tMap[mark] != undefined) {
        tMap[mark].activePath = val
      }
      tabbarMap.value = tMap
    }
    /** 是否有新建资产登记的权限。 */
    function hasPermission(menuName, path, btnCaption) {
      let menu = userInfoData.value.find(u => u.productName == menuName);
      if (!menu) {
        return true;
      }
      let m = menu.menuList?.find(m => m.path == path);
      if (!m || m.children == null) {
        return true;
      }
      return m.children.some(c => c.menuType == 'F' && c.menuName == btnCaption);
    }
    return {
      account,
      userId,
      userName,
      userData,
      token,
      userInfoData,
      tabbar,
      tabbarMap,
      currentTime,
      permissions,
      isLogin,
      isGetCurrUserInfo,
      isLoginOut,
      isLogOutConnector,
      getTokenPromise,
      getToken,
      getUserSystemMenuByRole,
      login,
      logout,
      getPermissions,
      editPassword,
      setTabbar,
      setActiveTabbar,
      setTabbarInfo,
      hasPermission,
      refreshUserToken
    }
  },
)

export default useUserStore