const productApi = require('../../api/product') const tagApi = require('../../api/tag') const userApi = require('../../api/user') const couponApi = require('../../api/coupon') const shopApi = require('../../api/shop') const navigation = require('../../utils/navigation') const format = require('../../utils/format') const cache = require('../../utils/cache') const upload = require('../../utils/upload') const { getTempRecord, clearTempRecord } = require('../../utils/storage') const { getDraftValue, clearDraft, scheduleDraftSave, clearDraftTimer } = require('../../utils/form-draft') const { markDirty } = require('../../utils/page-state') const { CACHE_TTL } = require('../../utils/config') const DRAFT_KEY = 'admin-product-form' function normalizeId(value) { return value === undefined || value === null ? '' : String(value) } function buildCheckableList(list, selectedIds, labelKey) { return (Array.isArray(list) ? list : []).map(item => ({ ...item, valueId: normalizeId(item.id), labelText: item[labelKey], checked: selectedIds.includes(normalizeId(item.id)) })) } function syncSelectedIds(selectedIds, list) { const availableIds = new Set((Array.isArray(list) ? list : []).map(item => normalizeId(item.id))) return (Array.isArray(selectedIds) ? selectedIds : []).filter(id => availableIds.has(normalizeId(id))) } Page({ data: { mode: 'create', productId: '', shops: [], shopIndex: 0, shopLabel: '', tags: [], artists: [], coupons: [], uploading: false, uploadProgress: 0, form: { title: '', description: '', price: '', approximateDuration: '', likeCount: '', collectCount: '', imageFileIds: [], shopId: '' } }, onLoad(options) { const mode = options && options.mode ? options.mode : 'create' const currentProduct = getTempRecord('currentProduct', null) const draft = getDraftValue(DRAFT_KEY, null) this.setData({ mode, productId: options && options.id ? options.id : '' }) this._selectedTagIds = [] this._selectedArtistIds = [] this._selectedCouponIds = [] if (mode === 'edit' && currentProduct) { this._selectedTagIds = format.splitCsv(currentProduct.tags) this._selectedArtistIds = format.splitCsv(currentProduct.bookableArtists) this._selectedCouponIds = format.splitCsv(currentProduct.availableCoupons) this._initialShopId = currentProduct.shopId this.setData({ form: { title: currentProduct.title || '', description: currentProduct.description || '', price: currentProduct.price || '', approximateDuration: currentProduct.approximateDuration || '', likeCount: currentProduct.likeCount || '', collectCount: currentProduct.collectCount || '', imageFileIds: format.splitCsv(currentProduct.imageFileIds), shopId: currentProduct.shopId || '' } }) } if (draft && draft.mode === mode) { this._selectedTagIds = Array.isArray(draft.selectedTagIds) ? draft.selectedTagIds : this._selectedTagIds this._selectedArtistIds = Array.isArray(draft.selectedArtistIds) ? draft.selectedArtistIds : this._selectedArtistIds this._selectedCouponIds = Array.isArray(draft.selectedCouponIds) ? draft.selectedCouponIds : this._selectedCouponIds this._initialShopId = draft.form && draft.form.shopId ? draft.form.shopId : this._initialShopId this.setData({ form: { ...this.data.form, ...(draft.form || {}) } }) } this.loadDependencies() }, onUnload() { clearTempRecord('currentProduct') clearDraftTimer(this) }, scheduleProductDraft() { scheduleDraftSave(this, DRAFT_KEY, () => ({ mode: this.data.mode, form: { ...this.data.form, imageFileIds: this.data.form.imageFileIds.slice() }, selectedTagIds: this._selectedTagIds.slice(), selectedArtistIds: this._selectedArtistIds.slice(), selectedCouponIds: this._selectedCouponIds.slice() })) }, async loadDependencies() { const app = getApp() const currentShop = app.globalData.currentShop const operator = app.globalData.userInfo || {} try { const shopList = await cache.remember('admin:shops:all', CACHE_TTL.dict, () => shopApi.listAllShops()) let shops = Array.isArray(shopList) ? shopList : [] if (Number(operator.type) !== 4 && currentShop) { shops = shops.filter(item => normalizeId(item.id) === normalizeId(currentShop.id)) } let shopIndex = 0 if (this._initialShopId) { const index = shops.findIndex(item => normalizeId(item.id) === normalizeId(this._initialShopId)) if (index >= 0) { shopIndex = index } } const selectedShop = shops[shopIndex] this.setData({ shops, shopIndex, shopLabel: selectedShop ? selectedShop.shopName : '', 'form.shopId': selectedShop ? selectedShop.id : '' }) await this.loadShopScopedOptions(selectedShop ? selectedShop.id : '') } catch (error) { wx.showToast({ title: error.message || '初始化作品表单失败', icon: 'none' }) } }, async loadShopScopedOptions(shopId) { if (!normalizeId(shopId)) { this._selectedTagIds = [] this._selectedArtistIds = [] this._selectedCouponIds = [] this.setData({ tags: [], artists: [], coupons: [] }) return } try { const [tagList, artistList, couponList] = await Promise.all([ tagApi.listTagsByShopId(shopId), userApi.listArtists(shopId), couponApi.listAllCoupons(shopId) ]) this._selectedTagIds = syncSelectedIds(this._selectedTagIds, tagList) this._selectedArtistIds = syncSelectedIds(this._selectedArtistIds, artistList) this._selectedCouponIds = syncSelectedIds(this._selectedCouponIds, couponList) this.setData({ tags: buildCheckableList(tagList, this._selectedTagIds, 'tagName'), artists: buildCheckableList(artistList, this._selectedArtistIds, 'nickname'), coupons: buildCheckableList(couponList, this._selectedCouponIds, 'couponName') }) this.scheduleProductDraft() } catch (error) { this.setData({ tags: [], artists: [], coupons: [] }) wx.showToast({ title: error.message || '店铺关联数据加载失败', icon: 'none' }) } }, handleInputChange(event) { const field = event.currentTarget.dataset.field this.setData({ [`form.${field}`]: event.detail.value }) this.scheduleProductDraft() }, handleShopChange(event) { const shopIndex = Number(event.detail.value) const selectedShop = this.data.shops[shopIndex] this.setData({ shopIndex, shopLabel: selectedShop ? selectedShop.shopName : '', 'form.shopId': selectedShop ? selectedShop.id : '' }) this.loadShopScopedOptions(selectedShop ? selectedShop.id : '') this.scheduleProductDraft() }, handleTagChange(event) { this._selectedTagIds = event.detail.value || [] this.setData({ tags: this.data.tags.map(item => ({ ...item, checked: this._selectedTagIds.includes(item.valueId) })) }) this.scheduleProductDraft() }, handleArtistChange(event) { this._selectedArtistIds = event.detail.value || [] this.setData({ artists: this.data.artists.map(item => ({ ...item, checked: this._selectedArtistIds.includes(item.valueId) })) }) this.scheduleProductDraft() }, handleCouponChange(event) { this._selectedCouponIds = event.detail.value || [] this.setData({ coupons: this.data.coupons.map(item => ({ ...item, checked: this._selectedCouponIds.includes(item.valueId) })) }) this.scheduleProductDraft() }, async handleUploadImages() { try { const files = await upload.chooseImageFiles({ count: 9 }) this.setData({ uploading: true, uploadProgress: 0 }) const result = await upload.uploadImageFiles({ files, scene: 'admin-product-image', onProgress: progress => { this.setData({ uploadProgress: Math.round(progress) }) } }) this.setData({ 'form.imageFileIds': this.data.form.imageFileIds.concat(result.map(item => String(item.id))) }) this.scheduleProductDraft() } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) } finally { this.setData({ uploading: false }) } }, async handleSubmit() { if (!this.data.form.title) { wx.showToast({ title: '请输入作品标题', icon: 'none' }) return } if (!this.data.form.shopId) { wx.showToast({ title: '请选择所属店铺', icon: 'none' }) return } if (!this.data.form.price) { wx.showToast({ title: '请输入作品价格', icon: 'none' }) return } const payload = { shopId: this.data.form.shopId || undefined, title: this.data.form.title, description: this.data.form.description || undefined, imageFileIds: this.data.form.imageFileIds.join(',') || undefined, price: Number(this.data.form.price), tags: this._selectedTagIds.join(',') || undefined, likeCount: this.data.form.likeCount ? Number(this.data.form.likeCount) : undefined, collectCount: this.data.form.collectCount ? Number(this.data.form.collectCount) : undefined, approximateDuration: this.data.form.approximateDuration || undefined, bookableArtists: this._selectedArtistIds.join(',') || undefined, availableCoupons: this._selectedCouponIds.join(',') || undefined } try { if (this.data.mode === 'edit') { await productApi.updateProduct(this.data.productId, payload) } else { await productApi.createProduct(payload) } clearDraft(DRAFT_KEY) markDirty('admin-products') wx.showToast({ title: this.data.mode === 'edit' ? '作品已更新' : '作品已创建', icon: 'none' }) navigation.goBack('/pages/products/index') } catch (error) { wx.showToast({ title: error.message || '保存失败', icon: 'none' }) } } })