import { Apis } from '@/gen/Apis' import { defineStore } from 'pinia' import { ref } from 'vue' import { getApiLoading } from '../libraries/apiLoading' const wxAppId = 'wx31500e871924b903' //小程序id type DataType = { user?: { id: number phone?: string name?: string } orgs?: { id?: number; name?: string }[] selectedOrg?: { id?: number; name?: string; is_show_procedure?: number } work_info?: { session_key: string; openid: string } selected_house?: { id?: string; full_name?: string; asset_projects_id?: string } environment?: string house_register?: boolean house_occupant?: boolean is_house_exist?: number config?: { companyConfig?: { config_value?: { color?: string pageColor?: string logo?: { url?: string }[] } } } } export const useWeAppAuthStore = defineStore('we_app_auth', () => { const loading = ref(true) const hasError = ref(false) const is_house_exist = ref(0) const data = ref({ user: { id: 0, name: '' }, work_info: { session_key: '', openid: '' }, selected_house: {}, environment: '', house_occupant: false, house_register: false, is_house_exist: 0, config: {} }) function login(app: any) { uni.login({ provider: 'weixin', //使用微信登录 success: function (loginRes) { console.log(loginRes) getWXToken(app, loginRes.code) } }) } const getWXToken = (app: any, code: string) => { Apis.Login.Auth.Login({ code: code, app_id: wxAppId }) .then(res => { console.log('登录', res?.data) data.value.user = res.data?.user data.value.selected_house = res.data?.selected_house data.value.config = res.data?.config loading.value = false uni.setStorageSync(import.meta.env.VITE_ACCESS_TOKEN_KEY, res?.data?.token?.token) if (data.value.user) { getIsHouseExist() } app?.appContext.config.globalProperties.$isResolve() }) .catch(() => { loading.value = false hasError.value = true }) } const getIsHouseExist = () => { Apis.Archive.HouseOccupants.GetCustomerHouseIsExist().then(res => { data.value.house_occupant = res.data?.house_occupant || false data.value.house_register = res.data?.house_register || false data.value.is_house_exist = is_house_exist.value + 1 }) } function me(fun?: () => void) { getApiLoading(Apis.Login.Auth.Me, {}).then(res => { data.value.user = res.data.user data.value.config = res.data?.config data.value.selected_house = res.data?.selected_house console.log('me', res.data) loading.value = false hasError.value = false if (data.value.user) { getIsHouseExist() } return fun?.() }) } //小程序快捷绑定 const handleUserLogin = async (from_data: { code?: string phone?: string phone_validate_code?: string }) => { getApiLoading(Apis.Login.Auth.BindPhoneNumber, { app_id: wxAppId, ...from_data }).then(res => { me(() => { uni.navigateBack({ delta: 1 }) }) }) } return { loading, hasError, data, login, me, handleUserLogin, getIsHouseExist } })