const authApi = require('../../api/auth') const { BRAND_CONFIG } = require('../../utils/config') const PHONE_REGEX = /^1[3-9]\d{9}$/ const LOGIN_PREFERENCE_KEY = 'fingertip_manager_login_preference' function buildSession(data) { const userInfo = data.userInfo || data.user || {} return { ...data, accessToken: data.accessToken || data.token, userInfo, shopName: data.shopName || userInfo.shopName || (data.shop && data.shop.shopName) } } function getSelectableShopIds(session) { const userInfo = session.userInfo || {} if (Array.isArray(userInfo.shopIds)) { return userInfo.shopIds } return Array.isArray(session.shopIds) ? session.shopIds : [] } function getSelectableShopNames(session) { const userInfo = session.userInfo || {} if (Array.isArray(userInfo.shopNames)) { return userInfo.shopNames } return Array.isArray(session.shopNames) ? session.shopNames : [] } function buildShopOptions(session) { const shopIds = getSelectableShopIds(session) const shopNames = getSelectableShopNames(session) return shopIds.map((shopId, index) => ({ id: shopId, name: shopNames[index] || `店铺 ${shopId}` })) } function buildShopOptionsFromSelection(selection) { const shops = selection && Array.isArray(selection.shops) ? selection.shops : [] return shops.map(shop => ({ id: shop.id, name: shop.shopName || shop.name || `店铺 ${shop.id}`, description: selection && selection.message ? selection.message : '' })) } function isShopSelectionRequiredError(error) { const message = error && error.message ? error.message : '' return message.indexOf('选择店铺') !== -1 || message.indexOf('请选择店铺') !== -1 || message.indexOf('请选择登录店铺') !== -1 } function assertShopSession(session) { const userInfo = session.userInfo || {} if (!userInfo.shopId) { throw new Error('请选择店铺后再进入管理师端') } return session } function getLoginPreference() { try { return wx.getStorageSync(LOGIN_PREFERENCE_KEY) || {} } catch (error) { return {} } } function setLoginPreference(preference) { wx.setStorageSync(LOGIN_PREFERENCE_KEY, preference || {}) } function clearLoginPreference() { wx.removeStorageSync(LOGIN_PREFERENCE_KEY) } Page({ data: { loginMode: 'phone', form: { account: '', password: '', phone: '', code: '' }, loading: false, codeLoading: false, countdown: 0, countdownTimer: null, agreementAccepted: false, agreementLoading: false, agreementError: '', agreementModalVisible: false, selectedAgreement: null, rememberMe: false, agreements: [], appName: BRAND_CONFIG.appName, shopSelectVisible: false, shopSelectMode: '', shopOptions: [], switchingShop: false, wechatLoginTicket: '' }, onLoad() { const preference = getLoginPreference() if (preference.rememberMe) { this.setData({ // 记住账号不代表默认使用密码登录,工作台优先引导手机号验证码登录。 loginMode: 'phone', rememberMe: true, 'form.account': preference.account || '', 'form.phone': preference.phone || '' }) } this.loadAgreements() }, onInput(event) { const field = event.currentTarget.dataset.field const value = field === 'phone' ? String(event.detail.value || '').replace(/\D/g, '').slice(0, 11) : event.detail.value this.setData({ [`form.${field}`]: value }) }, switchLoginMode(event) { const loginMode = event.currentTarget.dataset.mode if (loginMode === this.data.loginMode) { return } this.setData({ loginMode }) }, async sendLoginCode() { if (!this.ensureAgreementAccepted()) { return } const phone = String(this.data.form.phone || '').trim() if (!PHONE_REGEX.test(phone)) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }) return } if (this.data.codeLoading || this.data.countdown > 0) { return } this.setData({ codeLoading: true }) try { await authApi.sendLoginCode(phone) wx.showToast({ title: '验证码已发送' }) this.startCountdown() } catch (error) { wx.showToast({ title: error.message || '验证码发送失败', icon: 'none' }) } finally { this.setData({ codeLoading: false }) } }, async loadAgreements() { if (this.data.agreements.length) { return this.data.agreements } if (this.data.agreementLoading) { return this.data.agreements } this.setData({ agreementLoading: true, agreementError: '' }) try { const agreements = await authApi.getCurrentAgreements() const normalizedAgreements = Array.isArray(agreements) ? agreements : [] this.setData({ agreements: normalizedAgreements }) return normalizedAgreements } catch (error) { const agreementError = error.message || '协议内容加载失败,请稍后重试' this.setData({ agreementError }) return [] } finally { this.setData({ agreementLoading: false }) } }, toggleAgreement() { this.setData({ agreementAccepted: !this.data.agreementAccepted }) }, async openAgreement(event) { const type = event.currentTarget.dataset.type const agreements = await this.loadAgreements() const selectedAgreement = agreements.find(item => item.agreementType === type) if (!selectedAgreement) { wx.showToast({ title: this.data.agreementError || '协议内容暂不可用', icon: 'none' }) return } this.setData({ selectedAgreement, agreementModalVisible: true }) }, closeAgreementModal() { this.setData({ agreementModalVisible: false, selectedAgreement: null }) }, stopTap() { }, toggleRememberMe() { const rememberMe = !this.data.rememberMe this.setData({ rememberMe }) if (!rememberMe) { clearLoginPreference() } }, saveLoginPreference() { if (!this.data.rememberMe) { clearLoginPreference() return } const form = this.data.form setLoginPreference({ rememberMe: true, loginMode: this.data.loginMode, account: String(form.account || '').trim(), phone: String(form.phone || '').trim() }) }, buildAgreementPayload() { const agreementVersions = {} ;(this.data.agreements || []).forEach(item => { if (item && item.agreementType && item.version) { agreementVersions[item.agreementType] = item.version } }) return { agreementAccepted: !!this.data.agreementAccepted, agreementVersions, clientType: 'WECHAT_MINI' } }, ensureAgreementAccepted() { if (!this.data.agreementAccepted) { wx.showToast({ title: '请先阅读并同意用户协议和隐私政策', icon: 'none' }) return false } const versions = this.buildAgreementPayload().agreementVersions if (!versions.USER_TERMS || !versions.PRIVACY_POLICY) { wx.showToast({ title: this.data.agreementError || '协议版本加载中,请稍后再试', icon: 'none' }) return false } return true }, async resolveLoginSession(data) { const session = buildSession(data) const userInfo = session.userInfo || {} if (userInfo.shopId) { return session } const shopOptions = buildShopOptions(session) if (!shopOptions.length) { throw new Error('当前账号没有可用店铺,无法进入管理师端') } if (shopOptions.length === 1) { return this.loginForShop(shopOptions[0].id) } this.setData({ shopOptions, shopSelectVisible: true, shopSelectMode: 'login' }) return null }, openRegistrationFlow(data) { const ticket = String(data.registrationTicket || '').trim() const status = data.registrationStatus if (status === 'PENDING_ADMIN' || status === 'PENDING_MANAGER') { wx.showToast({ title: status === 'PENDING_ADMIN' ? '管理员审核中' : '店长审核中', icon: 'none', duration: 2500 }) return } if (!ticket) { wx.showToast({ title: data.registrationRejectReason || '该手机号需要先完成身份注册', icon: 'none', duration: 2200 }) return } wx.showToast({ title: '手机号已验证,请完成身份注册', icon: 'none', duration: 1600 }) const query = [ `registrationTicket=${encodeURIComponent(ticket)}`, `phone=${encodeURIComponent(data.phone || this.data.form.phone || '')}`, data.wxCode ? `wxCode=${encodeURIComponent(data.wxCode)}` : '', data.registrationApplicationId ? `applicationId=${encodeURIComponent(data.registrationApplicationId)}` : '' ].filter(Boolean).join('&') setTimeout(() => wx.navigateTo({ url: `/pages/register/index?${query}` }), 700) }, buildLoginRequestData(shopId) { const form = this.data.form if (this.data.loginMode === 'phone') { return { phone: String(form.phone || '').trim(), verificationCode: String(form.code || '').trim(), rememberMe: !!this.data.rememberMe, ...this.buildAgreementPayload(), ...(shopId ? { shopId } : {}) } } return { account: form.account, password: form.password, rememberMe: !!this.data.rememberMe, ...this.buildAgreementPayload(), ...(shopId ? { shopId } : {}) } }, requestLogin(shopId) { const data = this.buildLoginRequestData(shopId) return this.data.loginMode === 'phone' ? authApi.phoneLogin(data) : authApi.login(data) }, async loginForShop(shopId) { return assertShopSession(buildSession(await this.requestLogin(shopId))) }, async loadLoginShopOptions() { const form = this.data.form const selection = this.data.loginMode === 'phone' ? await authApi.getPhoneLoginShops(String(form.phone || '').trim()) : await authApi.getLoginShops(String(form.account || '').trim()) const shopOptions = buildShopOptionsFromSelection(selection) if (!shopOptions.length) { throw new Error((selection && selection.message) || '当前账号没有可用店铺,无法进入管理师端') } return shopOptions }, async openLoginShopSelector() { const shopOptions = await this.loadLoginShopOptions() if (shopOptions.length === 1) { await this.loginWithSelectedShop(shopOptions[0].id) return } this.setData({ shopOptions, shopSelectVisible: true, shopSelectMode: 'login' }) }, closeShopSelector() { this.setData({ shopOptions: [], shopSelectMode: '', shopSelectVisible: false }) }, async tryOpenLoginShopSelector() { try { await this.openLoginShopSelector() return true } catch (error) { return false } }, async selectLoginShop(event) { if (this.data.switchingShop) { return } const shopId = event.currentTarget.dataset.id if (!shopId) { wx.showToast({ title: '请选择店铺', icon: 'none' }) return } this.setData({ switchingShop: true }) try { if (this.data.shopSelectMode === 'login') { await this.loginWithSelectedShop(shopId) } else if (this.data.shopSelectMode === 'wechat') { await this.loginWithWechatSelectedShop(shopId) } else { await this.switchSelectedShop(shopId) } } catch (error) { wx.showToast({ title: error.message || '进入店铺失败', icon: 'none' }) } finally { this.setData({ switchingShop: false }) } }, async loginWithSelectedShop(shopId) { const session = await this.loginForShop(shopId) const app = getApp() app.setSession(session) this.saveLoginPreference() this.closeShopSelector() wx.reLaunch({ url: '/pages/planning/index' }) }, async switchSelectedShop(shopId) { const session = buildSession(await authApi.switchShop(shopId)) const app = getApp() app.setSession(session) this.closeShopSelector() wx.reLaunch({ url: '/pages/planning/index' }) }, async loginWithWechatSelectedShop(shopId) { const result = await authApi.wechatConfirmLogin({ ticket: this.data.wechatLoginTicket, shopId, ...this.buildAgreementPayload() }) if (result.status !== 'SUCCESS' || !result.accessToken) { throw new Error(result.message || '进入店铺失败') } getApp().setSession(result) this.closeShopSelector() wx.reLaunch({ url: '/pages/planning/index' }) }, startCountdown() { if (this.data.countdownTimer) { clearInterval(this.data.countdownTimer) } this.setData({ countdown: 60 }) const timer = setInterval(() => { const next = this.data.countdown - 1 if (next <= 0) { clearInterval(timer) this.setData({ countdown: 0, countdownTimer: null }) return } this.setData({ countdown: next }) }, 1000) this.setData({ countdownTimer: timer }) }, onUnload() { if (this.data.countdownTimer) { clearInterval(this.data.countdownTimer) } }, async submit() { if (this.data.loading) { return } const form = this.data.form if (this.data.loginMode === 'password' && (!form.account || !form.password)) { wx.showToast({ title: '请填写账号和密码', icon: 'none' }) return } if (this.data.loginMode === 'phone' && (!PHONE_REGEX.test(String(form.phone || '').trim()) || !String(form.code || '').trim())) { wx.showToast({ title: '请输入正确手机号和验证码', icon: 'none' }) return } await this.loadAgreements() if (!this.ensureAgreementAccepted()) { return } this.setData({ loading: true }) try { const app = getApp() const data = await this.requestLogin('') if (this.data.loginMode === 'phone' && data && data.registrationRequired) { this.openRegistrationFlow(data) return } const session = await this.resolveLoginSession(data) if (!session) { return } app.setSession(assertShopSession(session)) this.saveLoginPreference() wx.reLaunch({ url: '/pages/planning/index' }) } catch (error) { if (String(error.message || '').indexOf('禁用') !== -1) { await this.showRegistrationStatus() return } if (isShopSelectionRequiredError(error)) { try { if (!this.data.shopSelectVisible) { await this.openLoginShopSelector() } } catch (shopError) { wx.showToast({ title: shopError.message || '店铺列表加载失败', icon: 'none' }) } return } wx.showToast({ title: error.message || '登录失败', icon: 'none' }) } finally { this.setData({ loading: false }) } }, async showRegistrationStatus() { try { const phone = this.data.loginMode === 'phone' ? this.data.form.phone : this.data.form.account const status = await authApi.getRegistrationStatus(String(phone || '').trim()) const statusText = { PENDING_ADMIN: '管理员审核中', PENDING_MANAGER: '店长审核中', REJECTED: `申请已驳回:${status.rejectReason || '请修改资料后重新提交'}`, APPROVED: '账号已审核,请稍后重试登录' }[status.status] || '账号暂不可用' wx.showToast({ title: statusText, icon: 'none', duration: 3000 }) } catch (statusError) { wx.showToast({ title: statusError.message || '账号已被禁用', icon: 'none' }) } }, async getWechatCode() { const result = await new Promise((resolve, reject) => wx.login({ success: resolve, fail: reject })) return result.code }, goRegister(wxCode) { const query = wxCode ? `?wxCode=${encodeURIComponent(wxCode)}` : '' wx.navigateTo({ url: `/pages/register/index${query}` }) }, async wechatLogin() { try { const loginResult = await new Promise((resolve, reject) => { wx.login({ success: resolve, fail: reject }) }) const result = await authApi.wechatAutoLogin(loginResult.code) if (result.status === 'NEED_MANUAL_LOGIN') { wx.showToast({ title: '新账号请先完成手机号注册和身份审核', icon: 'none', duration: 2500 }) const wxCode = await this.getWechatCode() setTimeout(() => this.goRegister(wxCode), 900) return } if (result.status !== 'SUCCESS' || !result.accessToken) { throw new Error(result.message || '微信登录暂不可用') } getApp().setSession(result) wx.reLaunch({ url: '/pages/planning/index' }) } catch (error) { wx.showToast({ title: error.message || '微信快捷登录失败', icon: 'none' }) } }, async wechatPhoneLogin(event) { if (this.data.loading || !this.ensureAgreementAccepted()) { return } const phoneCode = event && event.detail && event.detail.code if (!phoneCode) { wx.showToast({ title: '需要授权手机号后才能登录', icon: 'none' }) return } this.setData({ loading: true }) try { const wxCode = await this.getWechatCode() const result = await authApi.wechatPhoneLogin({ wxCode, phoneCode, ...this.buildAgreementPayload() }) if (result.registrationRequired) { this.openRegistrationFlow({ ...result, wxCode }) return } if (result.status === 'SELECT_SHOP') { this.setData({ shopOptions: buildShopOptionsFromSelection(result), shopSelectVisible: true, shopSelectMode: 'wechat', wechatLoginTicket: result.ticket, switchingShop: false }) return } if (result.status !== 'SUCCESS' || !result.accessToken) { throw new Error(result.message || '微信手机号登录暂不可用') } getApp().setSession(result) wx.reLaunch({ url: '/pages/planning/index' }) } catch (error) { wx.showToast({ title: error.message || '微信手机号登录失败', icon: 'none' }) } finally { this.setData({ loading: false }) } } })