<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">
					<ld-select :list="brandDict" label-key="dictLabel" value-key="dictValue" placeholder="请选择物品品牌"
						v-model="form.brand" :border="false"></ld-select>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-row justify="space-between">
					<u-form-item label="型号" prop="model">
						<u-col span="6">
							<u--input v-model="form.model" placeholder="请输入型号" border="none"></u--input>

						</u-col>
					</u-form-item>

					<u-form-item label="实价" prop="price">
						<u-col span="6">
							<u--input v-model="form.price" placeholder="请输入实价" border="none"></u--input>
						</u-col>
					</u-form-item>
				</u-row>

				<u-row justify="space-between">
					<u-form-item label="客户电话" prop="phone">
						<u-col span="6">
							<u--input v-model="form.phone" placeholder="请输入客户电话" border="none"></u--input>

						</u-col>
					</u-form-item>

					<u-form-item label="客户微信" prop="wechat">
						<u-col span="6">
							<u--input v-model="form.wechat" placeholder="请输入客户微信" border="none"></u--input>
						</u-col>
					</u-form-item>
				</u-row>

				<u-form-item label="省市区">
					<pick-regions :defaultRegion="defaultRegion" @getRegion="handleGetRegion">
						<view class="region-picker">
							<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-form-item label="详细地址" prop="address" class='form_card'>
					<u--textarea v-model="form.address" placeholder="请输入详细地址" count confirmType="done"></u--textarea>
				</u-form-item>

				<u-form-item label="上门时间" prop="visitTime">
					<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">
					<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>
				</u-form-item>



				<u-form-item label="价格范围" prop="priceRange">
					<u--input v-model="form.priceRange" placeholder="请输入价格范围" border="none"></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">
					<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" :file-list="form.chatAttachmentList"
				@update:fileList="updateChatFiles" tip-text="上传聊天截图、录音等文件"></order-file-upload>

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

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

			<!-- 其他附件 -->
			<order-file-upload title="其他附件" orderFileType="4" :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"
export default {
	components: {
		orderFileUpload,
		dateTimePicker,
		ldSelect
	},
	data() {
		return {
			defaultRegion: ['广东省', '广州市', '番禺区'],
			categoryDict: [],
			tacticDict: [],
			brandDict: [],

			sendFormId: undefined,

			form: {
				clueId: '',
				sendDate: '',
				website: '',
				item: '',
				phone: '',
				wechat: '',
				address: '',
				visitTime: '',
				remarks: '',
				category: '',
				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: true,
					message: '请输入客户微信',
					trigger: ['blur', 'change']
				},
				phone: {
					type: 'string',
					required: true,
					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;
			// 只在详细地址为空时自动填充省市区
			if (!this.form.address || this.form.address.trim() === '') {
				this.form.address = this.form.province + this.form.city + this.form.area;
			}
		},

		// 更新各类附件
		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: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 100rpx;
	padding-top: 10px;
	padding-left: 20rpx;
	padding-right: 20rpx;
}

.form_wrap {
	/* 移除整体背景和边框，让每个form-item成为独立卡片 */
}

.upload_area {
	padding: 0 0rpx;
	margin: 20rpx 0;
}

.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);
}

.region-picker {
	width: 100%;
}

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

.form_card {
	background-color: #fff;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

}

::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: 0.75rem;
	line-height: 1rem;
	font-weight: 700;
}


.u-button {
	border-radius: 40rpx;
	background-color: rgb(29 78 216 / var(--tw-bg-opacity, 1));
	--tw-text-opacity: 1;
	color: rgb(255 255 255 / var(--tw-text-opacity, 1));
	font-weight: 700;
	font-size: 1rem;
	line-height: 1.5rem;
	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: #f5f5f5;
	color: rgb(107 114 128 / 1);
	font-size: 28rpx;
	transition: all 0.3s ease;
	font-weight: 700;
}

.tactic-button.active {
	border-color: rgb(29 78 216 / 1);
	color: rgb(29 78 216 / 1);
}

.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: rgb(29 78 216 / 1);
	opacity: 0;
	transition: all 0.3s ease;
}

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

.u-textarea{
	background-color: #f5f5f5;
}

</style>