<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 class="header-cell">报工时间</view>
					</view>
					
					<view class="table-body">
						<view 
							v-for="(item, index) in projectReportList" 
							:key="item.reportId" 
							class="table-row"
						>
							<view class="table-cell checkbox">
								<u-checkbox 
									v-model="item.selected" 
									@change="handleSelectionChange"
								></u-checkbox>
							</view>
							<view class="table-cell">
								<u-tag v-if="!item.projectCode" type="error" text="无"></u-tag>
								<u-tag v-else :text="item.projectCode"></u-tag>
							</view>
							<view class="table-cell">
								<text v-if="item.prePay > 0">⭐</text>
								<text>{{ item.projectName }}</text>
							</view>
							<view class="table-cell">{{ item.projectNum }}</view>
							<view class="table-cell">
								<text>{{ item.nickName }}</text>
								<text v-if="item.deptName">({{ item.deptName }})</text>
							</view>
							<view class="table-cell">{{ item.workPlace }}</view>
							<view class="table-cell">
								<u-tag :type="item.workType === 0 ? 'primary' : 'warning'" :text="item.workType === 0 ? '国内' : '国外'"></u-tag>
							</view>
							<view class="table-cell">{{ formatDate(item.createTime) }}</view>
						</view>
					</view>
				</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="800rpx">
			<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="180rpx">
						<u-form-item label="工作地点" prop="workPlace">
							<u-input v-model="form.workPlace" placeholder="请输入工作地点"></u-input>
						</u-form-item>
						
						<u-form-item label="是否出差" prop="isTrip">
							<u-radio-group v-model="form.isTrip">
								<u-radio :name="1" label="是"></u-radio>
								<u-radio :name="0" label="否"></u-radio>
							</u-radio-group>
						</u-form-item>
						
						<u-form-item v-if="form.isTrip === 1" label="国内/国外" prop="workType">
							<u-radio-group v-model="form.workType">
								<u-radio :name="0" label="国内"></u-radio>
								<u-radio :name="1" label="国外"></u-radio>
							</u-radio-group>
						</u-form-item>
						
						<u-form-item label="请选择项目" prop="projectId">
							<u-select
								v-model="form.projectId"
								:list="projectList"
								placeholder="请选择项目"
								label-name="projectName"
								value-name="projectId"
							></u-select>
						</u-form-item>
						
						<u-form-item label="报工内容" prop="content">
							<u-textarea
								v-model="form.content"
								placeholder="请输入报工内容"
								:height="200"
							></u-textarea>
						</u-form-item>
						
						<u-form-item label="备注" prop="remark">
							<u-input v-model="form.remark" 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 { listProjectReport, addProjectReport, delProjectReport } from '@/api/oa/projectReport'
import { listProject } from '@/api/oa/project'
import { listDept } from '@/api/oa/dept'

export default {
	data() {
		return {
			// 按钮loading
			buttonLoading: false,
			// 遮罩层
			loading: true,
			// 选中数组
			selectedIds: [],
			// 全选状态
			selectAll: false,
			// 总条数
			total: 0,
			// 项目报工表格数据
			projectReportList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			showForm: false,
			// 项目列表
			projectList: [],
			// 部门列表
			deptList: [],
			// 表单参数
			form: {},
			// 加载更多状态
			loadMoreStatus: 'loadmore',
			// 分页参数
			queryParams: {
				pageNum: 1,
				pageSize: 10
			},
			// 表单校验规则
			rules: {
				workPlace: [
					{ required: true, message: "工作地点不能为空", trigger: "blur" }
				],
				projectId: [
					{ required: true, message: "项目不能为空", trigger: "blur" }
				],
				content: [
					{ required: true, message: "报工内容不能为空", trigger: "blur" }
				],
				isTrip: [
					{ required: true, message: '请选择是否出差', trigger: 'change' }
				],
				workType: [
					{
						required: true,
						message: '请选择出差地点',
						trigger: 'change',
						validator: (rule, value, callback) => {
							if (this.form.isTrip === 1 && !value && value !== 0) {
								callback(new Error('请选择出差地点'));
							} else {
								callback();
							}
						}
					}
				]
			}
		}
	},
	onLoad() {
		this.getList();
	},
	methods: {
		// 格式化日期
		formatDate(date) {
			if (!date) return '';
			const d = new Date(date);
			return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
		},
		
		// 获取项目列表
		getProjectList() {
			listProject({ pageNum: 1, pageSize: 9999 }).then(res => {
				this.projectList = res.rows || [];
			}).catch(err => {
				console.error('获取项目列表失败:', err);
				uni.showToast({
					title: '获取项目列表失败',
					icon: 'none'
				});
			});
		},
		
		// 获取部门列表
		getDeptList() {
			listDept().then(res => {
				this.deptList = res.data || [];
			}).catch(err => {
				console.error('获取部门列表失败:', err);
			});
		},
		
		// 查询项目报工列表
		getList() {
			this.loading = true;
			listProjectReport(this.queryParams).then(response => {
				this.projectReportList = (response.rows || []).map(item => ({
					...item,
					selected: false
				}));
				this.total = response.total || 0;
				this.loading = false;
				this.getProjectList();
				// this.getDeptList();
			}).catch(err => {
				console.error('获取报工列表失败:', err);
				this.loading = false;
				uni.showToast({
					title: '获取数据失败',
					icon: 'none'
				});
			});
		},
		
		// 全选/取消全选
		handleSelectAll(value) {
			this.projectReportList.forEach(item => {
				item.selected = value;
			});
			this.updateSelectedIds();
		},
		
		// 选择变化
		handleSelectionChange() {
			this.updateSelectedIds();
			// 更新全选状态
			const selectedCount = this.projectReportList.filter(item => item.selected).length;
			this.selectAll = selectedCount === this.projectReportList.length && this.projectReportList.length > 0;
		},
		
		// 更新选中ID数组
		updateSelectedIds() {
			this.selectedIds = this.projectReportList
				.filter(item => item.selected)
				.map(item => item.reportId);
		},
		
		// 新增
		handleAdd() {
			this.reset();
			this.showForm = true;
			this.title = "添加项目报工";
		},
		
		// 删除
		handleDelete() {
			if (!this.selectedIds.length) {
				uni.showToast({
					title: '请选择要删除的数据',
					icon: 'none'
				});
				return;
			}
			
			uni.showModal({
				title: '确认删除',
				content: `是否确认删除项目报工编号为"${this.selectedIds.join(',')}"的数据项？`,
				success: (res) => {
					if (res.confirm) {
						this.loading = true;
						// 批量删除
						const deletePromises = this.selectedIds.map(id => delProjectReport(id));
						
						Promise.all(deletePromises).then(() => {
							this.loading = false;
							this.selectedIds = [];
							this.selectAll = false;
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							this.getList(); // 重新获取列表
						}).catch(err => {
							this.loading = false;
							console.error('删除失败:', err);
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							});
						});
					}
				}
			});
		},
		
		// 提交表单
		submitForm() {
			this.$refs.form.validate(valid => {
				if (valid) {
					this.buttonLoading = true;
					
					// 获取选中的项目信息
					const selectedProject = this.projectList.find(p => p.projectId === this.form.projectId);
					
					const submitData = {
						...this.form,
						projectName: selectedProject?.projectName || '',
						projectNum: selectedProject?.projectNum || '',
						projectCode: selectedProject?.projectCode || null
					};
					
					addProjectReport(submitData).then(response => {
						this.buttonLoading = false;
						uni.showToast({
							title: '新增成功',
							icon: 'success'
						});
						this.showForm = false;
						this.getList(); // 重新获取列表
					}).catch(err => {
						this.buttonLoading = false;
						console.error('新增失败:', err);
						uni.showToast({
							title: '新增失败',
							icon: 'none'
						});
					});
				}
			});
		},
		
		// 取消
		cancel() {
			this.showForm = false;
			this.reset();
		},
		
		// 重置表单
		reset() {
			this.form = {
				workPlace: '',
				projectId: null,
				content: '',
				remark: '',
				isTrip: undefined,
				workType: undefined
			};
		},
		
		// 加载更多
		loadMore() {
			if (this.projectReportList.length >= this.total) {
				this.loadMoreStatus = 'nomore';
				return;
			}
			
			this.queryParams.pageNum++;
			this.loadMoreStatus = 'loading';
			
			listProjectReport(this.queryParams).then(response => {
				const newData = (response.rows || []).map(item => ({
					...item,
					selected: false
				}));
				this.projectReportList = [...this.projectReportList, ...newData];
				this.loadMoreStatus = 'loadmore';
			}).catch(err => {
				console.error('加载更多失败:', err);
				this.loadMoreStatus = 'loadmore';
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				});
			});
		}
	}
}
</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: 1400rpx; // 设置最小宽度，确保表格内容不会被压缩
}

.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;
		
		&:hover {
			background-color: #f8f9fa;
		}
		
		.table-cell {
			width: 200rpx; // 固定列宽
			padding: 20rpx 10rpx;
			text-align: center;
			font-size: 26rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			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: 600rpx;
	}
	
	.popup-footer {
		display: flex;
		justify-content: center;
		gap: 20rpx;
		padding: 30rpx;
		border-top: 1rpx solid #e9ecef;
	}
}
</style>
