<template>
	<view class="oder_form_wrap">
		<u-navbar placeholder :autoBack="true" title="发单表单">

		</u-navbar>

		<view class="form_wrap">
			<u--form labelPosition="top" labelWidth="100" :model="form" :rules="rules" ref="form" class="form_wrap"
				:errorType="'toast'">
				<u-form-item label="品牌" prop="brand" class="brand_wrap">
					<BrandSelect :list="brandDict" label-key="dictLabel" value-key="dictValue" placeholder="请选择物品品牌"
						v-model="form.brand" :border="false" border></BrandSelect>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-row gutter="5" justify="space-between">
					<u-col span="6">
						<u-form-item label="型号" prop="model">
							<u--input v-model="form.model" placeholder="例如:CF小号" border="surround"></u--input>
						</u-form-item>
					</u-col>
					<u-col span="6">
						<u-form-item label="实价" prop="price">
							<u--input v-model="form.price" placeholder="0.00" border="surround"></u--input>
						</u-form-item>
					</u-col>
				</u-row>

				<u-row gutter="5" justify="space-between">
					<u-col span="6">
						<u-form-item label="客户电话" prop="phone">
							<u--input v-model="form.phone" placeholder="电话号" border="surround"></u--input>
						</u-form-item>
					</u-col>
					<u-col span="6">
						<u-form-item label="客户微信" prop="wechat">
							<u--input v-model="form.wechat" placeholder="微信号" border="surround"></u--input>
						</u-form-item>
					</u-col>
				</u-row>
				<view class="address_wrap">
					<view class="address_title">
						<u-icon name="map" color="#3b82f6" size="16"></u-icon>
						<view>地址信息</view>
					</view>
					<u-form-item label="详细地址" prop="address" class='form_card'>
						<pick-regions :defaultRegion="defaultRegion" @getRegion="handleGetRegion" clearable
							class="region-picker">
							<view>
								<template v-if="form.province">
									<u--input :value="form.province + '/' + form.city + '/' + form.area"
										placeholder="点击选择" readonly suffixIcon="arrow-right"
										suffixIconStyle="color : #c0c4cc"></u--input>
								</template>
								<template v-else>
									<u--input placeholder="点击选择" readonly suffixIcon="arrow-right"
										suffixIconStyle="color : #c0c4cc"></u--input>
								</template>
							</view>
						</pick-regions>
					</u-form-item>
					<u--textarea v-model="form.address" placeholder="粘贴地址自动识别(例如：浙江省杭州市...)" confirmType="done"
						@blur="handleAddressBlur"></u--textarea>
				</view>
				<u-form-item label="上门时间" prop="visitTime" class="visit_time_wrap">
					<date-time-picker v-model="form.visitTime" :value-format="'YYYY-MM-DD HH:mm:ss'" :type="'datetime'">
					</date-time-picker>
				</u-form-item>

				<!-- <u-form-item label="类型" prop="category" class="category_wrap"> -->
				<u-form-item label="类型" prop="category" class="brand_wrap">
					<!-- <view class="category_select_wrap"> -->
					<ld-select :list="categoryDict" label-key="dictLabel" value-key="dictValue" placeholder="请选择类型"
						v-model="form.category" :border="false"></ld-select>
					<u-icon slot="right" name="arrow-right"></u-icon>
					<!-- </view> -->
				</u-form-item>

				<u-form-item label="价格范围" prop="priceRange">
					<u--input v-model="form.priceRange" placeholder="请输入价格范围" border="surround"></u--input>
				</u-form-item>

				<u-form-item label="战术选择" prop="tactic">
					<view class="tactic-buttons">
						<view v-for="item in tacticDict" :key="item.dictValue" class="tactic-button"
							:class="{ 'active': form.tactic === item.dictValue }" @click="form.tactic = item.dictValue">
							{{ item.dictLabel }}
						</view>
					</view>
				</u-form-item>

				<u-form-item label="备注信息" prop="remarks" class="remarks_wrap">
					<u--textarea v-model="form.remarks" placeholder="填写线索来源、客户特殊要求等..." count
						confirmType="done"></u--textarea>
				</u-form-item>

			</u--form>
		</view>

		<!-- 文件上传区域 -->
		<view class="upload_area" v-if="!sendFormId">
			<!-- 聊天记录附件 -->
			<order-file-upload title="聊天记录附件" orderFileType="1" fileType="image" :file-list="form.chatAttachmentList"
				@update:fileList="updateChatFiles" tip-text="上传聊天截图、录音等文件"></order-file-upload>

			<!-- 报价附件 -->
			<order-file-upload title="报价附件" orderFileType="2" fileType="image" :file-list="form.quoteAttachmentList"
				@update:fileList="updateQuoteFiles" tip-text="上传报价附件"></order-file-upload>

			<!-- 高清图附件 -->
			<order-file-upload title="高清图附件" orderFileType="3" fileType="image" :file-list="form.hdImageAttachmentList"
				@update:fileList="updateHdImageFiles" tip-text="上传物品高清图片"></order-file-upload>

			<!-- 其他附件 -->
			<order-file-upload title="其他附件" orderFileType="4" fileType="image" :file-list="form.otherAttachmentList"
				@update:fileList="updateOtherFiles" tip-text="上传其他相关文件"></order-file-upload>
		</view>

		<u-button @click="handleNavSaveClick" type="primary">提交订单</u-button>

	</view>
</template>

<script>
import orderFileUpload from '@/components/order-file-upload/order-file-upload.vue'
import dateTimePicker from "@/components/dateTimePicker/dateTimePicker.vue"
import ldSelect from "@/components/ld-select/ld-select.vue"
import BrandSelect from "@/components/brand-select/brand-select.vue"
const CHINA_REGIONS = require('@/components/pick-regions/regions.json')
export default {
	components: {
		orderFileUpload,
		dateTimePicker,
		ldSelect,
		BrandSelect
	},
	data() {
		return {
			defaultRegion: ['广东省', '广州市', '番禺区'],
			categoryDict: [],
			tacticDict: [],
			brandDict: [],

			sendFormId: undefined,

			form: {
				clueId: '',
				sendDate: '',
				website: '',
				item: '',
				phone: '',
				wechat: '',
				address: '',
				visitTime: '',
				remarks: '',
				category: '1',
				brand: '',
				model: '',
				price: '',
				priceRange: '',
				tactic: '',
				// 地区信息
				province: '',
				city: '',
				area: '',
				// 附件列表
				chatAttachmentList: [], // 聊天记录附件
				quoteAttachmentList: [], // 报价附件
				hdImageAttachmentList: [], // 高清图附件
				otherAttachmentList: [] // 其他附件
			},

			rules: {
				sendDate: {
					type: 'string',
					required: true,
					message: '请输入发单日期',
					trigger: ['blur', 'change']
				},
				model: {
					type: 'string',
					required: true,
					message: '请输入型号',
					trigger: ['blur', 'change']
				},
				price: {
					type: 'string',
					required: true,
					message: '请输入实价',
					trigger: ['blur', 'change']
				},
				website: {
					type: 'url',
					message: '请输入正确的网址格式',
					trigger: ['blur', 'change']
				},
				item: {
					type: 'string',
					required: true,
					message: '请输入物品描述',
					trigger: ['blur', 'change']
				},
				wechat: {
					type: 'string',
					required: false,
					message: '请输入客户微信',
					trigger: ['blur', 'change']
				},
				phone: {
					type: 'string',
					required: false,
					message: '请输入联系电话',
					trigger: ['blur', 'change']
				},
				address: {
					type: 'string',
					required: true,
					message: '请输入详细地址',
					trigger: ['blur', 'change']
				},
				visitTime: {
					type: 'string',
					required: true,
					message: '请输入上门时间',
					trigger: ['blur', 'change']
				},
				category: {
					type: 'string',
					required: true,
					message: '请选择类型',
					trigger: ['blur', 'change']
				},
				brand: {
					type: 'string',
					required: true,
					message: '请选择物品品牌',
					trigger: ['blur', 'change']
				},
				tactic: {
					type: 'string',
					required: true,
					message: '请选择战术',
					trigger: ['blur', 'change']
				}
			}
		}
	},

	methods: {
		// 加载表单数据
		async loadFormData(sendFormId) {
			try {
				const res = await uni.$u.api.getClueSendFormVoByOrderId({
					id: sendFormId
				});
				if (res.code === 200) {
					this.form = res.data;
				}
			} catch (error) {
				console.error('加载表单数据失败:', error);
				uni.$u.toast('加载表单数据失败');
			}
		},

		// 获取地区选择
		handleGetRegion(region) {
			const [provinceData, cityData, areaData] = region;
			this.form.province = provinceData.name;
			this.form.city = cityData.name;
			this.form.area = areaData.name;

			// 构建完整的地区信息
			const regionText = this.form.province + this.form.city + this.form.area;

			// 检查当前地址内容是否为纯地区信息（没有具体街道等）
			const isPureRegion = !this.form.address ||
				this.form.address.trim() === '' ||
				this.form.address.trim().includes(this.form.province) ||
				this.form.address.trim().includes(this.form.city) ||
				this.form.address.trim().includes(this.form.area);

			// 如果是纯地区信息或者是空地址，则更新为选择的地区
			if (isPureRegion) {
				this.form.address = regionText;
			} else {
				// 如果有具体地址信息，保留原有地址，但更新地区部分
				// 这里可以保持原有地址不变，让用户自己选择是否更新
				// 或者可以选择性地更新地区信息
			}
		},

		// 地址失焦时自动解析地址信息
		async handleAddressBlur() {
			if (!this.form.address || !this.form.address.trim()) {
				return;
			}
			
			const address = this.form.address.trim();
			const parsedRegion = this.parseAddress(address);
			
			if (parsedRegion && parsedRegion.province) {
				this.form.province = parsedRegion.province;
				this.form.city = parsedRegion.city || '';
				this.form.area = parsedRegion.area || '';
				// 更新 defaultRegion，用于更新 pick-regions 组件的显示
				this.defaultRegion = [
					parsedRegion.province,
					parsedRegion.city || '',
					parsedRegion.area || ''
				];
			}
		},
		
		// 基于地址字典解析地址，提取省市区信息
		parseAddress(address) {
			if (!address || !CHINA_REGIONS || CHINA_REGIONS.length === 0) {
				return null;
			}
			
			let bestMatch = null;
			let bestMatchScore = 0; // 匹配分数：完整匹配得分更高
			
			// 遍历所有省份
			for (const province of CHINA_REGIONS) {
				const provinceName = province.name;
				// 移除可能的"省"、"市"、"自治区"、"特别行政区"等后缀进行匹配
				const provinceNameShort = provinceName.replace(/省|市|自治区|特别行政区|壮族自治区|维吾尔自治区|回族自治区/g, '');
				
				// 检查地址中是否包含省份名称
				const hasProvinceFull = address.includes(provinceName);
				const hasProvinceShort = address.includes(provinceNameShort);
				
				if (hasProvinceFull || hasProvinceShort) {
					// 找到省份在地址中的位置
					const provinceIndex = hasProvinceFull 
						? address.indexOf(provinceName) 
						: address.indexOf(provinceNameShort);
					
					if (provinceIndex === -1) continue;
					
					// 获取省份后的剩余地址
					const provinceMatchLength = hasProvinceFull ? provinceName.length : provinceNameShort.length;
					const remainingAfterProvince = address.substring(provinceIndex + provinceMatchLength);
					
					// 直辖市特殊处理
					const municipalities = ['北京市', '上海市', '天津市', '重庆市'];
					if (municipalities.includes(provinceName)) {
						// 直辖市：市名就是省名，直接查找区/县
						const cityName = provinceName;
						let matchedArea = null;
						let maxAreaLength = 0;
						
						// 遍历该省份下的所有市（通常是"市辖区"）
						if (province.childs && province.childs.length > 0) {
							for (const city of province.childs) {
								// 遍历该市下的所有区/县
								if (city.childs && city.childs.length > 0) {
									for (const area of city.childs) {
										const areaName = area.name;
										// 检查剩余地址中是否包含区/县名称
										if (remainingAfterProvince.includes(areaName)) {
											// 找到最长的匹配（更准确）
											if (areaName.length > maxAreaLength) {
												maxAreaLength = areaName.length;
												matchedArea = areaName;
											}
										}
									}
								}
							}
						}
						
						// 计算匹配分数：有区/县得3分，只有省市区得2分
						const matchScore = matchedArea ? 3 : 2;
						if (matchScore > bestMatchScore) {
							bestMatchScore = matchScore;
							bestMatch = {
								province: provinceName,
								city: cityName,
								area: matchedArea || ''
							};
							// 如果找到了完整的省市区，可以提前返回
							if (matchedArea) {
								return bestMatch;
							}
						}
						continue;
					}
					
					// 非直辖市：查找市
					if (province.childs && province.childs.length > 0) {
						for (const city of province.childs) {
							const cityName = city.name;
							// 移除可能的"市"、"州"、"盟"、"地区"、"自治州"等后缀
							const cityNameShort = cityName.replace(/市|州|盟|地区|自治州/g, '');
							
							// 检查剩余地址中是否包含市名称
							const hasCityFull = remainingAfterProvince.includes(cityName);
							const hasCityShort = remainingAfterProvince.includes(cityNameShort);
							
							if (hasCityFull || hasCityShort) {
								const cityIndex = hasCityFull
									? remainingAfterProvince.indexOf(cityName)
									: remainingAfterProvince.indexOf(cityNameShort);
								
								if (cityIndex === -1) continue;
								
								// 获取市后的剩余地址
								const cityMatchLength = hasCityFull ? cityName.length : cityNameShort.length;
								const remainingAfterCity = remainingAfterProvince.substring(cityIndex + cityMatchLength);
								
								// 查找区/县
								let matchedArea = null;
								let maxAreaLength = 0;
								if (city.childs && city.childs.length > 0) {
									for (const area of city.childs) {
										const areaName = area.name;
										// 检查剩余地址中是否包含区/县名称
										if (remainingAfterCity.includes(areaName)) {
											// 找到最长的匹配（更准确）
											if (areaName.length > maxAreaLength) {
												maxAreaLength = areaName.length;
												matchedArea = areaName;
											}
										}
									}
								}
								
								// 计算匹配分数：完整省市区得3分，只有省市得2分
								const matchScore = matchedArea ? 3 : 2;
								if (matchScore > bestMatchScore) {
									bestMatchScore = matchScore;
									bestMatch = {
										province: provinceName,
										city: cityName,
										area: matchedArea || ''
									};
									// 如果找到了完整的省市区，可以提前返回
									if (matchedArea) {
										return bestMatch;
									}
								}
							}
						}
					}
					
					// 如果只找到了省份，也记录（得分1分）
					if (!bestMatch || bestMatchScore < 1) {
						bestMatch = {
							province: provinceName,
							city: '',
							area: ''
						};
						bestMatchScore = 1;
					}
				}
			}
			
			return bestMatch;
		},

		// 更新各类附件
		updateChatFiles(fileList) {
			this.form.chatAttachmentList = fileList;
		},

		updateQuoteFiles(fileList) {
			this.form.quoteAttachmentList = fileList;
		},

		updateHdImageFiles(fileList) {
			this.form.hdImageAttachmentList = fileList;
		},

		updateOtherFiles(fileList) {
			this.form.otherAttachmentList = fileList;
		},

		// 文件变化处理
		handleFileChange(data) {
			console.log('文件上传变化:', data);
		},
		// 获取字典数据
		async getDicts() {
			try {
				const [categoryRes, tacticRes, brandRes] = await Promise.all([
					this.$getDicts('crm_form_category'),
					this.$getDicts('crm_form_tactic'),
					this.$getDicts('crm_form_brand')
				]);

				this.categoryDict = categoryRes;
				this.tacticDict = tacticRes;
				this.brandDict = brandRes;
			} catch (error) {
				console.error('获取字典数据失败:', error);
			}
		},

		// 处理保存
		async handleNavSaveClick() {
			try {
				// 表单验证
				await this.$refs.form.validate();

				if (this.form.id) {
					const updatedForm = {
						clueId: this.form.clueId,
						model: this.form.model,
						price: this.form.price,
						wechat: this.form.wechat,
						id: this.form.id,
						item: this.form.item,
						phone: this.form.phone,
						authenticateUserId: this.form.authenticateUserId,
						category: this.form.category,
						brand: this.form.brand,
						idCard: this.form.idCard,
						customName: this.form.customName,
						bankCardNumber: this.form.bankCardNumber,
						bankName: this.form.bankName,
						paymentMethod: this.form.paymentMethod,
						visitTime: this.form.visitTime,
						remarks: this.form.remarks,
						priceRange: this.form.priceRange,
						tactic: this.form.tactic
					}
					await uni.$u.api.updateClueOrderForm(updatedForm);
					uni.$emit('updateSendFormSuccess');
					uni.$u.toast('发单记录更新成功');
				} else {
					// 合并所有附件
					const allAttachments = [
						...this.form.chatAttachmentList,
						...this.form.quoteAttachmentList,
						...this.form.hdImageAttachmentList,
						...this.form.otherAttachmentList
					];

					// 准备提交数据
					const submitData = {
						...this.form,
						uploadList: allAttachments
					};
					await uni.$u.api.saveClueOrderForm(submitData);
					uni.$u.toast('发单记录添加成功');
				}

				// 延迟返回
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);

			} catch (error) {
				console.error('保存失败:', error);
				if (error.message) {
					uni.$u.toast(error.message);
				}
			}
		}
	},

	onLoad(option) {
		console.log('option', option);
		const clueId = option.clueId;
		this.sendFormId = option.sendFormId;
		this.form.clueId = clueId;
		this.getDicts();
		if (option.sendFormId) {
			this.loadFormData(option.sendFormId);
		}
	}
}
</script>

<style lang="scss" scoped>
.oder_form_wrap {
	background-color: #f8f9fa;
	min-height: 100vh;
	padding-bottom: 10rpx;
	padding-top: 10px;
	padding-left: 20rpx;
	padding-right: 20rpx;
}

.upload_area {
	padding: 0 10rpx;
}

.bottom_btn {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx;
	background: #fff;
	box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
}



::v-deep .u-form-item {
	/* 移除底部边框 */
	border-bottom: none;
	/* 添加卡片样式 */
	// background-color: #fff;
	border-radius: 16rpx;
	/* 添加内边距 */
	padding: 10rpx;
	/* 确保内容不会溢出 */
	overflow: hidden;

	.u-input--square {
		border-radius: 20rpx;
	}

	.u-input--square:focus-within,
	.u-input--square.u-input--focus {
		border: 2rpx solid #2563eb !important;
		background-color: #fff !important;
	}
}

.brand_wrap {
	::v-deep .u-form-item__body__right__content {
		border: 1px solid #dadbde;
		padding: 10rpx;
		border-radius: 20rpx;

		.inputWrap {
			border: none;
		}
	}
}

.address_wrap {
	border-radius: 20rpx;
	padding: 24rpx;
	display: flex;
	flex-direction: column;
	background-color: #fff;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	margin: 0 10rpx;

	.address_title {
		display: flex;
		align-items: center;
		background-color: #fff;
		padding-bottom: 12rpx;
		gap: 16rpx;
		font-size: 26rpx;
		color: #6b7280;
		font-weight: 600;
	}

	::v-deep .u-form-item {
		margin-bottom: 0 !important;
		padding: 0;

		.u-input--square {
			background-color: #f9fafb;
		}
	}

	::v-deep .u-textarea--radius {
		border-radius: 20rpx;
	}

	.region-picker {
		width: 100%;
	}

	::v-deep .u-textarea {
		background-color: #f9fafb;
	}
}

.visit_time_wrap {
	::v-deep .uni-date-x {
		border-radius: 10px;
		padding: 8rpx 10rpx;
		border: 1px solid #dadbde;
		background-color: #f8f9fa;
	}
}

.category_wrap {
	.category_select_wrap {
		border-radius: 20rpx;
		border: 1px solid #dadbde;
		padding: 6rpx;
		width: 100%;

		::v-deep .ldSelectInput {
			font-size: 28rpx !important;
		}
	}

	.category_select_wrap:focus-within,
	.category_select_wrap:focus {
		border: 2rpx solid #2563eb !important;
		background-color: #fff !important;
	}
}

.remarks_wrap {
	.u-textarea {
		background-color: #fff;
	}

	::v-deep .u-textarea--radius {
		border-radius: 20rpx;
	}
}

::v-deep .u-form-item__body {
	padding: 10rpx 0rpx;
}


::v-deep .u-form-item__body__left__content__label {
	color: rgb(107 114 128 / 1) !important;
	font-size: 28rpx;
	font-weight: 700;
}

.u-button {
	border-radius: 40rpx;
	background-color: #2563eb;
	border: none;
	color: #fff;
	font-weight: 700;
	font-size: 40rpx;
	height: 100rpx;
}

.tactic-buttons {
	display: flex;
	justify-content: space-between;
	margin-top: 10rpx;
	width: 100%;
}

.tactic-button {
	position: relative;
	border-width: 3rpx;
	border-style: solid;
	border-color: #e5e7eb;
	width: 30%;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	border-radius: 30rpx;
	background-color: #f9fafb;
	color: rgb(107 114 128 / 1);
	font-size: 28rpx;
	transition: all 0.3s ease;
	font-weight: 700;
}

.tactic-button.active {
	border-color: #3b82f6;
	color: #3b82f6;
	background-color: #eff6ff;
}

.tactic-button::after {
	content: '';

	position: absolute;
	border-width: 5rpx;
	border-style: solid;
	border-color: #ffffff;
	top: 4%;
	right: -12%;
	transform: translate(-50%, -50%);
	width: 25rpx;
	height: 25rpx;
	border-radius: 50%;
	background-color: #3b82f6;
	opacity: 0;
	transition: all 0.3s ease;
}

.tactic-button.active::after {
	opacity: 1;
}

.u-textarea {
	background-color: #f5f5f5;
}
</style>