与牧同行-兽医端小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

569 lines
14 KiB

// 第一个页面的完整JS代码 - pages/diagnosisDetail/diagnosisDetail.js
import http from '../../../utils/api'
const baseUrl = require('../../../utils/baseUrl')
Page({
/**
* 页面的初始数据
*/
data: {
diagnosisData: {},
replies: [],
baseUrl: baseUrl,
refreshing: false,
// 新增回复相关数据
showReplyInput: true,
replyContent: '',
replyImages: [],
replyImagesTemp: [], // 本地临时路径,用于预览
uploadingImage: false,
submittingReply: false,
isUploading: false // 防止重复上传
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
if (options.data) {
// 根据id加载兽医回复数据
const data = JSON.parse(decodeURIComponent(options.data));
// 处理用户图片 - 确保是数组格式
if (data.images) {
if (typeof data.images === 'string') {
data.images = data.images.split(',')
}
console.log('用户图片:', data.images);
} else {
data.images = [];
}
this.setData({
diagnosisData: data,
})
this.loadDiagnosisData(data.formId);
}
},
/**
* 加载问诊数据(兽医回复)
* @param {string} id - 问诊ID
*/
loadDiagnosisData(id) {
console.log('加载问诊数据:', id);
wx.showLoading({
title: '加载中...',
mask: true
});
http.wzdxq({
data: {
consultationId: id
},
success: res => {
wx.hideLoading();
// 处理兽医回复的图片
let replies = [];
if (res && res.rows) {
replies = res.rows || [];
// 遍历每个回复,处理图片字段
for (let i = 0; i < replies.length; i++) {
const item = replies[i];
// 处理图片 - 确保是数组格式
if (item.images) {
if (typeof item.images === 'string') {
// 如果是空字符串,设为空数组
if (item.images.trim() === '') {
item.images = [];
} else {
// 按逗号分割字符串
item.images = item.images.split(',');
}
} else if (Array.isArray(item.images)) {
// 已经是数组,但需要过滤空值
item.images = item.images.filter(img => img && img.trim() !== '');
} else {
item.images = [];
}
} else {
item.images = [];
}
console.log(`兽医回复[${i}]图片:`, item.images);
}
}
console.log('兽医回复数据:', replies);
this.setData({
replies: replies
})
},
fail: err => {
wx.hideLoading();
console.error('加载回复失败:', err);
wx.showToast({
title: '加载失败',
icon: 'none'
});
}
})
},
/**
* 回复内容输入
*/
onReplyContentInput(e) {
this.setData({
replyContent: e.detail.value
});
},
/**
* 清空所有图片
*/
clearAllImages() {
if (this.data.replyImages.length === 0) return;
wx.showModal({
title: '提示',
content: '确定要清空所有已选图片吗?',
success: (res) => {
if (res.confirm) {
this.setData({
replyImages: [],
replyImagesTemp: []
});
}
}
});
},
/**
* 选择回复图片 - 优化后的版本
*/
chooseReplyImage() {
if (this.data.isUploading) {
wx.showToast({
title: '正在上传中,请稍候',
icon: 'none'
});
return;
}
if (this.data.replyImages.length >= 9) {
wx.showToast({
title: '最多上传9张图片',
icon: 'none'
});
return;
}
wx.chooseMedia({
count: 9 - this.data.replyImages.length,
mediaType: ['image'],
sourceType: ['album', 'camera'],
sizeType: ['compressed'],
success: (res) => {
if (res.tempFiles && res.tempFiles.length > 0) {
this.setData({
isUploading: true
});
// 显示加载提示
wx.showLoading({
title: '上传图片中...',
mask: true
});
// 获取临时文件路径列表
const tempPaths = res.tempFiles.map(file => file.tempFilePath);
// 保存临时路径用于预览
const newTempPaths = [...this.data.replyImagesTemp, ...tempPaths];
this.setData({
replyImagesTemp: newTempPaths
});
// 逐张上传图片
this.uploadImages(tempPaths);
}
}
});
},
/**
* 上传多张图片 - 优化后的版本
*/
uploadImages(filePaths) {
const uploadTasks = filePaths.map(path => {
return new Promise((resolve, reject) => {
wx.uploadFile({
url: baseUrl + '/common/upload',
filePath: path,
name: 'file',
header: {
'Authorization': 'Bearer ' + wx.getStorageSync('token')
},
success: (res) => {
try {
const data = JSON.parse(res.data);
if (data.code === 200 || data.fileName) {
const imagePath = data.fileName || data.url;
resolve(imagePath);
} else {
reject(new Error(data.msg || '上传失败'));
}
} catch (e) {
reject(e);
}
},
fail: (err) => {
reject(err);
}
});
});
});
Promise.all(uploadTasks)
.then((imagePaths) => {
wx.hideLoading();
// 将新上传的图片添加到现有图片数组中
const newReplyImages = [...this.data.replyImages, ...imagePaths];
this.setData({
replyImages: newReplyImages,
isUploading: false
});
wx.showToast({
title: '上传成功',
icon: 'success'
});
})
.catch((err) => {
wx.hideLoading();
console.error('上传失败:', err);
// 上传失败时,移除对应的临时预览图片
const failedCount = filePaths.length;
const currentTempPaths = [...this.data.replyImagesTemp];
for (let i = 0; i < failedCount; i++) {
currentTempPaths.pop();
}
this.setData({
replyImagesTemp: currentTempPaths,
isUploading: false
});
wx.showToast({
title: '上传失败,请重试',
icon: 'none'
});
});
},
/**
* 移除单张回复图片
*/
removeReplyImage(e) {
const index = e.currentTarget.dataset.index;
const replyImages = this.data.replyImages.filter((_, i) => i !== index);
const replyImagesTemp = this.data.replyImagesTemp.filter((_, i) => i !== index);
this.setData({
replyImages: replyImages,
replyImagesTemp: replyImagesTemp
});
},
/**
* 提交回复 - 优化后的版本
*/
submitReply() {
const content = this.data.replyContent.trim();
const images = this.data.replyImages;
// 检查内容
if (!content && images.length === 0) {
wx.showToast({
title: '请输入回复内容或上传图片',
icon: 'none'
});
return;
}
if (this.data.submittingReply || this.data.isUploading) {
wx.showToast({
title: this.data.isUploading ? '图片上传中,请稍后' : '提交中,请稍后',
icon: 'none'
});
return;
}
this.setData({ submittingReply: true });
// 显示加载提示
wx.showLoading({
title: '发送中...',
mask: true
});
// 准备提交数据
const submitData = {
consultationId: this.data.diagnosisData.formId,
content: content
};
// 如果有图片,将图片数组转为逗号分隔的字符串
if (images.length > 0) {
submitData.images = images.join(',');
}
console.log('提交回复数据:', submitData);
// 调用回复接口
http.wzdAdd({
data: submitData,
success: res => {
wx.hideLoading();
if (res.code === 200 || res.success) {
// 清空输入
this.setData({
replyContent: '',
replyImages: [],
replyImagesTemp: [],
submittingReply: false
});
wx.showToast({
title: '回复成功',
icon: 'success'
});
// 重新加载回复列表
this.loadDiagnosisData(this.data.diagnosisData.formId);
// 滚动到底部
setTimeout(() => {
wx.createSelectorQuery().select('.page-content').boundingClientRect(rect => {
wx.pageScrollTo({
scrollTop: rect.height,
duration: 300
});
}).exec();
}, 500);
} else {
this.setData({ submittingReply: false });
wx.showToast({
title: res.message || '回复失败',
icon: 'none'
});
}
},
fail: err => {
wx.hideLoading();
this.setData({ submittingReply: false });
console.error('回复失败:', err);
wx.showToast({
title: '网络错误,请重试',
icon: 'none'
});
}
});
},
/**
* 返回上一页
*/
goBack() {
wx.navigateBack();
},
/**
* 分享
*/
onShare() {
wx.showActionSheet({
itemList: ['分享给好友', '保存到相册'],
success: (res) => {
if (res.tapIndex === 0) {
wx.showToast({
title: '已分享',
icon: 'success'
});
}
}
});
},
/**
* 下拉刷新
*/
onRefresh() {
this.setData({
refreshing: true
});
if (this.data.diagnosisData && this.data.diagnosisData.formId) {
this.loadDiagnosisData(this.data.diagnosisData.formId)
}
setTimeout(() => {
this.setData({
refreshing: false
});
wx.showToast({
title: '刷新成功',
icon: 'success'
});
}, 1000);
},
/**
* 预览用户图片
*/
previewImage(e) {
const dataset = e.currentTarget.dataset;
const current = dataset.url;
const urls = dataset.urls || [];
// 构建完整URL数组
const urlsArray = urls.map(item => {
if (typeof item === 'string' && (item.startsWith('http://') || item.startsWith('https://'))) {
return item;
}
return baseUrl + item;
});
console.log('预览用户图片:', urlsArray);
wx.previewImage({
current: current,
urls: urlsArray
});
},
/**
* 预览兽医回复图片
*/
previewReplyImage(e) {
const dataset = e.currentTarget.dataset;
const currentFileName = dataset.url;
const currentFullUrl = dataset.fullurl;
const urlsArray = dataset.urls || [];
const currentIndex = dataset.currentIndex || 0;
const replyIndex = dataset.replyIndex;
console.log('预览兽医图片 - 数据集:', dataset);
// 从replies数据中获取当前回复的图片列表
let targetUrls = [];
let targetCurrentUrl = '';
if (replyIndex !== undefined && this.data.replies[replyIndex]) {
const reply = this.data.replies[replyIndex];
if (reply.images && reply.images.length > 0) {
targetUrls = reply.images;
const fullUrls = targetUrls.map(img => {
if (typeof img === 'string' && (img.startsWith('http://') || img.startsWith('https://'))) {
return img;
}
return baseUrl + img;
});
if (currentIndex < fullUrls.length) {
targetCurrentUrl = fullUrls[currentIndex];
} else if (currentFullUrl) {
targetCurrentUrl = currentFullUrl;
} else if (currentFileName) {
targetCurrentUrl = baseUrl + currentFileName;
}
console.log('预览兽医回复图片:', fullUrls, '当前:', targetCurrentUrl);
wx.previewImage({
current: targetCurrentUrl,
urls: fullUrls
});
return;
}
}
// 使用dataset中的数据
if (urlsArray && urlsArray.length > 0) {
const fullUrls = urlsArray.map(item => {
if (typeof item === 'string' && (item.startsWith('http://') || item.startsWith('https://'))) {
return item;
}
return baseUrl + item;
});
let currentUrl = '';
if (currentFullUrl) {
currentUrl = currentFullUrl;
} else if (currentIndex < fullUrls.length) {
currentUrl = fullUrls[currentIndex];
} else if (currentFileName) {
currentUrl = baseUrl + currentFileName;
}
console.log('预览兽医回复图片(从dataset):', fullUrls, '当前:', currentUrl);
wx.previewImage({
current: currentUrl,
urls: fullUrls
});
return;
}
// 预览单张图片
if (currentFullUrl) {
console.log('预览单张兽医图片:', [currentFullUrl]);
wx.previewImage({
current: currentFullUrl,
urls: [currentFullUrl]
});
} else if (currentFileName) {
const fullUrl = baseUrl + currentFileName;
console.log('预览单张兽医图片(拼接后):', [fullUrl]);
wx.previewImage({
current: fullUrl,
urls: [fullUrl]
});
} else {
wx.showToast({
title: '图片预览失败',
icon: 'none'
});
}
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
// 如果已经有数据,刷新列表
if (this.data.diagnosisData && this.data.diagnosisData.formId) {
this.loadDiagnosisData(this.data.diagnosisData.formId);
}
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
// 页面卸载时重置状态
this.setData({
submittingReply: false,
isUploading: false
});
}
});