<template>
	<view class="container">
		<u-navbar class="u-navbar" title="日计划制定" placeholder @leftClick="leftClick" leftIconColor="#fff"
			bgColor="#00337A" :titleStyle="{ color: '#FFF', fontSize: '32rpx' }" />
		<!-- Project Header -->
		<view class="project-header">
			<text class="project-title">{{proName}}</text>
			<!-- <view class="completion-rates">
				<text>作业计划完成率：70%</text>
				<text>月作业计划完成率：70%</text>
			</view> -->
		</view>

		<!-- Total Plan Input -->
		<view class="total-plan">
			<text>计划作业人数：</text>
			<input type="number" v-model="totalPlan" class="total-input" />
		</view>

		<!-- Project Table -->
		<view class="table-container">
			<view class="table-header">
				<text class="col-index">序号</text>
				<text class="col-name">项目名称</text>
				<text class="col-desc">项目描述</text>
				<text class="col-completion">本日计划完成量</text>
			</view>

			<view class="table-body">
				<view v-for="(item, index) in tableData" :key="index" class="table-row">
					<text class="col-index">{{ index + 1 }}</text>
					<text class="col-name">{{ item.taskName }}</text>
					<view class="col-desc">
						<text>{{ item.taskContent }}</text>
					</view>
					<view class="col-completion">
						<input type="number" v-model="item.completeNumDay" class="completion-input" />
					</view>

					<input type="hidden" name="totalId" :value="item.totalId" class="hidden-input">
					<input type="hidden" name="contentId" :value="item.contentId" class="hidden-input">
					<input type="hidden" name="monthId" :value="item.monthId" class="hidden-input">
					<input type="hidden" name="monthContentId" :value="item.monthContentId" class="hidden-input">
				</view>
			</view>
		</view>

		<!-- Save Button -->
		<view class="save-button-container">
			<button type="primary" @click="saveData">保存</button>
		</view>
	</view>
</template>

<script>
	function getTomorrowDate() {
		const today = new Date();
		const tomorrow = new Date(today);
		tomorrow.setDate(tomorrow.getDate() + 1);
		const year = tomorrow.getFullYear();
		const month = String(tomorrow.getMonth() + 1).padStart(2, '0');
		const day = String(tomorrow.getDate()).padStart(2, '0');
		return `${year}-${month}-${day}`;
	}

	import config from '@/config'

	export default {
		onLoad(options) {
			console.log('Received parameters:', options); // { proId: '...', currentDate: '...' }
			// 将接收到的参数保存到 data 或其他地方
			this.proId = decodeURIComponent(options.proId);
			this.proName = decodeURIComponent(options.proName);
			this.id = decodeURIComponent(options.id);
			this.currentDate = '2024-11-02';
			// 其他初始化逻辑...
			this.getListTable()
		},

		data() {
			return {
				proId: '',
				currentDate: '',
				proName: '',
				totalPlan: '',
				tableData: [],
				needPersonNum: ''
			}
		},

		methods: {
			getListTable() {
				let param = {
					proId: this.proId,
					day: this.currentDate,
					id: this.id
				}
				uni.request({
					url: config.lpBmwUrl + '/bmw/workPlanDay/getPlanDetailById',
					method: 'post',
					data: JSON.stringify(param),
					header: {
						'content-type': 'application/json',
						'Authorization': uni.getStorageSync('realNameToken')
					},
					success: res => {
						console.log('日计划制定', res)
						if (res.data.code == 200) {
							this.needPersonNum = res.data.data.needPersonNum;
							this.tableData = res.data.data.contentList;
						} else {
							uni.$u.toast(res.data.msg);
						}
					},
					fail: err => {
						console.log(err)
					}
				})
			},

			saveData() {
				const planWorkNum = Number(this.totalPlan) || 0;
				const needPersonNum = Number(this.needPersonNum) || 0;

				if (planWorkNum > needPersonNum) {
					uni.showToast({
						icon: 'none',
						title: '计划作业人数不能大于预估投入人员数'
					});
					return;
				}
				let isValid = true;
				let errorMessage = '';

				this.tableData.forEach((item, index) => {
					const totalNum = item.totalNum;
					console.log("totalNum",totalNum)
					
					const completeNumAllDay = Number(item.completeNumDay) || 0;
					console.log("completeNumAllDay",completeNumAllDay)
					
					const completeNumDay = item.completeNumDay;
					console.log("completeNumDay",completeNumDay)
					
					if (completeNumDay + completeNumAllDay > totalNum) {
						isValid = false;
						errorMessage += `第 ${index + 1} 行: 本日计划完成量 + 本月已定计划量 不能大于 本月计划量\n`;
					}
				});

				if (!isValid) {
					uni.showModal({
						title: '验证错误',
						content: errorMessage,
						showCancel: false
					});
					return;
				}

				// 收集所有数据
				const members = this.tableData.map(item => ({
					taskName: item.taskName,
					taskContent: item.taskContent,
					totalNum: item.totalNum,
					completeNum: item.completeNum,
					completeNumMonth: item.completeNumMonth,
					completeNumAllMonth: item.completeNumAllMonth,
					completeNumAllDay: item.completeNumAllDay,
					completeNumDay: item.completeNumDay,
					monthId: item.monthId,
					monthContentId: item.monthContentId,
					totalId: item.totalId,
					contentId: item.contentId
				}));

				const allData = {
					totalId: this.tableData[0]?.totalId || '',
					day: this.currentDate,
					monthId: this.tableData[0]?.monthId || '',
					needPersonNum: this.needPersonNum,
					planWorkNum: this.totalPlan,
					contentList: members
				};

				console.log("allData:", allData);
				// 提交数据
				this.uploadData(allData);
			},
			uploadData(data) {

				// 检查计划作业人数是否为空
				if (this.totalPlan === null || this.totalPlan <= 0) {
					uni.showToast({
						icon: 'none',
						title: '请填写有效的计划作业人数'
					});
					return;
				}

				// 检查本日计划完成量是否为空
				const incompleteTasks = this.tableData.filter(item => item.completeNumDay == null || item.completeNumDay < 0);
				if (incompleteTasks.length > 0) {
					uni.showToast({
						icon: 'none',
						title: '请确保所有任务都有有效的本日计划完成量'
					});
					return;
				}
				console.log("data",data)
				
				uni.request({
					url: config.lpBmwUrl + '/bmw/workPlanDay/add',
					method: 'post',
					data: JSON.stringify(data),
					header: {
						'content-type': 'application/json',
						'Authorization': uni.getStorageSync('realNameToken')
					},
					success: res => {
						console.log('日计划制定', res)
						if (res.data.code == 200) {
							// 模拟保存成功后提示用户
							uni.showToast({
							    icon: 'success',
							    title: '保存成功',
							    duration: 2000, // 提示框显示时间，单位为毫秒
							    success: () => {
							      setTimeout(() => {
							        this.leftClick(); // 在提示框消失后返回上一级页面
							      }, 2000); // 确保与duration一致
							    }
							  });
						} else {
							uni.$u.toast(res.data.msg);
						}
					},
					fail: err => {
						console.log(err)
					}
				})

				
			},

			// 返回
			leftClick() {
				console.log('返回')
				uni.navigateBack({
					delta: 1 // 返回
				});
			}
		}
	}
</script>

<style>
	.container {
		padding: 30rpx;
		background-color: #fff;
	}

	.project-header {
		margin-bottom: 30rpx;
	}

	.project-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.completion-rates {
		display: flex;
		justify-content: space-between;
		color: #666;
		font-size: 28rpx;
	}

	.total-plan {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		font-size: 28rpx;
	}

	.total-input {
		width: 200rpx;
		height: 60rpx;
		border: 1px solid #ddd;
		padding: 0 20rpx;
		margin-left: 20rpx;
	}

	.table-container {
		border: 1px solid #ddd;
	}

	.table-header {
		display: flex;
		background-color: #f5f5f5;
		padding: 20rpx;
		font-size: 28rpx;
		font-weight: bold;
		border-bottom: 1px solid #ddd;
	}

	.table-body {
		background-color: #fff;
	}

	.table-row {
		display: flex;
		padding: 20rpx;
		font-size: 28rpx;
		border-bottom: 1px solid #ddd;
		align-items: center;
	}

	/* 隔行变色 */
	.table-row:nth-child(even) {
		background-color: #fafafa;
	}

	.table-row:last-child {
		border-bottom: none;
	}

	.col-index {
		width: 80rpx;
		flex-shrink: 0;
	}

	.col-name {
		width: 200rpx;
		flex-shrink: 0;
	}

	.col-desc {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.col-completion {
		width: 200rpx;
		flex-shrink: 0;
		box-sizing: border-box;
		padding: 0 10rpx;
	}

	.completion-input {
		width: 100%;
		height: 60rpx;
		border: 1px solid #ddd;
		padding: 0 10rpx;
		box-sizing: border-box;
		font-size: 28rpx;
	}

	input {
		background-color: #fff;
	}

	/* 确保隐藏输入字段 */
	.hidden-input {
		display: none;
	}
</style>