longz
2026-06-29 9d4cbff7464ebfd7803c2ce53ded49d0f73fe011
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
<script setup lang="ts">
import type { ApiError } from '@/api/core/handlers'
import { fetchMiniMe, loginByWx } from '@/api/auth'
import { useMiniAuthStore } from '@/store/auth'
import { normalizeLoginProfile, normalizeMeProfile, normalizeProfileDisplayName } from '@/types/auth'
 
definePage({
  name: 'login',
  layout: 'default',
  style: {
    navigationBarTitleText: '登录',
    navigationBarBackgroundColor: '#FFFFFF',
    navigationBarTextStyle: 'black',
  },
})
 
const router = useRouter()
const authStore = useMiniAuthStore()
const submitting = ref(false)
const needPhoneAuthorize = ref(false)
const EMPLOYEE_SUBSCRIBE_TEMPLATE_IDS = [
  'QlNwG99WXWztRDgtlLcE0fHxfY2VwaX8PRMrwGpEync',
  'Wip0ODJgybZpeFpcvev_0GK1wQXEqZw-LHOjS-UyDLw',
]
const MINI_PHONE_AUTH_REQUIRED = 10008
 
function getApiErrorCode(error: unknown) {
  return typeof error === 'object' && error != null && 'code' in error
    ? Number((error as ApiError).code)
    : NaN
}
 
async function getWxLoginCode() {
  // #ifdef MP-WEIXIN
  return await new Promise<string>((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: (res) => {
        if (res.code) {
          resolve(res.code)
          return
        }
        reject(new Error('获取微信登录凭证失败'))
      },
      fail: () => reject(new Error('获取微信登录凭证失败')),
    })
  })
  // #endif
  // #ifndef MP-WEIXIN
  throw new Error('当前环境暂不支持微信授权登录')
  // #endif
}
 
async function finishLogin(loginData: Awaited<ReturnType<typeof loginByWx>>) {
  authStore.setSession({
    token: loginData.token,
    profile: normalizeLoginProfile(loginData),
  })
 
  try {
    const profile = await fetchMiniMe(loginData.token)
    authStore.setProfile(normalizeMeProfile(profile))
  }
  catch (error) {
    console.warn('load mini profile failed after login', error)
  }
 
  await requestEmployeeSubscribeAuthorization()
}
 
function shouldForceEditProfile() {
  return !normalizeProfileDisplayName(authStore.profile?.displayName)
}
 
async function openProfileEditorIfNeeded() {
  if (!shouldForceEditProfile()) {
    return false
  }
  uni.showToast({
    title: '请先完善个人资料',
    icon: 'none',
  })
  router.replaceAll({ name: 'profile' })
  return true
}
 
async function handleLogin() {
  if (submitting.value) {
    return
  }
 
  submitting.value = true
  try {
    const wxCode = await getWxLoginCode()
    const loginData = await loginByWx({ wxCode })
    needPhoneAuthorize.value = false
    await finishLogin(loginData)
    if (await openProfileEditorIfNeeded()) {
      return
    }
    uni.showToast({
      title: '登录成功',
      icon: 'success',
    })
    router.replaceAll({ name: 'home' })
  }
  catch (error) {
    if (getApiErrorCode(error) === MINI_PHONE_AUTH_REQUIRED) {
      needPhoneAuthorize.value = true
      uni.showToast({
        title: '请授权手机号完成登录',
        icon: 'none',
      })
    }
    else {
      uni.showToast({
        title: error instanceof Error ? error.message : '登录失败',
        icon: 'none',
      })
    }
  }
  finally {
    submitting.value = false
  }
}
 
async function handlePhoneAuthorize(event: any) {
  if (submitting.value) {
    return
  }
  const phoneCode = event?.detail?.code
  if (!phoneCode) {
    uni.showToast({
      title: '未获取到手机号授权',
      icon: 'none',
    })
    return
  }
  submitting.value = true
  try {
    const wxCode = await getWxLoginCode()
    const loginData = await loginByWx({ wxCode, phoneCode })
    needPhoneAuthorize.value = false
    await finishLogin(loginData)
    if (await openProfileEditorIfNeeded()) {
      return
    }
    uni.showToast({
      title: '登录成功',
      icon: 'success',
    })
    router.replaceAll({ name: 'home' })
  }
  catch (error) {
    uni.showToast({
      title: error instanceof Error ? error.message : '登录失败',
      icon: 'none',
    })
  }
  finally {
    submitting.value = false
  }
}
 
async function requestEmployeeSubscribeAuthorization() {
  if (authStore.profile?.userType !== 'EMPLOYEE') {
    return
  }
  // #ifdef MP-WEIXIN
  try {
    await new Promise<void>((resolve) => {
      uni.requestSubscribeMessage({
        tmplIds: EMPLOYEE_SUBSCRIBE_TEMPLATE_IDS,
        complete: () => resolve(),
      })
    })
  }
  catch (error) {
    console.warn('request employee subscribe message failed', error)
  }
  // #endif
}
</script>
 
<template>
  <view class="login-page">
    <view class="login-card">
      <text class="login-title">
        红宇精工访客预约
      </text>
      <text class="login-subtitle">
        {{ needPhoneAuthorize ? '首次登录需授权手机号完成身份识别' : '点击下方按钮使用微信授权登录' }}
      </text>
 
      <button class="login-button" :disabled="submitting" @click="handleLogin">
        {{ submitting ? '登录中...' : '微信登录' }}
      </button>
 
      <!-- #ifdef MP-WEIXIN -->
      <button
        v-if="needPhoneAuthorize"
        class="login-button login-button-secondary"
        :disabled="submitting"
        open-type="getPhoneNumber"
        @getphonenumber="handlePhoneAuthorize"
      >
        {{ submitting ? '授权中...' : '授权手机号登录' }}
      </button>
      <!-- #endif -->
    </view>
  </view>
</template>
 
<style scoped>
.login-page {
  min-height: 100vh;
  padding: 120rpx 32rpx 32rpx;
  box-sizing: border-box;
  background: linear-gradient(180deg, #e9f2ff 0%, #f7fbff 40%, #ffffff 100%);
}
 
.login-card {
  padding: 56rpx 40rpx;
  border-radius: 32rpx;
  background: #ffffff;
  box-shadow: 0 16rpx 48rpx rgba(6, 47, 108, 0.12);
}
 
.login-title {
  display: block;
  font-size: 44rpx;
  font-weight: 600;
  color: #1a1a1a;
}
 
.login-subtitle {
  display: block;
  margin-top: 20rpx;
  font-size: 28rpx;
  line-height: 1.6;
  color: #666666;
}
 
.login-button {
  margin-top: 56rpx;
  height: 88rpx;
  line-height: 88rpx;
  border: none;
  border-radius: 44rpx;
  background: #0c6fff;
  color: #ffffff;
  font-size: 32rpx;
}
 
.login-button[disabled] {
  opacity: 0.7;
}
 
.login-button-secondary {
  margin-top: 24rpx;
  background: #19be6b;
}
</style>