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 }, onLoad() { const preference = getLoginPreference() if (preference.rememberMe) { this.setData({ loginMode: preference.loginMode === 'password' ? 'password' : 'phone', rememberMe: true, 'form.account': preference.account || '', 'form.phone': preference.phone || '' }) } this.loadAgreements() }, onInput(event) { const field = event.currentTarget.dataset.field this.setData({ [`form.${field}`]: event.detail.value }) }, switchLoginMode(event) { const loginMode = event.currentTarget.dataset.mode if (loginMode === this.data.loginMode) { return } this.setData({ loginMode }) }, async sendLoginCode() { 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 }, 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 { 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' }) }, 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('') const session = await this.resolveLoginSession(data) if (!session) { return } app.setSession(assertShopSession(session)) this.saveLoginPreference() wx.reLaunch({ url: '/pages/planning/index' }) } catch (error) { 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 }) } }, goRegister() { wx.navigateTo({ url: '/pages/register/index' }) }, wechatLogin() { wx.showToast({ title: '请先使用账号登录', icon: 'none' }) } })