<template>
	<view class="page-container">
		<!-- 顶部导航栏 -->
<!-- 		<view class="nav-bar">
			<view class="nav-left">
				<text class="back-icon" @click="navigateBack">←</text>
			</view>
			<view class="nav-title">上书记录</view>
			<view class="nav-right">
				<text class="more-icon">⋮</text>
			</view>
		</view> -->

		<!-- 账号/店铺切换 -->
		<view class="tab-switch">
			<view class="tab" :class="{active: activeTab === 'account'}" @click="activeTab = 'account'">
				<text>账号</text>
			</view>
			<view class="tab" :class="{active: activeTab === 'store'}" @click="activeTab = 'store'">
				<text>店铺</text>
			</view>
		</view>

		<!-- 日期选择器 -->
		<view class="date-picker-bar">
			<picker mode="date" :value="dateInput" @change="onDatePickerConfirm">
				<view class="date-left">
					<text class="date-day">{{displayDate.day}}</text>
					<view class="date-info">
						<text>{{displayDate.day}} 日 - {{displayDate.month}} 月 - {{displayDate.year}} 年</text>
						<text class="date-arrow">▼</text>
					</view>
				</view>
			</picker>
			<text class="date-total">累计 {{ total }} 条</text>
		</view>
		
		
		<!-- 加载中提示 -->
		<view class="loading-state" v-if="isLoading">
			<text>正在加载...</text>
		</view>

		<!-- 图片网格 -->
		<scroll-view
			scroll-y
			style="height: 100vh"
			@scrolltolower="loadMore"
		>
			<view class="image-grid">
				<view class="image-item" v-for="(record, index) in filteredBookRecords" :key="index"
					@click="previewImage(record.images)">
					<image :src="record.bookPic ? record.bookPic : record.images[0]" mode="aspectFill" class="book-image"></image> 
					<view class="image-info">
						<text class="book-name">{{record.bookName}}</text>
						<view class="book-details">
							<text class="book-isbn">ISBN: {{record.isbn}}</text>
						</view>
						<view class="book-details">
							<text class="book-condition">品相: {{record.condition}}</text>
							<text class="upload-time">{{record.uploadTime}}</text>
						</view>
						<view class="book-details">
							<!-- <text v-if="record.artNo" class="book-artno">货号: {{formatArtNo(record.artNo)}}</text> -->
							<!-- <text v-if="record.itemNumber" class="book-item-number">商品ID: {{record.itemNumber}}</text> -->
							<text v-if="record.stock !== undefined" class="book-stock">库存: {{record.stock}}</text>
							<text class="book-price">{{record.price}}元</text>
						</view>
						
						<view class="book-details">
							<text class="book-condition">拼多多:</text>
							<text class="status-value" :class="record.pddPublishedStatus === 1 ? 'published' : 'unpublished'">
								{{record.pddPublishedStatus === 1 ? '已发布' : '未发布'}}
							</text>
						</view>
						<view class="book-details" :class="{'status-success': record.kfzPublishedStatus === 1}">
							<text class="book-condition">孔夫子:</text>
							<text class="status-value" :class="record.kfzPublishedStatus === 1 ? 'published' : 'unpublished'">
								{{record.kfzPublishedStatus === 1 ? '已发布' : '未发布'}}
							</text>
						</view>
						<view class="book-details" :class="{'status-success': record.xyPublishedStatus === 1}">
							<text class="book-condition">闲鱼:</text>
							<text class="status-value" :class="record.xyPublishedStatus === 1 ? 'published' : 'unpublished'">
								{{record.xyPublishedStatus === 1 ? '已发布' : '未发布'}}
							</text>
						</view>
					</view>
				</view>
			</view>
			<view class="loading-more" v-if="isLoading">
				<text>加载中...</text>
			</view>
			<view class="no-more" v-if="!hasMore && filteredBookRecords.length > 0">
				<text>没有更多数据了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import * as bookRecords from '@/service/bookRecords.js';

	export default {
		data() {
			return {
				bookRecords: [], // 存储上书记录数据
				filteredBookRecords: [], // 筛选后的上书记录
				activeTab: 'account', // 当前激活的标签
				isLoading: true, // 加载状态
				totalCount: 0, // 累计数量
				show: false,
				dateInput: '',
				displayDate: {
					day: new Date().getDate().toString().padStart(2, '0'),
					month: (new Date().getMonth() + 1).toString().padStart(2, '0'),
					year: new Date().getFullYear()
				},
				// 添加分页相关数据
				pageNum: 1,
				pageSize: 10,
				hasMore: true,
				total: 0
			}
		},
		onLoad(options) {
			// 尝试获取事件通道
			try {
				const eventChannel = this.getOpenerEventChannel();
				if (eventChannel && typeof eventChannel.on === 'function') {
					// 如果事件通道可用，监听数据
					eventChannel.on('bookRecordsData', (data) => {
						console.log('接收到的上书记录数据:', data.records);
						if (data && data.records) {
							this.processBookRecords(data.records);
						} else {
							// 如果数据无效，使用备用方案
							console.log('接收到的数据无效，使用备用方案');
							this.loadBookRecords();
						}
					});
				} else {
					// 事件通道不可用，使用备用方案
					console.log('事件通道不可用，使用备用方案');
					this.loadBookRecords();
				}
			} catch (error) {
				// 发生错误时使用备用方案
				console.error('获取事件通道失败:', error);
				this.loadBookRecords();
			}
			// 初始化filteredBookRecords
			this.filteredBookRecords = this.bookRecords;
		},
		// 添加下拉刷新和上拉加载更多方法
		onPullDownRefresh() {
			this.pageNum = 1;
			this.hasMore = true;
			this.loadBookRecords().then(() => {
				uni.stopPullDownRefresh();
			});
		},
		onReachBottom() {
			if (this.hasMore && !this.isLoading) {
				this.loadMore();
			}
		},
		methods: {
			onDatePickerConfirm(e) {
				this.dateInput = e.detail.value;
				console.log("获取日期",this.dateInput)
				const [year, month, day] = this.dateInput.split('-');
				this.displayDate = { day, month, year };
				
				// 重置分页
				this.pageNum = 1;
				this.hasMore = true;
				
				// 直接请求后端，获取该日期的所有数据
				this.loadBookRecords();
			},
			resetDateFilter() {
				this.filteredBookRecords = this.bookRecords;
				const now = new Date();
				this.displayDate = {
					day: now.getDate().toString().padStart(2, '0'),
					month: (now.getMonth() + 1).toString().padStart(2, '0'),
					year: now.getFullYear()
				};
				this.dateInput = '';
			},
			// 返回上一页
			navigateBack() {
				uni.navigateBack()
			},
			// 处理上书记录数据
			processBookRecords(records) {
				try {
					console.log('开始处理上书记录数据:', records);
					
					// 检查 records 是否为有效数据
					if (!records || !records.rows || !Array.isArray(records.rows)) {
						console.error('无效的上书记录数据格式:', records);
						throw new Error('无效的数据格式');
					}

					// 处理从后端接收的数据
					this.bookRecords = records.rows.map(item => {
						// 确保images是数组格式
						let images = [];
						if (item.bookPic) {
							images.push(item.bookPic);
						} else if (item.imageUrl) {
							images.push(item.imageUrl);
						} else if (item.images && Array.isArray(item.images)) {
							images = item.images;
						} else {
							// 使用默认的imgNull.webp图片
							images.push('/static/imgNull.webp');
						}
						
						// 格式化上传时间
						let uploadTime = item.createTime || item.uploadTime || new Date().toISOString();
						if (uploadTime && uploadTime.length > 10) {
							uploadTime = uploadTime.substring(0, 10); // 只保留日期部分
						}
						
						// 处理品相代码
						let conditionText = '未知品相';
						if (item.conditionCode) {
							switch(item.conditionCode) {
								case 'A': conditionText = '一品'; break;
								case 'B': conditionText = '二品'; break;
								case 'C': conditionText = '三品'; break;
								case 'D': conditionText = '四品'; break;
								case 'E': conditionText = '五品'; break;
								case 'F': conditionText = '六品'; break;
								case 'G': conditionText = '六五品'; break;
								case 'H': conditionText = '七品'; break;
								case 'I': conditionText = '七五品'; break;
								case 'J': conditionText = '八品'; break;
								case 'K': conditionText = '八五品'; break;
								case 'L': conditionText = '九品'; break;
								case 'M': conditionText = '九五品'; break;
								case 'N': conditionText = '全新'; break;
								default: conditionText = item.conditionCode;
							}
						} else if (item.condition) {
							conditionText = item.condition;
						} else if (item.qualityText) {
							conditionText = item.qualityText;
						}
						
						return {
							bookName: item.goodsName || item.bookName || item.name || '未知书名',
							uploadTime: uploadTime,
							images: images,
							isbn: item.isbn || '无ISBN',
							price: item.price / 100 || 0,
							condition: conditionText,
							artNo: item.artNo || '',
							itemNumber: item.itemNumber || item.productId || '',
							productId: item.productId || '',
							stock: item.inventory || 0,
							id: item.id || '',
							remark: item.remark || '',
							kfzPublishedStatus: item.kfzPublishedStatus || 0,
							pddPublishedStatus: item.pddPublishedStatus || 0,
							xyPublishedStatus: item.xyPublishedStatus || 0,
							bookPic: item.bookPic || '',
						};
					});
					
					// 更新总数
					this.total = records.total || 0;
					
					// 按uploadTime倒序排序
					this.bookRecords.sort((a, b) => {
						if (!a.uploadTime) return 1;
						if (!b.uploadTime) return -1;
						return b.uploadTime.localeCompare(a.uploadTime);
					});
					
					this.totalCount = this.bookRecords.length;
					this.isLoading = false;
					console.log('处理后的上书记录数据:', this.bookRecords);
					this.filteredBookRecords = this.bookRecords; // 初始化筛选数据
				} catch (error) {
					console.error('处理上书记录数据失败:', error);
					this.isLoading = false;
					uni.showToast({
						title: '数据处理失败',
						icon: 'none'
					});
				}
			},
			
			// 修改加载上书记录方法
			async loadBookRecords() {
				try {
					this.isLoading = true;
					const phoneNumber = uni.getStorageSync('phoneNumber');
					if (!phoneNumber) {
						uni.showToast({
							title: '请先登录',
							icon: 'none' 
						});
						return;
					}
					// 新增：带上日期参数
					const date = this.dateInput; // 格式：'2024-06-08'
					console.log("时间",date)
					const result = await bookRecords.fetchBookRecords(phoneNumber, this.pageNum, this.pageSize, date);
					if (result && result.rows) {
						const formattedRows = result.rows.map(item => {
							let images = [];
							if (item.bookPic) {
								images.push(item.bookPic);
							} else if (item.imageUrl) {
								images.push(item.imageUrl);
							} else if (item.images && Array.isArray(item.images)) {
								images = item.images;
							} else {
								images.push('/static/imgNull.webp');
							}
							let uploadTime = item.createTime || item.uploadTime || new Date().toISOString();
							if (uploadTime && uploadTime.length > 10) {
								uploadTime = uploadTime.substring(0, 10);
							}
							let conditionText = '未知品相';
							if (item.conditionCode) {
								switch(item.conditionCode) {
									case 'A': conditionText = '一品'; break;
									case 'B': conditionText = '二品'; break;
									case 'C': conditionText = '三品'; break;
									case 'D': conditionText = '四品'; break;
									case 'E': conditionText = '五品'; break;
									case 'F': conditionText = '六品'; break;
									case 'G': conditionText = '六五品'; break;
									case 'H': conditionText = '七品'; break;
									case 'I': conditionText = '七五品'; break;
									case 'J': conditionText = '八品'; break;
									case 'K': conditionText = '八五品'; break;
									case 'L': conditionText = '九品'; break;
									case 'M': conditionText = '九五品'; break;
									case 'N': conditionText = '全新'; break;
									default: conditionText = item.conditionCode;
								}
							} else if (item.condition) {
								conditionText = item.condition;
							} else if (item.qualityText) {
								conditionText = item.qualityText;
							}
							return {
								bookName: item.goodsName || item.bookName || item.name || '未知书名',
								uploadTime: uploadTime,
								images: images,
								isbn: item.isbn || '无ISBN',
								price: item.price / 100 || 0,
								condition: conditionText,
								artNo: item.artNo || '',
								itemNumber: item.itemNumber || item.productId || '',
								productId: item.productId || '',
								stock: item.inventory || 0,
								id: item.id || '',
								remark: item.remark || '',
								kfzPublishedStatus: item.kfzPublishedStatus || 0,
								pddPublishedStatus: item.pddPublishedStatus || 0,
								xyPublishedStatus: item.xyPublishedStatus || 0,
								bookPic: item.bookPic || '',
							};
						});

						if (this.pageNum === 1) {
							this.bookRecords = formattedRows;
						} else {
							this.bookRecords = [...this.bookRecords, ...formattedRows];
						}
						this.filteredBookRecords = this.bookRecords;
						this.total = result.total;
						this.hasMore = this.bookRecords.length < result.total;
						this.gotoPage = this.pageNum;
					}
				} catch (error) {
					console.error('加载上书记录失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
				}
			},
			// 添加加载更多方法
			async loadMore() {
				if (!this.hasMore || this.isLoading) return;
				
				this.pageNum++;
				await this.loadBookRecords();
			},
			// 预览图片
			previewImage(images) {
				// 显示图片预览
				uni.previewImage({
					urls: images,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮')
						},
						fail: function(err) {
							console.log(err.errMsg)
						}
					}
				})
			},
			
			// 格式化货号信息
			formatArtNo(artNo) {
				if (!artNo) return '';
				
				// 解析货号格式，例如 CM11M-9787538259704A
				// C: 表示品类，M: 表示品相等级
				let result = '';
				
				if (artNo.startsWith('C')) {
					result += '书籍/';
				}
				
				// 提取品相信息
				const conditionMatch = artNo.match(/[A-Z](\d+)([A-Z])/i);
				if (conditionMatch && conditionMatch[2]) {
					const condition = conditionMatch[2];
					switch(condition) {
						case 'N': result += '全新/'; break;
						case 'A': result += '上好/'; break;
						case 'B': result += '中上/'; break;
						case 'M': result += '中等/'; break;
						case 'L': result += '中下/'; break;
						default: result += condition + '/';
					}
				}
				
				return result + artNo;
			},
			// 添加生成占位图的方法
			generatePlaceholderImage() {
				// 创建canvas上下文
				const canvas = uni.createCanvasContext('placeholderCanvas');
				
				// 设置背景色
				canvas.setFillStyle('#f5f5f5');
				canvas.fillRect(0, 0, 300, 400);
				
				// 设置文字样式
				canvas.setFillStyle('#999999');
				canvas.setFontSize(28);
				canvas.setTextAlign('center');
				canvas.setTextBaseline('middle');
				
				// 绘制文字
				canvas.fillText('暂无图片', 150, 200);
				
				// 将canvas内容转换为图片
				return new Promise((resolve) => {
					canvas.draw(false, () => {
						setTimeout(() => {
							uni.canvasToTempFilePath({
								canvasId: 'placeholderCanvas',
								success: (res) => {
									resolve(res.tempFilePath);
								},
								fail: (err) => {
									console.error('生成占位图失败:', err);
									resolve('/static/images/default-book.png'); // 失败时使用默认图片
								}
							});
						}, 100);
					});
				});
			}
		}
	}
</script>

<style>
	.page-container {
		padding-bottom: 20rpx;
	}

	/* 导航栏样式 */
	.nav-bar {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background-color: #fff;
	}

	.nav-left,
	.nav-right {
		width: 80rpx;
	}

	.back-icon,
	.more-icon {
		font-size: 40rpx;
	}

	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
	}

	/* 标签切换样式 */
	.tab-switch {
		display: flex;
		padding: 20rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.tab {
		flex: 1;
		text-align: center;
		padding: 16rpx 0;
		color: #666;
	}

	.tab.active {
		color: #007AFF;
		font-weight: bold;
	}

	/* 日期选择器样式 */
	.date-picker-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #fff;
		padding: 24rpx 20rpx 0 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.date-left {
		display: flex;
		align-items: baseline;
		cursor: pointer;
	}

	.date-day {
		font-size: 64rpx;
		font-weight: bold;
		color: #222;
		margin-right: 16rpx;
	}

	.date-info {
		display: flex;
		flex-direction: column;
		font-size: 28rpx;
		color: #666;
	}

	.date-arrow {
		font-size: 24rpx;
		color: #bbb;
		margin-left: 8rpx;
	}

	.date-total {
		font-size: 28rpx;
		color: #007AFF;
		font-weight: bold;
	}

	/* 加载状态样式 */
	.loading-state {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
	}

	/* 图片网格样式 */
	.image-grid {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 20rpx;
	}

	.image-item {
		width: 48%;
		margin-bottom: 20rpx;
		margin-right: 2%;
		background: #fff;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.image-item:nth-child(2n) {
		margin-right: 0;
	}

	.book-image {
		width: 100%;
		height: 300rpx;
		object-fit: cover;
	}

	.image-info {
		padding: 16rpx;
	}

	.book-name {
		font-size: 28rpx;
		color: #333;
		display: block;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		font-weight: bold;
		margin-bottom: 8rpx;
	}

	.book-details {
		display: flex;
		justify-content: space-between;
		margin-top: 6rpx;
	}

	.book-isbn, .book-price, .book-condition, .upload-time, .book-artno {
		font-size: 24rpx;
		color: #666;
	}

	.book-price {
		color: #ff6b00;
		font-weight: bold;
	}

	.book-condition {
		color: #007AFF;
	}

	.upload-time {
		color: #999;
	}

	.book-artno, .book-item-number {
		color: #999;
		font-size: 22rpx;
	}

	.book-stock {
		display: block;
		margin-top: 6rpx;
		color: #4CAF50;
		font-size: 22rpx;
		font-weight: bold;
	}

	/* 空状态样式 */
	.empty-state {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
	}

	.status-value.published {
		color: #007aff;
		font-size: 24rpx;
	}
	.status-value.unpublished {
		color: #ff4d4f;
		font-size: 24rpx;
	}

	/* 添加新样式 */
	.loading-more, .no-more {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 24rpx;
	}

	.no-more {
		color: #666;
	}
</style>