import { defineStore } from 'pinia'; 
 | 
import { store } from '@/stores'; 
 | 
import { 
 | 
  getToken as getCacheToken, 
 | 
  getUserInfo as getCacheUserInfo, 
 | 
  setUserInfo, 
 | 
  removeUserInfo, 
 | 
  setUserDetail, 
 | 
  getUserDetail, 
 | 
  removeUserDetail, 
 | 
} from '@/utils/storage/auth'; 
 | 
import Taro, { useRouter } from '@tarojs/taro'; 
 | 
import { ButtonProps } from '@tarojs/components'; 
 | 
import { debounce } from 'lodash'; 
 | 
import { goHome, getStorageLocationCity, setStorageLocationCity } from '@/utils'; 
 | 
import { 
 | 
  getAccountInfoFromAccessToken, 
 | 
  AccountInfo, 
 | 
  setOSSLink, 
 | 
  getUserCertificationFrontStatusAdapter, 
 | 
  LocationUtils, 
 | 
  md5Encrypt, 
 | 
} from '@12333/utils'; 
 | 
import DefaultAvatar from '@/assets/components/icon-default-avatar.png'; 
 | 
import { myClient } from '@/constants/query'; 
 | 
import { globalEventEmitter } from '@12333/hooks'; 
 | 
import * as authServices from '@12333/services/apiV2/auth'; 
 | 
import { AppLocalConfig } from '@/constants'; 
 | 
  
 | 
interface UserState { 
 | 
  userInfo?: Nullable<API.LoginCommandCallback>; 
 | 
  token?: Nullable<string>; 
 | 
  refreshToken?: Nullable<string>; 
 | 
  userDetail?: Nullable<API.GetEnterpriseLoginInfoQueryResult>; 
 | 
  firstGetUserDetail?: boolean; 
 | 
  
 | 
  locationCity?: string; 
 | 
  locationProvince?: string; 
 | 
  firstSetLocation?: boolean; 
 | 
} 
 | 
  
 | 
const goAuthorization = debounce( 
 | 
  () => { 
 | 
    const route = Taro.getCurrentInstance().router; 
 | 
    if (route.path !== RouterPath.authorization) { 
 | 
      Taro.navigateTo({ 
 | 
        url: RouterPath.authorization, 
 | 
      }); 
 | 
    } 
 | 
  }, 
 | 
  300, 
 | 
  { 
 | 
    leading: true, 
 | 
    trailing: false, 
 | 
  } 
 | 
); 
 | 
  
 | 
export const useUserStore = defineStore({ 
 | 
  id: 'app-user', 
 | 
  state: (): UserState => { 
 | 
    const userInfo = getCacheUserInfo(); 
 | 
    const userDetail = getUserDetail(); 
 | 
    const storageLocation = getStorageLocationCity(); 
 | 
  
 | 
    return { 
 | 
      // user info 
 | 
      userInfo: userInfo, 
 | 
      // token 
 | 
      token: userInfo?.accessToken ?? '', 
 | 
  
 | 
      refreshToken: userInfo?.refreshToken ?? '', 
 | 
      userDetail: userDetail, 
 | 
      firstGetUserDetail: true, 
 | 
      locationCity: storageLocation?.city ?? '北京市', 
 | 
      locationProvince: storageLocation?.province ?? '北京', 
 | 
      firstSetLocation: true, 
 | 
    }; 
 | 
  }, 
 | 
  getters: { 
 | 
    cacheRefreshToken: (state) => { 
 | 
      return state.refreshToken; 
 | 
    }, 
 | 
  
 | 
    accountInfo(): Partial<AccountInfo> { 
 | 
      return getAccountInfoFromAccessToken(this.userInfo?.accessToken); 
 | 
    }, 
 | 
  
 | 
    userId: (state) => { 
 | 
      return state.userDetail?.id; 
 | 
    }, 
 | 
  
 | 
    // matchMakingIdentity(state): MatchMakingIdentityEnum { 
 | 
  
 | 
    // }, 
 | 
  }, 
 | 
  actions: { 
 | 
    // 手机号授权Code登录 
 | 
    async getTokenByPhone( 
 | 
      detail: ButtonProps.onGetPhoneNumberEventDetail, 
 | 
      wxMiniAppUserLoginRes: API.LoginCommandCallback 
 | 
    ) { 
 | 
      try { 
 | 
        let res: API.LoginCommandCallback = wxMiniAppUserLoginRes; 
 | 
        if (!wxMiniAppUserLoginRes?.isBindPhoneNumber) { 
 | 
          let bindRes = await authServices.bindWxmpUserInfo({ 
 | 
            encryptedData: detail.encryptedData, 
 | 
            iv: detail.iv, 
 | 
            sessionKey: wxMiniAppUserLoginRes.sessionKey, 
 | 
            accessToken: wxMiniAppUserLoginRes.accessToken, 
 | 
          }); 
 | 
          res.accessToken = bindRes.accessToken; 
 | 
          this.loginSuccess(res); 
 | 
        } 
 | 
        return res; 
 | 
      } catch (error) { 
 | 
        console.log('error3: ', error); 
 | 
      } 
 | 
    }, 
 | 
  
 | 
    // 用户手机验证码登入 
 | 
    async loginByUsername(data: API.SmsLoginCommand) { 
 | 
      let res = await authServices.smsLogin( 
 | 
        { 
 | 
          phoneNumber: data.phoneNumber, 
 | 
          verifyCode: data.verifyCode, 
 | 
          type: AppLocalConfig.userType, 
 | 
          clientType: AppLocalConfig.clientType, 
 | 
        }, 
 | 
        { showLoading: false } 
 | 
      ); 
 | 
  
 | 
      if (res) { 
 | 
        this.loginSuccess(res); 
 | 
      } 
 | 
      return res; 
 | 
    }, 
 | 
  
 | 
    // 用户账号密码登入 
 | 
    async loginByPassword(params: API.PasswordLoginCommand) { 
 | 
      let res = await authServices.passwordLogin( 
 | 
        { 
 | 
          userName: params.userName, 
 | 
          password: params.password, 
 | 
          // password: md5Encrypt(params.password), 
 | 
          type: AppLocalConfig.userType, 
 | 
          clientType: AppLocalConfig.clientType, 
 | 
        }, 
 | 
        { showLoading: false } 
 | 
      ); 
 | 
      if (res) { 
 | 
        this.loginSuccess(res); 
 | 
      } 
 | 
      return res; 
 | 
    }, 
 | 
  
 | 
    async loginSuccess(res: API.IdentityModelTokenCacheItem) { 
 | 
      try { 
 | 
        this.setUserInfoAction(res); 
 | 
        this.setTokenAction(res); 
 | 
        await this.getCurrentUserInfo(); 
 | 
      } catch (error) {} 
 | 
    }, 
 | 
  
 | 
    async wxMiniAppUserLoginFromScan(wxIndentityRes: API.WxMiniAppIndentityInfo, uuid: string) { 
 | 
      // try { 
 | 
      //   let res = await accountServices.wxMiniAppUserLoginFromScan({ 
 | 
      //     uId: uuid, 
 | 
      //     userName: wxIndentityRes.userName, 
 | 
      //     openId: wxIndentityRes.openId, 
 | 
      //   }); 
 | 
      //   this.loginSuccess(res); 
 | 
      //   return res; 
 | 
      // } catch (error) {} 
 | 
    }, 
 | 
  
 | 
    async wxMiniAppPhoneAuthLoginFromScan( 
 | 
      detail: ButtonProps.onGetPhoneNumberEventDetail, 
 | 
      wxIndentityRes: API.WxMiniAppIndentityInfo, 
 | 
      uuid: string 
 | 
    ) { 
 | 
      // try { 
 | 
      //   let res = await accountServices.wxMiniAppPhoneAuthLoginFromScan({ 
 | 
      //     uId: uuid, 
 | 
      //     openId: wxIndentityRes.openId, 
 | 
      //     sessionKey: wxIndentityRes.sessionKey, 
 | 
      //     encryptedData: detail.encryptedData, 
 | 
      //     iv: detail.iv, 
 | 
      //     wxMiniApp: WxMiniAppEnum.C端小程序, 
 | 
      //   }); 
 | 
      //   this.loginSuccess(res); 
 | 
      //   return res; 
 | 
      // } catch (error) {} 
 | 
    }, 
 | 
  
 | 
    async getCurrentUserInfo() { 
 | 
      try { 
 | 
        let res = await authServices.getEnterpriseLoginInfo({}, { showLoading: false }); 
 | 
        if (res) { 
 | 
          // res.frontStatus = getUserCertificationFrontStatusAdapter( 
 | 
          //   res.userCertificationStatus, 
 | 
          //   res.userCertificationAuditStatus 
 | 
          // ); 
 | 
          res.originalAvatar = res.avatar; 
 | 
          res.avatar = res.avatar ? setOSSLink(res.avatar) : DefaultAvatar; 
 | 
          this.setUserDetail(res); 
 | 
          this.firstGetUserDetail = false; 
 | 
        } 
 | 
      } catch (error) {} 
 | 
    }, 
 | 
  
 | 
    setTokenAction(tokenInfo: API.IdentityModelTokenCacheItem) { 
 | 
      this.token = tokenInfo?.accessToken; 
 | 
      this.refreshToken = tokenInfo.refreshToken ?? ''; 
 | 
    }, 
 | 
  
 | 
    setUserInfoAction(info: API.IdentityModelTokenCacheItem) { 
 | 
      this.userInfo = info; 
 | 
      setUserInfo(info); 
 | 
    }, 
 | 
  
 | 
    setUserDetail(detail: API.GetEnterpriseLoginInfoQueryResult) { 
 | 
      this.userDetail = detail; 
 | 
      setUserDetail(detail); 
 | 
    }, 
 | 
  
 | 
    resetState() { 
 | 
      this.userInfo = null; 
 | 
      this.token = ''; 
 | 
      this.refreshToken = ''; 
 | 
      this.userDetail = null; 
 | 
      removeUserInfo(); 
 | 
      removeUserDetail(); 
 | 
    }, 
 | 
  
 | 
    /** 
 | 
     * @description: logout 
 | 
     */ 
 | 
    logout() { 
 | 
      this.resetState(); 
 | 
      // myClient.removeQueries(); 
 | 
      goAuthorization(); 
 | 
    }, 
 | 
  
 | 
    logoutAndToHome() { 
 | 
      this.resetState(); 
 | 
      goHome(); 
 | 
    }, 
 | 
  
 | 
    toLoginPage(targetUrl?: string) { 
 | 
      // 存 登录后跳转目标页 
 | 
      if (targetUrl) { 
 | 
        // tabbar 跳转:不是在具体页面判断用户是否登录 
 | 
      } else { 
 | 
        // 页面里 跳转登录页 存当前页面路径 已供登陆后 
 | 
        const currentPage = useRouter(); 
 | 
  
 | 
        // const params = omit(currentPage.params, '$taroTimestamp'); 
 | 
  
 | 
        console.log(currentPage.params); 
 | 
  
 | 
        // 直接用currentPage.path,params 会丢失 
 | 
  
 | 
        Taro.redirectTo({ 
 | 
          url: `/packageLogin/authLogin/index`, 
 | 
        }); 
 | 
      } 
 | 
    }, 
 | 
  
 | 
    setLocationCity(cityName: string, provinceName: string) { 
 | 
      this.locationCity = cityName; 
 | 
      this.locationProvince = provinceName; 
 | 
      this.firstSetLocation = false; 
 | 
      setStorageLocationCity({ city: cityName, province: provinceName }); 
 | 
      // if (LocationUtils.isProvinceChange(provinceName)) { 
 | 
      //   this.resetState(); 
 | 
      //   myClient.removeQueries(); 
 | 
      //   globalEventEmitter.trigger('logout/refresh'); 
 | 
      //   // myClient.invalidateQueries({ 
 | 
      //   //   queryKey: ['logout/refresh'], 
 | 
      //   // }); 
 | 
      // } 
 | 
      LocationUtils.currentProvinceName = provinceName; 
 | 
    }, 
 | 
  }, 
 | 
}); 
 | 
  
 | 
// Need to be used outside the setup 
 | 
export function useUserStoreWithOut() { 
 | 
  return useUserStore(store); 
 | 
} 
 |