Files
JayuCloud/YumiNail-Admin-Program/pages/artist-form/index.js
T

329 lines
9.3 KiB
JavaScript

const artistApi = require('../../api/nail-artist')
const userApi = require('../../api/user')
const tagApi = require('../../api/tag')
const productApi = require('../../api/product')
const shopApi = require('../../api/shop')
const navigation = require('../../utils/navigation')
const format = require('../../utils/format')
const { getTempRecord, clearTempRecord } = require('../../utils/storage')
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)))
}
function filterProductsByShop(products, shopId) {
const targetShopId = normalizeId(shopId)
if (!targetShopId) {
return []
}
return (Array.isArray(products) ? products : []).filter(item => normalizeId(item.shopId) === targetShopId)
}
Page({
data: {
mode: 'create',
userId: '',
shops: [],
shopIndex: 0,
shopLabel: '',
statusOptions: ['营业中', '休息中'],
statusIndex: 0,
userForm: {
nickname: '',
account: '',
phone: '',
password: '',
signature: ''
},
artistForm: {
identity: '',
experience: '',
rating: '',
portfolioText: ''
},
tags: [],
products: []
},
onLoad(options) {
const mode = options && options.mode ? options.mode : 'create'
const currentArtist = getTempRecord('currentArtist', null)
this.setData({
mode,
userId: options && options.userId ? options.userId : ''
})
this._selectedTagIds = []
this._selectedProductIds = []
this._allProducts = []
if (mode === 'edit' && currentArtist) {
this._selectedTagIds = format.splitCsv(currentArtist.skills)
this._selectedProductIds = format.splitCsv(currentArtist.portfolio)
this._initialShopId = currentArtist.shopId
this.setData({
artistForm: {
identity: currentArtist.identity || '',
experience: currentArtist.experience || '',
rating: currentArtist.rating || '',
portfolioText: ''
},
userForm: {
nickname: currentArtist.nickname || '',
account: '',
phone: '',
password: '',
signature: currentArtist.signature || ''
},
statusIndex: Number(currentArtist.status) === 0 ? 1 : 0
})
}
this.loadDependencies()
},
onUnload() {
clearTempRecord('currentArtist')
},
async loadDependencies() {
const app = getApp()
const currentShop = app.globalData.currentShop
const operator = app.globalData.userInfo || {}
try {
const [shops, products, users] = await Promise.all([
shopApi.listAllShops(),
productApi.listAllProducts(),
userApi.listAllUsers()
])
let availableShops = Array.isArray(shops) ? shops : []
if (Number(operator.type) !== 4 && currentShop) {
availableShops = availableShops.filter(item => normalizeId(item.id) === normalizeId(currentShop.id))
}
let shopIndex = 0
if (this._initialShopId) {
const index = availableShops.findIndex(item => normalizeId(item.id) === normalizeId(this._initialShopId))
if (index >= 0) {
shopIndex = index
}
}
const selectedShop = availableShops[shopIndex]
this._allProducts = Array.isArray(products) ? products : []
if (this.data.mode === 'edit') {
const userRecord = (Array.isArray(users) ? users : []).find(item => normalizeId(item.id) === normalizeId(this.data.userId))
if (userRecord) {
this.setData({
userForm: {
nickname: userRecord.nickname || '',
account: userRecord.account || '',
phone: userRecord.phone || '',
password: '',
signature: userRecord.signature || ''
}
})
}
}
this.setData({
shops: availableShops,
shopIndex,
shopLabel: selectedShop ? selectedShop.shopName : ''
})
await this.loadShopScopedOptions(selectedShop ? selectedShop.id : '')
} catch (error) {
wx.showToast({
title: error.message || '初始化美甲师表单失败',
icon: 'none'
})
}
},
async loadShopScopedOptions(shopId) {
if (!normalizeId(shopId)) {
this._selectedTagIds = []
this._selectedProductIds = []
this.setData({
tags: [],
products: []
})
return
}
try {
const tagList = await tagApi.listTagsByShopId(shopId)
const productList = filterProductsByShop(this._allProducts, shopId)
this._selectedTagIds = syncSelectedIds(this._selectedTagIds, tagList)
this._selectedProductIds = syncSelectedIds(this._selectedProductIds, productList)
this.setData({
tags: buildCheckableList(tagList, this._selectedTagIds, 'tagName'),
products: buildCheckableList(productList, this._selectedProductIds, 'title')
})
} catch (error) {
this.setData({
tags: [],
products: []
})
wx.showToast({
title: error.message || '店铺关联数据加载失败',
icon: 'none'
})
}
},
handleUserInput(event) {
const field = event.currentTarget.dataset.field
let value = event.detail.value
if (field === 'account') {
value = String(value || '').replace(/[^A-Za-z0-9]/g, '')
}
if (field === 'phone') {
value = String(value || '').replace(/[^\d]/g, '').slice(0, 11)
}
this.setData({
[`userForm.${field}`]: value
})
},
handleArtistInput(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`artistForm.${field}`]: event.detail.value
})
},
handleShopChange(event) {
const shopIndex = Number(event.detail.value)
const selectedShop = this.data.shops[shopIndex]
this.setData({
shopIndex,
shopLabel: selectedShop ? selectedShop.shopName : ''
})
this.loadShopScopedOptions(selectedShop ? selectedShop.id : '')
},
handleStatusChange(event) {
this.setData({
statusIndex: Number(event.detail.value)
})
},
handleTagChange(event) {
this._selectedTagIds = event.detail.value || []
this.setData({
tags: this.data.tags.map(item => ({
...item,
checked: this._selectedTagIds.includes(item.valueId)
}))
})
},
handleProductChange(event) {
this._selectedProductIds = event.detail.value || []
this.setData({
products: this.data.products.map(item => ({
...item,
checked: this._selectedProductIds.includes(item.valueId)
}))
})
},
validateForm() {
if (!this.data.userForm.nickname) {
return '请输入美甲师昵称'
}
if (!this.data.userForm.account) {
return '请输入账号'
}
if (!this.data.userForm.phone || this.data.userForm.phone.length !== 11) {
return '请输入 11 位手机号'
}
if (this.data.mode === 'create' && !this.data.userForm.password) {
return '新增美甲师时必须设置密码'
}
if (!this.data.shops[this.data.shopIndex]) {
return '请选择所属店铺'
}
return ''
},
async handleSubmit() {
const errorMessage = this.validateForm()
if (errorMessage) {
wx.showToast({
title: errorMessage,
icon: 'none'
})
return
}
const selectedShop = this.data.shops[this.data.shopIndex]
const userPayload = {
nickname: this.data.userForm.nickname,
account: this.data.userForm.account,
phone: this.data.userForm.phone,
signature: this.data.userForm.signature || undefined,
type: 3,
shopIds: selectedShop ? [Number(selectedShop.id)] : []
}
if (this.data.userForm.password) {
userPayload.password = this.data.userForm.password
}
try {
let targetUserId = this.data.userId
if (this.data.mode === 'edit') {
await userApi.updateUser(targetUserId, userPayload)
} else {
targetUserId = await userApi.createUser(userPayload)
}
await artistApi.saveNailArtistInfo({
userId: Number(targetUserId),
identity: this.data.artistForm.identity || undefined,
experience: this.data.artistForm.experience ? Number(this.data.artistForm.experience) : 0,
skills: this._selectedTagIds.join(',') || undefined,
rating: this.data.artistForm.rating ? Number(this.data.artistForm.rating) : 0,
status: this.data.statusIndex === 1 ? 0 : 1,
portfolio: this._selectedProductIds.join(',') || undefined,
nickname: this.data.userForm.nickname,
shopId: selectedShop ? Number(selectedShop.id) : undefined,
signature: this.data.userForm.signature || undefined
})
wx.showToast({
title: this.data.mode === 'edit' ? '美甲师已更新' : '美甲师已创建',
icon: 'none'
})
navigation.goBack('/pages/artists/index')
} catch (error) {
wx.showToast({
title: error.message || '保存失败',
icon: 'none'
})
}
}
})