<template>
	<view class="container">
		<!-- 操作按钮 -->
		<view class="action-buttons">
			<u-button type="primary" @click="handleAdd" size="medium">新增</u-button>
			<u-button type="error" @click="handleDelete" size="medium" :disabled="!selectedIds.length">删除</u-button>
		</view>

		<!-- 数据列表 -->
		<view class="table-wrapper">
			<scroll-view scroll-x class="table-scroll">
				<view class="table-container">
					<view class="table-header">
						<view class="header-cell checkbox">
							<u-checkbox v-model="selectAll" @change="handleSelectAll"></u-checkbox>
						</view>
						<view class="header-cell">汇报标题</view>
						<view class="header-cell">最近汇报时间</view>
						<view class="header-cell">汇报日期</view>
						<view class="header-cell">汇报人</view>
						<view class="header-cell">涉及项目</view>
						<view class="header-cell">备注</view>
					</view>
					<u-checkbox-group v-model="selectedIds" @change="handleSelectionChange">
						<view class="table-body">
							<view 
								v-for="(item, index) in reportSummaryList" 
								:key="item.summaryId" 
								class="table-row"
								@click="handleRowClick(item)"
							>
								<view class="table-cell checkbox" @click.stop>
									<u-checkbox 
										:name="item.summaryId"
										:value="item.summaryId"
									></u-checkbox>
								</view>
								<view class="table-cell">{{ item.reportTitle || '-' }}</view>
								<view class="table-cell">{{ formatDate(item.lastUpdateTime) }}</view>
								<view class="table-cell">{{ formatDate(item.reportDate) }}</view>
								<view class="table-cell">{{ item.reporter || '-' }}</view>
								<view class="table-cell">{{ item.projectName || '-' }}</view>
								<view class="table-cell">{{ item.remark || '-' }}</view>
							</view>
						</view>
					</u-checkbox-group>
				</view>
			</scroll-view>
		</view>

		<!-- 分页 -->
		<u-loadmore 
			v-if="total > 0"
			:status="loadMoreStatus"
			@loadmore="loadMore"
		></u-loadmore>

		<!-- 新增弹窗 -->
		<u-popup v-model="showForm" mode="center" width="600rpx" height="700rpx">
			<view class="form-popup">
				<view class="popup-header">
					<text class="popup-title">{{ title }}</text>
					<u-icon name="close" @click="cancel" size="40"></u-icon>
				</view>
				<scroll-view scroll-y class="form-content">
					<u-form :model="form" ref="form" label-width="160rpx">
						<u-form-item label="汇报标题" prop="reportTitle">
							<u-input v-model="form.reportTitle" placeholder="请输入汇报标题"></u-input>
						</u-form-item>
						<u-form-item label="汇报日期" prop="reportDate">
							<u-datetime-picker
								v-model="form.reportDate"
								type="datetime"
								placeholder="请选择汇报日期"
							></u-datetime-picker>
						</u-form-item>
						<u-form-item label="汇报人" prop="reporter">
							<u-input v-model="form.reporter" placeholder="请输入汇报人"></u-input>
						</u-form-item>
						<u-form-item label="涉及项目" prop="projectId">
							<u-select
								v-model="form.projectId"
								:list="projectList"
								label-name="projectName"
								value-name="projectId"
								placeholder="请选择涉及项目"
							></u-select>
						</u-form-item>
						<u-form-item label="备注" prop="remark">
							<u-input v-model="form.remark" type="textarea" placeholder="请输入内容"></u-input>
						</u-form-item>
					</u-form>
				</scroll-view>
				<view class="popup-footer">
					<u-button type="primary" @click="submitForm" :loading="buttonLoading">确定</u-button>
					<u-button @click="cancel">取消</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { listProject } from '@/api/oa/project'
import { addReportSummary, delReportSummary, listReportSummary } from '@/api/oa/reportSummary'

export default {
	data() {
		return {
			projectList: [],
			buttonLoading: false,
			loading: true,
			selectedIds: [],
			selectAll: false,
			showSearch: false,
			total: 0,
			reportSummaryList: [],
			title: '',
			showForm: false,
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				reportTitle: undefined,
				reportDate: undefined,
				reporter: undefined,
				projectId: undefined,
				type: 1
			},
			form: {},
			loadMoreStatus: 'loadmore',
			rules: {
				reportTitle: [
					{ required: true, message: '汇报标题不能为空', trigger: 'blur' }
				],
				reportDate: [
					{ required: true, message: '汇报日期不能为空', trigger: 'blur' }
				],
				reporter: [
					{ required: true, message: '汇报人不能为空', trigger: 'blur' }
				],
				projectId: [
					{ required: true, message: '涉及项目不能为空', trigger: 'blur' }
				],
			}
		}
	},
	onLoad() {
		this.getList();
		this.getProjectList();
	},
	methods: {
		getList() {
			this.loading = true;
			listReportSummary(this.queryParams).then(response => {
				this.reportSummaryList = response.rows || [];
				this.total = response.total || 0;
				this.loading = false;
				this.selectedIds = [];
				this.selectAll = false;
			}).catch(() => {
				this.loading = false;
			});
		},
		getProjectList() {
			listProject({ pageSize: 999 }).then(({ rows }) => {
				this.projectList = rows || [];
			});
		},
		toggleSearch() {
			this.showSearch = !this.showSearch;
		},
		handleSelectAll(value) {
			if (value) {
				// 全选
				this.selectedIds = this.reportSummaryList.map(item => item.summaryId);
			} else {
				// 取消全选
				this.selectedIds = [];
			}
		},
		handleSelectionChange(value) {
			// value 是选中的 ID 数组
			this.selectedIds = value;
			// 检查是否全选
			this.selectAll = this.reportSummaryList.length > 0 && 
				this.selectedIds.length === this.reportSummaryList.length;
		},
		cancel() {
			this.showForm = false;
			this.reset();
		},
		reset() {
			this.form = {
				reportTitle: undefined,
				reportDate: undefined,
				reporter: undefined,
				projectId: undefined,
				remark: undefined,
				type: 1
			};
			this.$refs.form && this.$refs.form.resetFields();
		},
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		resetQuery() {
			this.queryParams = {
				pageNum: 1,
				pageSize: 10,
				reportTitle: undefined,
				reportDate: undefined,
				reporter: undefined,
				projectId: undefined,
				type: 1
			};
			this.handleQuery();
		},
		handleAdd() {
			this.reset();
			this.showForm = true;
			this.title = '添加汇报概述';
		},
		submitForm() {
			this.$refs.form.validate(valid => {
				if (valid) {
					this.buttonLoading = true;
					addReportSummary(this.form).then(response => {
						uni.showToast({
							title: '新增成功',
							icon: 'success'
						});
						this.showForm = false;
						this.getList();
					}).catch(() => {
						uni.showToast({
							title: '新增失败',
							icon: 'error'
						});
					}).finally(() => {
						this.buttonLoading = false;
					});
				}
			});
		},
		handleDelete(row) {
			const ids = row ? row.summaryId : this.selectedIds;
			if (!ids || (Array.isArray(ids) && ids.length === 0)) {
				uni.showToast({
					title: '请选择要删除的数据',
					icon: 'none'
				});
				return;
			}
			uni.showModal({
				title: '确认删除',
				content: '是否确认删除选中的数据？',
				success: (res) => {
					if (res.confirm) {
						this.loading = true;
						const deleteIds = Array.isArray(ids) ? ids.join(',') : ids;
						delReportSummary(deleteIds).then(() => {
							this.loading = false;
							this.getList();
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						}).catch(() => {
							this.loading = false;
							uni.showToast({
								title: '删除失败',
								icon: 'error'
							});
						});
					}
				}
			});
		},
		formatDate(date) {
			if (!date) return '-';
			const d = new Date(date);
			return `${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2,'0')}-${d.getDate().toString().padStart(2,'0')}`;
		},
		loadMore() {
			if (this.loadMoreStatus === 'nomore') return;
			this.loadMoreStatus = 'loading';
			this.queryParams.pageNum += 1;
			listReportSummary(this.queryParams).then(response => {
				const newData = response.rows || [];
				this.reportSummaryList = [...this.reportSummaryList, ...newData];
				this.total = response.total || 0;
				if (newData.length < this.queryParams.pageSize) {
					this.loadMoreStatus = 'nomore';
				} else {
					this.loadMoreStatus = 'loadmore';
				}
			}).catch(() => {
				this.loadMoreStatus = 'loadmore';
				this.queryParams.pageNum -= 1;
			});
		},
		
		// 点击行跳转到详情页
		handleRowClick(item) {
			uni.navigateTo({
				url: `/pages/workbench/construction/detail?summaryId=${item.summaryId}&reportTitle=${encodeURIComponent(item.reportTitle || '')}&reporter=${encodeURIComponent(item.reporter || '')}&projectName=${encodeURIComponent(item.projectName || '')}`
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	padding: 20rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

.action-buttons {
	display: flex;
	gap: 20rpx;
	margin-bottom: 20rpx;
}
.table-wrapper {
	background-color: #fff;
	border-radius: 10rpx;
	overflow: hidden;
}

.table-scroll {
	width: 100%;
}

.table-container {
	min-width: 1200rpx; // 设置最小宽度，确保表格内容不会被压缩
	.table-header {
		display: flex;
		background-color: #f8f9fa;
		border-bottom: 1rpx solid #e9ecef;
		.header-cell {
			width: 200rpx; // 固定列宽
			padding: 20rpx 10rpx;
			text-align: center;
			font-weight: bold;
			font-size: 28rpx;
			flex-shrink: 0; // 防止列被压缩
			&.checkbox {
				width: 100rpx; // 复选框列宽度
			}
		}
	}
	.table-body {
		.table-row {
			display: flex;
			border-bottom: 1rpx solid #e9ecef;
			cursor: pointer;
			transition: background-color 0.2s;
			
			&:hover {
				background-color: #f8f9fa;
			}
			
			&:active {
				background-color: #e9ecef;
			}
			.table-cell {
				width: 200rpx; // 固定列宽
				padding: 20rpx 10rpx;
				text-align: center;
				font-size: 26rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-shrink: 0; // 防止列被压缩
				word-break: break-all; // 长文本换行
				&.checkbox {
					width: 100rpx; // 复选框列宽度
				}
			}
		}
	}
}
.form-popup {
	background-color: #fff;
	border-radius: 20rpx;
	overflow: hidden;
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #e9ecef;
		.popup-title {
			font-size: 32rpx;
			font-weight: bold;
		}
	}
	.form-content {
		padding: 30rpx;
		max-height: 500rpx;
	}
	.popup-footer {
		display: flex;
		gap: 20rpx;
		padding: 30rpx;
		border-top: 1rpx solid #e9ecef;
	}
}
</style>
