<template>
	<view class="container">

		<view class="form-card">
			<view class="form-content">
				<u-form :model="formData" ref="form" :rules="rules" @submit="handleFormSubmit" labelPosition="top"
					labelWidth="200">
					<!-- 拓客活动 -->
					<u-form-item label="拓客活动" prop="eventId" required>
						<u-picker :show="showEventPicker" :columns="[eventList]" @confirm="onEventConfirm"
							@cancel="showEventPicker = false" @close="showEventPicker = false"></u-picker>
						<view class="picker-trigger" @click="showEventPicker = true">
							<text class="picker-text">{{ selectedEventName || '请选择拓客活动' }}</text>
							<u-icon name="arrow-down" size="16" color="#6a9c6a"></u-icon>
						</view>
					</u-form-item>

					<!-- 顾客姓名 -->
					<u-form-item label="顾客姓名" prop="customerName" required>
						<u-input v-model="formData.customerName" placeholder="请输入顾客姓名" border="none"
							:customStyle="inputStyle"></u-input>
					</u-form-item>

					<!-- 电话号码 -->
					<u-form-item label="电话号码" prop="customerPhone" required>
						<u-input v-model="formData.customerPhone" placeholder="请输入电话号码" type="number" border="none"
							:customStyle="inputStyle"></u-input>
					</u-form-item>

					<!-- 支付方式 -->
					<u-form-item label="支付方式" prop="paymentMethod" required>
						<u-picker :show="showPaymentPicker" :columns="[paymentOptions]" @confirm="onPaymentConfirm"
							@cancel="showPaymentPicker = false" @close="showPaymentPicker = false"></u-picker>
						<view class="picker-trigger" @click="showPaymentPicker = true">
							<text class="picker-text">{{ formData.paymentMethod || '请选择支付方式' }}</text>
							<u-icon name="arrow-down" size="16" color="#6a9c6a"></u-icon>
						</view>
					</u-form-item>

					<!-- 是否加微信 -->
					<u-form-item label="是否加微信" prop="isAddWeChat" required>
						<u-picker :show="showWeChatPicker" :columns="[weChatOptions]" @confirm="onWeChatConfirm"
							@cancel="showWeChatPicker = false" @close="showWeChatPicker = false"></u-picker>
						<view class="picker-trigger" @click="showWeChatPicker = true">
							<text class="picker-text">{{ formData.isAddWeChat || '请选择是否加微信' }}</text>
							<u-icon name="arrow-down" size="16" color="#6a9c6a"></u-icon>
						</view>
					</u-form-item>

					<!-- 备注 -->
					<u-form-item label="备注" prop="remarks">
						<u-textarea v-model="formData.remarks" placeholder="请输入备注信息" border="none"
							:customStyle="textareaStyle" :height="120"></u-textarea>
					</u-form-item>

					<!-- 提交按钮 -->
					<u-button type="primary" :loading="loading" :disabled="loading" @click="loading?null:handleFormSubmit()"
						:customStyle="buttonStyle">
						{{ loading ? '提交中...' : '保存' }}
					</u-button>
				</u-form>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'

	export default {
		data() {
			return {
				loading: false,
				userInfo: null,
				currentEventId: null,
				eventList: [],
				formData: {
					eventId: '',
					customerName: '',
					customerPhone: '',
					paymentMethod: '微信',
					isAddWeChat: '否',
					remarks: ''
				},
				// 选择器相关
				showEventPicker: false,
				showPaymentPicker: false,
				showWeChatPicker: false,
				selectedEventName: '',
				// 选择器选项
				paymentOptions: [{
						text: '微信',
						value: '微信'
					},
					{
						text: '支付宝',
						value: '支付宝'
					},
					{
						text: '现金',
						value: '现金'
					},
					{
						text: '银行转账',
						value: '银行转账'
					}
				],
				weChatOptions: [{
						text: '是',
						value: '是'
					},
					{
						text: '否',
						value: '否'
					}
				],
				// 表单验证规则
				rules: {
					eventId: [{
						required: true,
						message: '请选择拓客活动',
						trigger: 'change'
					}],
					customerName: [{
						required: true,
						message: '请输入顾客姓名',
						trigger: 'blur'
					}],
					customerPhone: [{
							required: true,
							message: '请输入电话号码',
							trigger: 'blur'
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '请输入正确的手机号码',
							trigger: 'blur'
						}
					],
					paymentMethod: [{
						required: true,
						message: '请选择支付方式',
						trigger: 'change'
					}],
					isAddWeChat: [{
						required: true,
						message: '请选择是否加微信',
						trigger: 'change'
					}]
				},
				// 样式配置
				inputStyle: {
					backgroundColor: '#f9fff9',
					border: '3rpx solid #c8e6c9',
					borderRadius: '20rpx',
					padding: '24rpx',
					fontSize: '28rpx',
					color: '#2e7d32'
				},
				textareaStyle: {
					backgroundColor: '#f9fff9',
					border: '3rpx solid #c8e6c9',
					borderRadius: '20rpx',
					padding: '32rpx',
					fontSize: '28rpx',
					color: '#2e7d32'
				},
				buttonStyle: {
					width: '100%',
					height: '80rpx',
					borderRadius: '24rpx',
					fontSize: '32rpx',
					fontWeight: '600',
					letterSpacing: '2rpx',
					background: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
					boxShadow: '0 8rpx 32rpx rgba(67, 233, 123, 0.3)',
					marginTop: '64rpx',
					borderColor: 'rgba(67, 233, 123, 0.3)'
				}
			}
		},

		onLoad() {
			this.initializePage()
		},

		methods: {
			// 初始化页面
			async initializePage() {
				try {
					// 获取当前登录用户
					this.userInfo = uni.getStorageSync('userInfo')
					if (!this.userInfo || Object.keys(this.userInfo).length === 0) {
						uni.reLaunch({
							url: '/pages/login/login'
						})
						return
					}
					console.log('用户信息:', this.userInfo)

					// 设置默认时间
					this.setDefaultDateTime()

					// 获取当前活动
					await this.getCurrentEvent()
				} catch (error) {
					console.error('页面初始化失败:', error)
					uni.showToast({
						title: '页面初始化失败，请刷新重试',
						icon: 'none',
						duration: 3000
					})
				}
			},

			// 设置默认时间
			setDefaultDateTime() {
				// 设置默认支付方式
				this.formData.paymentMethod = '微信'
				// 设置默认是否加微信
				this.formData.isAddWeChat = '否'
			},

			// 获取当前活动
			async getCurrentEvent() {
				try {
					const res = await this.API.getCurrentEvent(this.userInfo.userId)
					if (res.code === 200 && res.data && res.data.length > 0) {
						// 填充活动下拉选项，适配 u-picker 格式
						this.eventList = res.data.map(event => ({
							text: event.EventName,
							value: event.EventId
						}))

						// 默认选择第一个活动
						if (res.data.length > 0) {
							this.currentEventId = res.data[0].EventId
							this.formData.eventId = this.currentEventId
							this.selectedEventName = res.data[0].EventName
							console.log('当前活动ID:', this.currentEventId)
						}
					} else {
						console.warn('未找到当前活动')
					}
				} catch (error) {
					console.error('获取当前活动失败:', error)
				}
			},

			// 表单验证
			async validateForm() {
				const errors = []

				// 验证必填字段
				if (!this.formData.eventId) {
					errors.push('请选择拓客活动')
				}

				if (!this.formData.customerName.trim()) {
					errors.push('请输入顾客姓名')
				}

				const phoneNumber = this.formData.customerPhone.trim()
				if (!phoneNumber) {
					errors.push('请输入电话号码')
				} else {
					// 验证手机号格式
					const phoneRegex = /^1[3-9]\d{9}$/
					if (!phoneRegex.test(phoneNumber)) {
						errors.push('请输入正确的手机号码')
					}
				}

				if (!this.formData.paymentMethod) {
					errors.push('请选择支付方式')
				}
				if (!this.formData.isAddWeChat) {
					errors.push('请选择是否加微信')
				}

				return errors
			},

			// 收集表单数据
			collectFormData() {
				return {
					expansionTime: null,
					customerName: this.formData.customerName.trim(),
					customerPhone: this.formData.customerPhone.trim(),
					buyNumber: 1,
					paymentMethod: this.formData.paymentMethod,
					isAddWeChat: this.formData.isAddWeChat,
					remarks: this.formData.remarks.trim(),
					expansionUserId: this.userInfo.userId,
					eventId: this.formData.eventId
				}
			},

			// 选择器确认方法
			onEventConfirm(e) {
				const {
					value
				} = e
				this.formData.eventId = value[0].value
				this.selectedEventName = value[0].text
				this.showEventPicker = false
			},

			onPaymentConfirm(e) {
				const {
					value
				} = e
				this.formData.paymentMethod = value[0].value
				this.showPaymentPicker = false
			},

			onWeChatConfirm(e) {
				const {
					value
				} = e
				this.formData.isAddWeChat = value[0].value
				this.showWeChatPicker = false
			},

			// 处理表单提交
			async handleFormSubmit() {
				console.error('【【【【【【')
				try {
					// 使用 uview 表单验证
					await this.$refs.form.validate()

					// 收集表单数据
					const formData = this.collectFormData()
					console.log('表单数据:', formData)

					// 提交数据
					await this.submitExpansion(formData)
				} catch (error) {
					console.log('表单验证失败:', error)
				}
			},

			// 提交扩展邀约数据
			async submitExpansion(data) {
				try {
					uni.showLoading({
						title: '正在提交...'
					})
					this.loading = true
					const res1 = await this.API.getEvent(data.eventId)
					let pushUrl = res1.data && res1.data.pushUrl ? res1.data.pushUrl : ''
					// console.error(pushUrl)
					// return
					const res = await this.API.submitExpansion(data)

					if (res.code === 200 && res.data && res.data.entity) {
						let tkinfo = res.data

						// return
						// 发送微信通知
						await this.sendWeChatNotification(tkinfo, data, pushUrl)

					} else {
						uni.hideLoading()
						uni.showToast({
							title: `添加失败：${res.data?.Message || '未知错误'}`,
							icon: 'none',
							duration: 3000
						})
						this.loading = false
					}
				} catch (error) {
					console.error('提交失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none',
						duration: 3000
					})
					this.loading = false
				}
			},

			// 发送微信通知
			async sendWeChatNotification(tkinfo, data, pushUrl) {
				try {
					// 格式化时间
					const formatTime = (timestamp) => {
						const date = new Date(timestamp)
						return uni.$u.timeFormat(date,'yyyy/mm/dd hh:MM')
					}

					const datanew = {
						"webhookUrl": pushUrl ||
							'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=581c22a6-cb67-42e5-8c76-b8e90052e188',
						// "webhookUrl": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=496f1add-122b-43fc-9e38-0ca79c48b33f",
						// 测试地址
						// "webhookUrl":"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6f8686ec-5011-4c1d-bae9-d82a2a2f4d83",
						"content": `🎉 拓客记录
⏩门店：${tkinfo.storeinfo?.Dm || '未知'}
⏩拓客人员：${this.userInfo.userName || '未知'}
⏩战队：${tkinfo.entity?.TeamName || '未知'}
⏩顾客姓名：${data.customerName}
⏩电话号码：${data.customerPhone}
⏩购买张数：${data.buyNumber}
⏩拓客时间：${formatTime(tkinfo.entity?.ExpansionTime)}
⏩支付方式：${data.paymentMethod}
⏩是否加微信：${data.isAddWeChat}
⏩备注：${data.remarks || ''}`
					}

					// 发送通知
					await this.API.sendWeChatNotification(datanew)
					uni.hideLoading()
					uni.showToast({
						title: '拓客数据提交成功！',
						icon: 'success',
						duration: 2000
					})
					this.loading = false
					// 清空表单
					this.clearForm()
				} catch (error) {
					console.error('发送微信通知失败:', error)
				}
			},

			// 清空表单
			clearForm() {
				try {
					// 重置表单
					this.formData = {
						eventId: this.currentEventId || '',
						customerName: '',
						customerPhone: '',
						paymentMethod: '微信',
						isAddWeChat: '否',
						remarks: ''
					}

					// 重置选择器显示名称
					if (this.currentEventId && this.eventList.length > 0) {
						const currentEvent = this.eventList.find(event => event.value === this.currentEventId)
						this.selectedEventName = currentEvent ? currentEvent.text : ''
					} else {
						this.selectedEventName = ''
					}

					// 清除表单验证
					this.$refs.form && this.$refs.form.clearValidate()

					console.log('表单已清空')
				} catch (error) {
					console.error('清空表单失败:', error)
				}
			},


		}
	}
</script>

<style lang="scss" scoped>
	*,
	*::before,
	*::after {
		box-sizing: border-box;
	}

	.container {
		font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
		margin: 0;
		height: 100vh;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		padding: 40rpx;
		width: 100%;
		box-sizing: border-box;
		overflow-y: scroll;
	}

	.page-title {
		text-align: center;
		color: #388e3c;
		margin-bottom: 36rpx;
		letter-spacing: 4rpx;
		font-size: 36rpx;
		font-weight: bold;
	}

	.form-card {
		background: #fff;
		border-radius: 40rpx;
		box-shadow: 0 16rpx 64rpx 0 rgba(76, 175, 80, 0.15);
		border: 2rpx solid #e8f5e9;
		overflow: hidden;
	}

	.form-content {
		padding: 64rpx;
		box-sizing: border-box;
	}

	.form-group {
		margin-bottom: 48rpx;
	}

	.form-group:last-child {
		margin-bottom: 0;
	}

	label {
		display: block;
		margin-bottom: 20rpx;
		font-weight: 600;
		color: #2e7d32;
		letter-spacing: 1rpx;
		font-size: 28rpx;
	}

	.input-wrapper {
		position: relative;
	}

	.input-icon {
		position: absolute;
		left: 24rpx;
		top: 50%;
		transform: translateY(-50%);
		width: 40rpx;
		height: 40rpx;
		color: #6a9c6a;
	}

	input,
	textarea,
	select,
	.form-select {
		width: 100%;
		padding: 24rpx;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		font-size: 28rpx;
		transition: all 0.2s ease;
		background: #f9fff9;
		color: #2e7d32;
		font-family: inherit;
		box-sizing: border-box;
	}

	textarea {
		min-height: 200rpx;
		resize: vertical;
		padding: 32rpx;
		line-height: 1.5;
	}

	select {
		cursor: pointer;
		background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236a9c6a' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
		background-position: right 24rpx center;
		background-repeat: no-repeat;
		background-size: 32rpx;
		padding-right: 80rpx;
		appearance: none;
		-webkit-appearance: none;
		-moz-appearance: none;
	}

	select:focus {
		outline: none;
		border-color: #43a047;
		box-shadow: 0 0 0 6rpx rgba(76, 175, 80, 0.1);
		background-color: #fff;
	}

	input:focus,
	textarea:focus,
	select:focus,
	.form-select:focus {
		outline: none;
		border-color: #43a047;
		box-shadow: 0 0 0 6rpx rgba(76, 175, 80, 0.1);
		background: #fff;
	}

	input:disabled {
		background: #f5f5f5;
		color: #666;
		cursor: not-allowed;
	}



	.btn {
		width: 100%;
		padding: 32rpx 40rpx;
		border: none;
		border-radius: 24rpx;
		font-size: 32rpx;
		font-weight: 600;
		cursor: pointer;
		transition: all 0.3s ease;
		letter-spacing: 2rpx;
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
		box-shadow: 0 8rpx 32rpx rgba(67, 233, 123, 0.3);
		margin-top: 64rpx;
	}

	.btn:hover {
		box-shadow: 0 12rpx 48rpx rgba(67, 233, 123, 0.4);
		transform: translateY(-4rpx);
	}

	.btn:active {
		transform: translateY(0);
	}

	.picker-trigger {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		padding: 24rpx;
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		font-size: 28rpx;
		color: #2e7d32;
		transition: all 0.2s ease;
		box-sizing: border-box;
	}

	.picker-trigger:active {
		border-color: #43a047;
		box-shadow: 0 0 0 6rpx rgba(76, 175, 80, 0.1);
		background: #fff;
	}

	.picker-text {
		flex: 1;
		color: #2e7d32;
	}


	// @media (max-width: 1040rpx) {
	// 	.container {
	// 		max-width: 100%;
	// 	}

	// 	.form-content {
	// 		padding: 48rpx;
	// 	}

	// 	.form-group {
	// 		margin-bottom: 40rpx;
	// 	}

	// 	.btn {
	// 		margin-top: 48rpx;
	// 	}
	// }
</style>