<template>
	<view class="container">
		<Step :step="currentStep" :stepsData="currentText" />

		<scroll-view class="content" scroll-y>
			<!-- 客户积分设置列表 -->
			<view class="integral-section">
				<view class="section-header">
					<view class="section-title">客户姓名</view>
					<view class="section-subtitle">积分数值</view>
				</view>

				<view class="integral-list">
					<view class="integral-item" v-for="(customer, index) in customerList" :key="customer.id">
						<view class="customer-info">
							<view class="customer-name">{{ customer.name }}</view>
						</view>
						<view class="integral-input-wrapper">
							<input class="integral-input" type="number" :placeholder="customer.placeholder"
								v-model="customer.integral" :disabled="customer.disabled"
								@input="onIntegralInput(customer)" />
							<view v-if="customer.integral" class="clear-icon-wrapper"
								@click.stop="clearIntegral(customer)">
								<image class="clear-icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_clear.png"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 概览悬浮按钮 -->
		<view class="suspension" @click="showOverviewPopup">概览</view>

		<!-- 概览弹窗 -->
		<!-- :show="showOverview" -->
		<u-popup :show="showOverview" mode="bottom" @close="closeOverviewPopup" round="20" :safeAreaInsetBottom="true">
			<view class="overview-popup">
				<!-- 弹窗头部 -->
				<view class="popup-header">
					<text class="popup-title">概览</text>
					<view class="close-btn" @click="closeOverviewPopup">
						<image class="close-icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_close.png"></image>
					</view>
				</view>

				<!-- 任务信息 -->
				<view class="overview-section">
					<view class="row">
						<text class="line"></text>
						<view class="section-title">任务信息</view>
					</view>
					<view class="info-list">
						<view class="info-item">
							<view class="info-label">项目归属：</view>
							<view class="info-value">湖南省药学服务公司</view>
						</view>
						<view class="info-item">
							<view class="info-label">项目任务：</view>
							<view class="info-value">科普文章</view>
						</view>
						<view class="info-item">
							<view class="info-label">项目时间：</view>
							<view class="info-value">2025/11/19 14:12~2025/11/19 14:12</view>
						</view>
					</view>
				</view>

				<!-- 客户信息 -->
				<view class="overview-section">
					<view class="row">
						<text class="line"></text>
						<view class="section-title">客户信息</view>
					</view>
					<view class="customer-table">
						<!-- 表头 -->
						<view class="table-header">
							<view class="table-cell" style="flex: 1.5;">姓名</view>
							<view class="table-cell" style="flex: 1;">级别</view>
							<view class="table-cell" style="flex: 1;">积分</view>
							<view class="table-cell" style="flex: 2;">联系方式</view>
						</view>

						<!-- 表格内容 -->
						<view class="table-body">
							<view class="table-row" v-for="(customer, index) in customerList" :key="customer.id">
								<view class="table-cell" style="flex: 1.5;">{{ customer.name }}</view>
								<view class="table-cell" style="flex: 1;">一级</view>
								<view class="table-cell" style="flex: 1;">{{ customer.integral || '0' }}</view>
								<view class="table-cell" style="flex: 2;">177****4235</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 安全区域占位 -->
				<view class="safe-area"></view>
			</view>
		</u-popup>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="del-box" @click="deleteSelected">
				<image class="w40 h40" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_delete.png"></image>
				<text>删除</text>
			</view>
			<view class="action-buttons">
				<view class="btn btn-cancel" @click="handlePrev">上一步</view>
				<view class="btn btn-submit" @click="submit">提交</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Step from '@/pages_task/components/step.vue'
	import { addInfo} from '@/api/task.js';
	export default {
		components: {
			Step
		},
		data() {
				return {
					currentText: [{
							id: 1,
							stepNumber: 1,
							title: '填写任务'
						},
						{
							id: 2,
							stepNumber: 2,
							title: '选择客户'
						},
						{
							id: 3,
							stepNumber: 3,
							title: '积分设置'
						}
					],
					currentStep: 3,
					showOverview: false, // 控制概览弹窗显示
					customerList: []
				}
			},
			onLoad() {
				// 从本地存储中获取选中的客户数据
				const selectedCustomersData = uni.getStorageSync('selectedCustomers')
				if (selectedCustomersData) {
					try {
						const selectedCustomers = typeof selectedCustomersData === 'string' ? JSON.parse(selectedCustomersData) : selectedCustomersData
						// 确保selectedCustomers是数组
						if (Array.isArray(selectedCustomers)) {
							// 将选中的客户数据转换为积分设置需要的格式
							this.customerList = selectedCustomers.map(customer => ({
								id: customer.id,
								name: customer.doctorName || '未知姓名',
								doctorName: customer.doctorName || '未知姓名',
								integral: '',
								placeholder: '请输入积分',
								disabled: false
							}))
						}
					} catch (e) {
						console.error('解析客户数据失败:', e)
					}
				}
			},
		computed: {
			totalIntegral() {
				let total = 0
				this.customerList.forEach(customer => {
					const integral = parseInt(customer.integral) || 0
					total += integral
				})
				return total
			}
		},
		methods: {
			
			// 显示概览弹窗
			showOverviewPopup() {
				this.showOverview = true
			},

			// 关闭概览弹窗
			closeOverviewPopup() {
				this.showOverview = false
			},

			clearIntegral(customer) {
				// 使用 $set 确保响应式更新
				this.$set(customer, 'integral', '')
			},
			onIntegralInput(customer) {
				// 积分输入验证
				if (customer.integral && parseInt(customer.integral) < 0) {
					this.$set(customer, 'integral', '0')
				}
			},
			handlePrev() {
				uni.navigateBack()
			},
			submit() {
					// 验证所有客户积分是否已填写
					const emptyCustomers = this.customerList.filter(customer => !customer.integral || customer.integral === '')
					if (emptyCustomers.length > 0) {
						uni.showToast({
							icon: 'none',
							title: '请为所有客户设置积分'
						})
						return
					}

					// 验证积分是否为数字
					const invalidCustomers = this.customerList.filter(customer => {
						const integral = parseInt(customer.integral)
						return isNaN(integral) || integral < 0
					})

					if (invalidCustomers.length > 0) {
						uni.showToast({
							icon: 'none',
							title: '请输入有效的积分数值'
						})
						return
					}

					// 获取所有三个页面的数据
					const taskFormDataStr = uni.getStorageSync('taskFormData')
					const selectedCustomersStr = uni.getStorageSync('selectedCustomers')
					const taskFormData = taskFormDataStr ? JSON.parse(taskFormDataStr) : {}
					const selectedCustomers = selectedCustomersStr ? JSON.parse(selectedCustomersStr) : []
					
					// 获取用户信息
					const userInfoData = uni.getStorageSync('userInfo')
					const userInfo = typeof userInfoData === 'string' ? JSON.parse(userInfoData) : userInfoData || {}
					
					// 获取当前时间
					const now = new Date()
					const applyTime = now.toISOString().slice(0, 19).replace('T', ' ')

					// 构建提交数据
					const taskData = {
						// 任务基本信息
						// taskName: taskFormData.taskName || '',
						deptId: taskFormData.deptId || 0,
						projectId: taskFormData.projectId || 0,
						costShareId: taskFormData.costShareId || 0,
						taskType: taskFormData.taskType || 0,
						taskIntegral: this.totalIntegral || 0,
						taskUnit: taskFormData.taskUnit || 0,
						productId: taskFormData.productId || 0,
						planStartTime: taskFormData.planStartTime || '',
						planEndTime: taskFormData.planEndTime || '',
						// applyTime: applyTime,
						belongType: taskFormData.belongType || 0,
						companyId: userInfo.companyId || 0,
						companyUserId: userInfo.userId || 0,
						remark: taskFormData.remark || '',
						// companyUserId: taskFormData.companyUserId || 0,
						// 构建doctorIds数组
						// doctorIds: this.customerList.map(customer => parseInt(customer.id) || 0),
						// 构建doctorTaskList数组
						doctorTaskList: this.customerList.map(customer => ({
							doctorId: parseInt(customer.id) || 0,
							taskIntegral: parseInt(customer.integral) || 0
						}))
					}

					console.log('提交的任务数据:', taskData)

					// 调用addInfo接口提交表单
					uni.showLoading({
						title: '提交中...'
					})
					addInfo(taskData).then(res => {
						uni.hideLoading()
						if (res.code === 200) {
							// 清除本地存储的数据
							uni.removeStorageSync('taskFormData')
							uni.removeStorageSync('selectedCustomers')
							// 显示提交成功提示
							uni.showToast({
								title: '任务创建成功',
								success: () => {
									// 延迟跳转，让用户看到成功提示
									setTimeout(() => {
										uni.navigateTo({
											url: '/pages_task/success'
										})
									}, 1500)
								}
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: res.message || '提交失败'
							})
						}
					}).catch(err => {
						uni.hideLoading()
						uni.showToast({
							icon: 'none',
							title: '网络错误，请重试'
						})
					})
				},
			deleteSelected() {
				// 删除所有客户数据
				uni.showModal({
					title: '提示',
					content: '确定要删除所有客户数据吗？删除后不可恢复。',
					success: (res) => {
						if (res.confirm) {
							// 清空所有客户的积分数据
							this.customerList.forEach(customer => {
								this.$set(customer, 'integral', '')
							})

							uni.showToast({
								title: '已清空所有客户积分',
								icon: 'success'
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: #F7F8FA;
		display: flex;
		flex-direction: column;

		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			width: 100%;
			height: 544rpx;
			background: linear-gradient(180deg, #E4EFFE 0%, rgba(228, 239, 254, 0) 100%);
		}
	}

	.content {
		flex: 1;
		padding: 24rpx;
		box-sizing: border-box;
		padding-bottom: 200rpx;
		position: relative;
	}

	.integral-section {
		background-color: #ffffff;
		border-radius: 24rpx;
		padding: 32rpx 24rpx;
		margin-bottom: 24rpx;

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 32rpx;
			padding: 32rpx 0;
			background: #F5F9FF;
			border-radius: 16rpx;
			font-size: 28rpx;
			color: #666666;
			text-align: center;
			font-weight: 600;

			.section-title {
				flex: 1;
			}

			.section-subtitle {
				flex: 1;
			}
		}

		.integral-list {
			.integral-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 32rpx 0;
				border-bottom: 1rpx solid #F2F3F5;

				&:last-child {
					border-bottom: none;
				}

				.customer-info {
					flex: 1;
					text-align: center;

					.customer-name {
						font-size: 32rpx;
						font-weight: 500;
						color: #333333;
					}
				}

				.integral-input-wrapper {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: center;
					position: relative;

					.integral-input {
						width: 100%;
						font-size: 32rpx;
						color: #333333;
						text-align: center;
						padding: 12rpx 60rpx 12rpx 16rpx;
						background: #F7F8FA;
						border-radius: 8rpx;

						&::placeholder {
							color: #C8C9CC;
							font-size: 28rpx;
							text-align: center;
						}

						&:disabled {
							background: transparent;
							opacity: 0.8;
						}
					}

					.clear-icon-wrapper {
						position: absolute;
						right: 8rpx;
						width: 48rpx;
						height: 48rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						z-index: 10;
						cursor: pointer;

						&:active {
							opacity: 0.6;
						}

						.clear-icon {
							width: 28rpx;
							height: 28rpx;
						}
					}
				}
			}
		}
	}

	.suspension {
		position: fixed;
		text-align: center;
		line-height: 96rpx;
		right: 36rpx;
		top: 70%;
		width: 96rpx;
		height: 96rpx;
		background: linear-gradient(0deg, #388BFF 0%, #388BFF 100%);
		box-shadow: inset 0rpx 4rpx 8rpx 0rpx rgba(255, 255, 255, 0.25),
			inset 0rpx -6rpx 8rpx 0rpx rgba(255, 255, 255, 0.25),
			4rpx 8rpx 12rpx 0rpx rgba(88, 144, 239, 0.29);
		border-radius: 110rpx;
		font-size: 28rpx;
		color: #FFFFFF;
		z-index: 999;
		cursor: pointer;

		&:active {
			opacity: 0.8;
		}
	}

	/* 概览弹窗样式 */
	.overview-popup {
		background-color: #fff;
		border-radius: 32rpx 32rpx 0 0;
		max-height: 80vh;
		overflow-y: auto;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.popup-header {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 32rpx 40rpx;
		.popup-title {
			font-weight: 500;
			font-size: 32rpx;
			color: #333333;
			
		}

		.close-btn {
			width: 48rpx;
			height: 48rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			position: absolute;
			right: 0;

			.close-icon {
				width: 44rpx;
				height: 44rpx;
				margin-right: 32rpx;
				flex-shrink: 0;
			}

			&:active {
				opacity: 0.6;
			}
		}
	}

	.overview-section {
		padding: 32rpx 40rpx;

		.row {
			display: flex;
			align-items: center;
			margin-bottom: 24rpx;

			&:last-child {
				border-bottom: none;
			}

			.line {
				width: 6rpx;
				height: 32rpx;
				background: #388BFF;
				border-radius: 36rpx;
				margin-right: 20rpx;
			}

			.section-title {
				font-size: 28rpx;
				font-weight: 600;
				color: #333333;
			}
		}





		.info-list {
			.info-item {
				display: flex;
				margin-bottom: 16rpx;
				align-items: flex-start;
				font-size: 28rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.info-label {
					color: #999999;
					flex-shrink: 0;
					width: 140rpx;
				}

				.info-value {
					color: #333333;
					flex: 1;
					line-height: 1.4;
				}
			}
		}

		.customer-table {
			.table-header {
				display: flex;
				background: #F5F9FF;
				border-radius: 8rpx;
				padding: 20rpx 16rpx;
				margin-bottom: 8rpx;

				.table-cell {
					font-size: 24rpx;
					font-weight: 600;
					color: #666666;
					text-align: center;
				}
			}

			.table-body {
				.table-row {
					display: flex;
					padding: 20rpx 16rpx;
					border-bottom: 1rpx solid #F2F3F5;

					&:last-child {
						border-bottom: none;
					}

					.table-cell {
						font-size: 28rpx;
						color: #333333;
						text-align: center;

						&:first-child {
							font-weight: 500;
						}
					}
				}
			}
		}
	}

	.total-section {
		padding: 32rpx 40rpx;
		background: #F5F9FF;
		border-radius: 16rpx;
		margin: 24rpx 40rpx 40rpx;

		.total-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.total-label {
				font-size: 28rpx;
				color: #666666;
			}

			.total-value {
				font-size: 28rpx;
				font-weight: 600;
				color: #388BFF;
			}
		}
	}

	.safe-area {
		height: env(safe-area-inset-bottom);
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #fff;
		padding: 24rpx 32rpx;
		border-top: 1rpx solid #F2F3F5;
		z-index: 100;
		display: flex;
		align-items: center;

		.del-box {
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: 24rpx;
			color: #666666;
			margin-right: 32rpx;
			cursor: pointer;

			&:active {
				opacity: 0.6;
			}
		}

		.action-buttons {
			display: flex;
			flex: 1;
			justify-content: space-between;

			.btn {
				width: 292rpx;
				height: 88rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
				font-weight: 500;
				border-radius: 200rpx 200rpx 200rpx 200rpx;
				cursor: pointer;

				&.btn-cancel {
					background: #fff;
					border: 2rpx solid #388BFF;
					color: #388BFF;
				}

				&.btn-submit {
					background: #388BFF;
					color: #fff;
				}
			}
		}
	}

	.w40 {
		width: 40rpx;
	}

	.h40 {
		height: 40rpx;
	}
</style>