<template>
	<view class="container">
		<view class="header">
			<view class="title">商家注册</view>
		</view>
		<view class="form">
			<view class="input-group" v-for="(field, index) in fields" :key="index">
				<view class="label">{{ field.label }}</view>
				<view class="input">
					<!-- 商家分类下拉选择器 -->
					<template v-if="field.model === 'categoryId'">
						 <uni-data-select 
						            v-model="formData.categoryId" 
						            :localdata="range" 
						            :clear="false"
						            placeholder="请选择商家分类"
						            class="distribution-select"
						            mode="selector" 
						        ></uni-data-select>
					</template>

					<!-- 普通输入框 -->
					<input 
						v-else-if="!field.isFile"
						v-model="formData[field.model]" 
						:placeholder="field.placeholder" 
						class="styled-input"
						@blur="validateField(field)"
					/>

					<!-- 文件上传按钮 -->
					<view v-else class="upload-container">
						<button @click="handleUpload(field)" class="upload-button">
							{{ formData[field.model] ? '已上传' : '点击上传' }}
						</button>
						<text v-if="formData[field.model]" class="upload-tip">已上传文件</text>
					</view>
				</view>
			</view>
			<view class="button">
				<button @click="saveAddress" class="styled-button">点击注册</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { apiImageUrl } from '../../API/api';
	
export default {
	data() {
		return {
			formData: {
				address: '',
				backIdCard: '',
				bankCard: '',
				businessAvatar: '',
				businessImages: '',
				businessName: '',
				businessPhone: '',
				businessProfile: '',
				categoryId: '',
				endBusiness: '',
				frontIdCard: '',
				license: '',
				shopkeeper: '',
				startBusiness: '',
				userAccount: '',
				userPassword: ''
			},
		range: [
						{ value: '1', text: '第一餐厅' },
						{ value: '2', text: '第二餐厅' },
						{ value: '3', text: '第三餐厅' },
						{ value: '4', text: '第四餐厅' },
						{ value: '5', text: '第五餐厅' }
					],

			fields: [
				{ label: '商家地址', model: 'address', placeholder: '请输入地址' },
				{ 
									label: '身份证背面图片', 
									model: 'backIdCard', 
									isFile: true,
									bizType: 'card' 
								},

				{ label: '银行卡号', model: 'bankCard', placeholder: '请输入银行卡号', validation: (value) => value.length === 16, errorMsg: '银行卡号必须为16位' },
				{ 
									label: '商家头像', 
									model: 'businessAvatar', 
									isFile: true,
									bizType: 'user_avatar' 
								},

				{ 
									label: '商家图片', 
									model: 'businessImages', 
									isFile: true,
									bizType: 'user_avatar' 
								},

				{ label: '商家名称', model: 'businessName', placeholder: '请输入商家名称' },
				{ label: '商家手机号', model: 'businessPhone', placeholder: '请输入商家手机号', validation: (value) => value.length === 11, errorMsg: '手机号必须为11位' },
				{ label: '商家门店简介', model: 'businessProfile', placeholder: '请输入商家简介' },
			 {
			        label: '商家分类',
			        model: 'categoryId',
			    },

				{ label: '关店时间', model: 'endBusiness', placeholder: '关店时间' },
				{ 
									label: '身份证正面', 
									model: 'frontIdCard', 
									isFile: true,
									bizType: 'card' 
								},

				{ 
									label: '营业执照正面', 
									model: 'license', 
									isFile: true,
									bizType: 'card' 
								},

				{ 
				    label: '店主姓名', 
				    model: 'shopkeeper', 
				    placeholder: '请输入店主姓名',
				    validation: (value) => /^[\u4e00-\u9fa5]+$/.test(value), 
				    errorMsg: '姓名只能包含汉字' 
				},
				{ label: '开店时间', model: 'startBusiness', placeholder: '开店时间' },
				{ label: '账户', model: 'userAccount', placeholder: '账户' },
				{ label: '密码', model: 'userPassword', placeholder: '密码', validation: (value) => value.length >= 8, errorMsg: '密码长度至少为8位' }
			]
		};
	},
	methods: {
			handleUpload(field) {
					uni.chooseImage({
						count: 1,
						sizeType: ['compressed'],
						sourceType: ['album', 'camera'],
						success: (res) => {
							const tempFilePath = res.tempFilePaths[0];
							this.uploadFile(tempFilePath, field);
						}
					});
				},
				uploadFile(filePath, field) {
							uni.uploadFile({
								url: apiImageUrl+'/api/file/upload/server/not_login',
								filePath: filePath,
								name: 'file',
								formData: {
									biz: field.bizType 
								},
								success: (res) => {
									try {
										const response = JSON.parse(res.data);
										if(response.code === 0) {
											this.formData[field.model] = response.data;
											uni.showToast({
												title: '上传成功',
												icon: 'success'
											});
										}
									} catch(e) {
										console.error('解析响应失败:', e);
									}
								},
								fail: (err) => {
									uni.showToast({
										title: '上传失败',
										icon: 'none'
									});
								}
							});
						},


		validateField(field) {
			if(field.isFile) return;
			const value = this.formData[field.model].trim();
			if (field.validation && !field.validation(value)) {
				uni.showToast({
					title: field.errorMsg,
					icon: 'none',
					duration: 2000
				});
			}
		},
		saveAddress() {
			for (const field of this.fields) {
							if(field.isFile) {
								if(!this.formData[field.model]) {
									uni.showToast({
										title: `${field.label}必须上传`,
										icon: 'none'
									});
									return;
								}
								continue;
							}
				const value = this.formData[field.model].trim();
				if (!value) {
					uni.showToast({
						title: `${field.label}不能为空，请填写`,
						icon: 'none',
						duration: 2000
					});
					return;
				}
				if (field.validation && !field.validation(value)) {
					uni.showToast({
						title: field.errorMsg,
						icon: 'none',
						duration: 2000
					});
					return;
				}
			}

		
			uni.request({
				url: apiImageUrl+'/api/business/add',
				method: 'POST',
				data: this.formData,
				header: {
					'Content-Type': 'application/json', 
					'cookie': uni.getStorageSync("cookie") || ''
				},
				success: (res) => {
					if(res.data.code === 0){
						uni.showToast({
							title: '注册成功！',
							duration: 2000, 
							icon: "success" 
						})
					} else if(res.data.code === 40000) {
						uni.showToast({
							title: res.data.description,
							duration: 2000, 
							icon: "fail" 
						})
					}
				},
				fail: (err) => {
					console.log("请求失败", err);
					uni.showToast({
						title: '网络连接失败',
						icon: 'none',
						duration: 2000
					});
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
	.container {
		padding: 20px;
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;

		.title {
			font-size: 24px;
			font-weight: bold;
		}
	}

.upload-container {
	display: flex;
	align-items: center;
	gap: 10px;
}

.upload-button {
	padding: 8px 15px;
	background-color: #4CAF50;
	color: white;
	border-radius: 5px;
	font-size: 14px;
}

.upload-tip {
	color: #666;
	font-size: 12px;
}



	.form {
		.input-group {
			display: flex;
			align-items: center;
			margin-bottom: 20px;

			.label {
				flex: 1;
				font-size: 14px;
				margin-right: 20px;
			}

			.input {
				flex: 3;

				.styled-input {
					font-size: 14px;
					width: 100%;
					padding: 10px;
					background-color: rgba(255, 235, 59, 0.6);
					border: none;
					border-radius: 20px; 
					box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08); 
					outline: none;
					transition: all 0.2s ease-in-out;

					&:focus {
						background-color: rgba(255, 235, 59, 0.8); 
						box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15), 0 2px 4px rgba(0, 0, 0, 0.1);
					}
				}
			}
		}

		.button {
			margin-top: 20px;

			.styled-button {
				width: 100%;
				padding: 10px;
				background-color: #007bff;
				color: #fff;
				border: none;
				border-radius: 15px;
				cursor: pointer;
				font-size: 16px;
				line-height: inherit;
				transition: background-color 0.2s;

				&:hover {
					background-color: #0056b3;
				}
			}
		}
	}
	
	
	.distribution-select {
	    width: 100%;
	    .uni-select {
	        padding: 10px;
	        background-color: rgba(255, 235, 59, 0.6);
	        border-radius: 20px;
	        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
	        &::after {
	            border-color: #5e7dec;
	        }
	    }
	}
</style>