<template>
	<view class="ruzhu-page">
		<!-- 顶部导航栏 - 根据身份动态显示标题 -->
		<custom-navbar :title="navTitle" :showBack="true"></custom-navbar>

		<!-- 步骤切换 -->
		<step-tab v-if="currentStep !== 2 && currentStep !== 4" :mappedStep="mappedStep"></step-tab>

		<!-- 内容区域根据身份和步骤显示不同内容 -->
		<view class="content">
			<view class="xieyi_content" v-if="currentStep === 0">
				<rich-text :nodes="textData.text"></rich-text>
			</view>

			<view v-else-if="currentStep === 1">
				<qualification-info ref="qualificationInfo"></qualification-info>
			</view>

			<view v-else-if="currentStep === 2">
				<successruzhu :data="successData"></successruzhu>
			</view>

			<view v-else-if="currentStep === 3">
				<store-info ref="storeInfo"></store-info>
			</view>

			<view v-else-if="currentStep === 4">
				<successruzhu :data="successData"></successruzhu>
			</view>
		</view>
		<view class="kong"></view>

		<!-- 底部按钮区域 -->
		<view class="bottom-fixed">
			<!-- 步骤0: 入驻协议 -->
			<view v-if="currentStep === 0" class="step-0-buttons">
				<view class="agree">
					<image v-if="!isAgree" src="/static/images/agree_n.png" class="agree-btn" mode="aspectFit"
						@click="isAgree = true"></image>
					<image v-else src="/static/images/agree_y.png" class="agree-btn" mode="aspectFit"
						@click="isAgree = false"></image>
					<text class="agree-tip">我已阅读并同意以上协议</text>
				</view>
				<view class="next-btn" @click="goNext">
					<text class="next-text">下一步，填写基本信息</text>
				</view>
			</view>

			<!-- 步骤1: 资质信息 -->
			<view v-else-if="currentStep === 1" class="step-1-buttons">
				<view class="button-row">
					<view class="prev-btn" @click="goPrev">
						<text class="prev-text">上一步</text>
					</view>
					<view class="next-btn" @click="goNext">
						<text class="next-text">提交入驻</text>
					</view>
				</view>
			</view>

			<!-- 步骤2: 提交成功 -->
			<view v-else-if="currentStep === 2" class="step-2-buttons">
				<view class="button-row">
					<view class="prev-btn" @click="topt">
						<text class="prev-text">进入平台</text>
					</view>
					<view class="submit-btn" @click="goNext">
						<text class="submit-text">去完成资质认证</text>
					</view>
				</view>
			</view>

			<!-- 步骤3: 门店信息 -->
			<view v-else-if="currentStep === 3" class="step-2-buttons">
				<view class="button-row">
					<view class="prev-btn" @click="goPrev">
						<text class="prev-text">上一步</text>
					</view>
					<view class="submit-btn" @click="submitApplication">
						<text class="submit-text">提交申请</text>
					</view>
				</view>
			</view>

			<!-- 步骤4: 资质认证成功 -->
			<view v-else-if="currentStep === 4" class="step-2-buttons">
				<view class="button-row">
					<view class="showziliao" @click="topt">
						<text class="showziliaotext">进入平台</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '../../utils/request';
	import StepTab from '@/components/step-tab/step-tab.vue';
	import QualificationInfo from './qualification_sj.vue';
	import StoreInfo from './sj-info.vue';
	import successruzhu from './successruzhu.vue';

	export default {
		components: {
			StepTab,
			QualificationInfo,
			StoreInfo,
			successruzhu
		},
		data() {
			return {
				currentStep: 0, // 当前步骤索引
				isAgree: false,
				identity: null,
				textData: {},
				loading: false,
				error: null,
				navTitle: '商家入驻', // 默认标题
				qualificationData: null, // 新增：保存资质信息
				storeInfoData: null, // 新增：保存门店信息
				successData: {}, //入驻提示
				// 新增：缓存手艺人数据
				artisanDataCache: {
					personalInfo: null,
					qualificationInfo: null
				}
			}
		},
		computed: {
			mappedStep() {
				if (this.currentStep === 0) return 0;
				if (this.currentStep === 1) return 1;
				if (this.currentStep === 3) return 2;
				if (this.currentStep === 4) return 2;
				return 0;
			}
		},
		async onLoad(options) {
			console.log(options, 'options---');
			if (options.type == 1) {
				this.currentStep = 4
			}

			// 如果首页传了 step 参数，就直接空降到对应的流程
			if (options.step) {
				this.currentStep = Number(options.step);
			}

			this.identity = 2;
			await this.getUserInfoSync()
			// 确保子组件也能访问到 identity
			this.getXieyi(1);
		},

		onShow() {
			console.log('入驻页面 onShow - 检查地址数据');
			// 检查商家地址数据
			this.checkAndPassAddressToSj();
		},

		methods: {
			topt() {
				uni.switchTab({
					url: '/pages/home/home'
				})
			},
			// 获取用户信息（复用不可服务时间页面的方法）
			async getUserInfoSync() {
				await request.post('/sj/userSjAuth/details', {
					type: 1
				}).then(result => {
					if (result.code == 200 && result.data) {
						let data = result.data
						if (getApp().globalData.artisanType == 2) {

							let qualification_form_data = {
								"uscc_type": data.uscc_type || '',
								// "contact_identity": 'legal',
								// "contact_name": data.legal_name || data.contact_name || '',
								"contact_phone": data.legal_phone || data.contact_phone || '',
								"backup_phone": data.backup_phone || '',
								"invite_code": data.invite_code_other || '',
								"dependency": data.dependency || '',
								"address": data.address || '',
								"dependency_code": data.dependency_code || '',
								"dependency_province": data.dependency_province || '',
								"dependency_city": data.dependency_city || '',
								"longitude": data.longitude || '',
								"latitude": data.latitude || '',
								"name": data.name || '',
								"contact_type": data.contact_type || ''

							}
							uni.setStorageSync('qualification_form_data', qualification_form_data);
							let store_info_form_data = {
								"head_photo": data.head_photo,
								"name": data.name,
								"business_time": data.business_time,
								// "servers_kill": data.servers_kill,
								"apply_state": data.apply_state,
								"invite_code_other": data.invite_code_other,
								"major": data.major
							}
							console.log(111111111, store_info_form_data)
							uni.setStorageSync('store_info_form_data', store_info_form_data);
						}

					}
				}).catch(error => {
					console.error('获取用户信息接口错误:', error);
				});
			},
			// 检查并传递地址给商家组件
			checkAndPassAddressToSj() {
				try {
					const sjAddress = uni.getStorageSync('sj_selected_address');
					if (sjAddress) {
						console.log('找到商家地址数据，准备传递:', sjAddress);

						setTimeout(() => {
							if (this.identity === 2 && this.$refs.qualificationInfo) {
								console.log('传递地址给资质组件');
								if (typeof this.$refs.qualificationInfo.handleAddressSelected === 'function') {
									this.$refs.qualificationInfo.handleAddressSelected(sjAddress);
								}
							}
							uni.removeStorageSync('sj_selected_address');
						}, 300);
					}
				} catch (e) {
					console.error('处理商家地址失败:', e);
				}
			},

			// 新增方法：检查并传递地址数据
			checkAndPassAddressData() {
				try {
					const syrAddress = uni.getStorageSync('syr_selected_address');
					if (syrAddress && this.$refs.personalInfo) {
						console.log('步骤切换时发现地址数据，传递给组件');

						// 传递给组件
						if (typeof this.$refs.personalInfo.handleAddressSelected === 'function') {
							this.$refs.personalInfo.handleAddressSelected(syrAddress);
						} else {
							// 直接设置
							this.$refs.personalInfo.formData.detail_address = syrAddress.address;
							this.$refs.personalInfo.formData.longitude = syrAddress.longitude;
							this.$refs.personalInfo.formData.latitude = syrAddress.latitude;
							this.$refs.personalInfo.saveFormDataToLocal();
							this.$refs.personalInfo.$forceUpdate();
						}

						// 清理
						uni.removeStorageSync('syr_selected_address');
					}
				} catch (e) {
					console.error('检查地址数据失败:', e);
				}
			},

			// 检查用户信息
			checkUserInfo() {
				console.log('检查用户信息...');

				// 从多种可能的存储位置检查用户信息
				const sources = [{
						name: '本地存储-userInfo',
						data: uni.getStorageSync('userInfo')
					},
					{
						name: '本地存储-loginInfo',
						data: uni.getStorageSync('loginInfo')
					},
					{
						name: '本地存储-token',
						data: uni.getStorageSync('token')
					}
				];

				sources.forEach(source => {
					console.log(`${source.name}:`, source.data);
				});

				// 检查是否有token（确认登录状态）
				const token = uni.getStorageSync('token');
				if (!token) {
					console.warn('未检测到登录token');
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
				}
			},

			// 获取用户信息（复用不可服务时间页面的方法）
			getUserInfo() {
				return new Promise((resolve, reject) => {
					request.post('/sj/User/getUser', {
						type: 1
					}).then(result => {
						if (result.state == 1) {
							// 保存用户信息到全局数据和本地存储
							uni.setStorageSync('userInfo', result.data);
							console.log('用户信息获取成功:', result.data);
							resolve(result.data);
						} else {
							console.error('获取用户信息失败:', result.msg);
							reject(result.msg);
						}
					}).catch(error => {
						console.error('获取用户信息接口错误:', error);
						reject(error);
					});
				});
			},

			// 检查并获取用户信息
			async checkAndGetUserInfo() {
				// 先检查是否已有用户信息
				const existingUserInfo = uni.getStorageSync('userInfo');
				if (existingUserInfo && existingUserInfo.account) {
					console.log('已有用户信息:', existingUserInfo);
					return existingUserInfo;
				}

				// 如果没有，则调用接口获取
				try {
					const userInfo = await this.getUserInfo();
					return userInfo;
				} catch (error) {
					console.error('获取用户信息失败:', error);
					uni.showModal({
						title: '提示',
						content: '获取用户信息失败，请重新登录',
						showCancel: false,
						success: () => {
							uni.navigateTo({
								url: '/pages/login/login'
							});
						}
					});
					return null;
				}
			},

			// 审核提交方法
			async submitForReview() {
				const userInfo = await this.checkAndGetUserInfo();
				if (!userInfo) {
					return;
				}

				uni.showLoading({
					title: '提交中...'
				});

				try {
					let formData = this.buildBusinessData(this.qualificationData, {});
					formData.type = 1;
					formData.id_type = 1;
					if (Array.isArray(formData.qualifications_sector)) {
						formData.qualifications_sector = JSON.stringify(formData.qualifications_sector);
					}
					if (Array.isArray(formData.qualifications_other)) {
						formData.qualifications_other = JSON.stringify(formData.qualifications_other);
					}
					const res = await request.post('/sj/userSjAuth/applyOne', formData);
					uni.hideLoading();

					if (res.state == 1 || res.code == 200) {
						this.successData = res.data.customer_service
						console.log(this.successData,
							'this.successDatathis.successDatathis.successDatathis.successData=======');
						uni.showToast({
							title: '提交成功',
							icon: 'none',
							duration: 1500
						});
						setTimeout(() => {
							this.currentStep = 2;
						}, 1500);
					} else {
						uni.showToast({
							title: res.msg || '提交失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'none'
					});
				}
			},

			// 构建商家数据
			buildBusinessData(qualificationData, storeData) {
				qualificationData = qualificationData || {};
				storeData = storeData || {};
				console.log(qualificationData, 'storeDatastoreDatastoreData');
				const formData = {};
				Object.assign(formData, storeData);

				if (qualificationData.uscc_type) {
					formData.uscc_type = qualificationData.uscc_type;
				}
				// if (qualificationData.contact_identity) {
				// 	formData.contact_identity = qualificationData.contact_identity;
				// }
				// if (qualificationData.contact_name) {
				// 	formData.contact_name = qualificationData.contact_name;
				// }
				if (qualificationData.contact_phone) {
					formData.contact_phone = qualificationData.contact_phone;
				}
				if (qualificationData.backup_phone) {
					formData.backup_phone = qualificationData.backup_phone;
				}
				if (qualificationData.contact_type) {
					formData.contact_type = qualificationData.contact_type;
				}
				if (qualificationData.invite_code_other) {
					formData.invite_code_other = qualificationData.invite_code_other;
				}
				if (qualificationData.contact_name) {
					formData.contact_name = qualificationData.contact_name;
				}

				if (qualificationData.dependency) {
					formData.dependency = qualificationData.dependency;
				}
				if (qualificationData.dependency_code) {
					formData.dependency_code = qualificationData.dependency_code;
				}
				if (qualificationData.dependency_province) {
					formData.dependency_province = qualificationData.dependency_province;
				}
				if (qualificationData.dependency_city) {
					formData.dependency_city = qualificationData.dependency_city;
				}
				if (qualificationData.name) {
					formData.name = qualificationData.name;
				}
				if (qualificationData.address) {
					formData.address = qualificationData.address;
				}
				if (qualificationData.longitude) formData.longitude = qualificationData.longitude;
				if (qualificationData.latitude) formData.latitude = qualificationData.latitude;

				// if (storeData && storeData.servers_kill && storeData.servers_kill.length > 0) {
				// 	// formData.servers_kill = Array.isArray(storeData.servers_kill) ?
				// 	// 	storeData.servers_kill : [storeData.servers_kill];
				// } else {
				// 	formData.servers_kill = [];
				// }
				if (storeData.head_photo) {
					formData.head_photo = storeData.head_photo;
				}
				if (storeData.name) {
					formData.name = storeData.name;
				}
				if (storeData.business_time) {
					formData.business_time = storeData.business_time;
				}
				if (storeData.apply_state) {
					formData.get_msg_method = storeData.apply_state;
				}
				if (storeData.major) {
					formData.major = storeData.major;
				}


				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo && userInfo.account) {
					formData.account = userInfo.account;
				} else {
					const loginAccount = uni.getStorageSync('loginAccount');
					if (loginAccount) {
						formData.account = loginAccount;
					} else if (qualificationData.contact_phone) {
						formData.contact_name = qualificationData.contact_name;
					} else {
						console.error('无法获取账号信息');
						uni.showToast({
							title: '无法获取用户账号',
							icon: 'none'
						});
						return null;
					}
				}

				return formData;

			},

			async goNext() {
				if (this.currentStep === 0 && !this.isAgree) {
					uni.showToast({
						title: '请阅读并同意以上协议',
						icon: 'none'
					});
					return;
				}

				if (this.currentStep === 1) {
					if (this.$refs.qualificationInfo) {
						const isValid = await this.$refs.qualificationInfo.saveFormData();
						if (!isValid) {
							return;
						}
						this.qualificationData = this.$refs.qualificationInfo.getFormData();
					}
					await this.submitForReview();
					return;
				}

				if (this.currentStep < 3) {
					this.currentStep++;
					setTimeout(() => {
						this.scrollToTop();
					}, 100);
				}
			},

			async submitApplication() {
				if (this.$refs.storeInfo) {
					if (!this.$refs.storeInfo.saveFormData()) {
						return;
					}
					this.storeInfoData = this.$refs.storeInfo.getFormData();
				}

				uni.showLoading({
					title: '提交中...'
				});
				try {
					const formData = this.buildBusinessData(this.qualificationData, this.storeInfoData);
					if (!formData) {
						uni.hideLoading();
						return;
					}
					formData.type = 1;
					formData.id_type = 1;
					console.log(formData, '-----------');
					if (formData.legal_idcard_expiry_start && formData.legal_idcard_expiry_end) {
						formData.legal_idcard_expiry =
							formData.legal_idcard_expiry_end === '长久有效' ?
							`${formData.legal_idcard_expiry_start} —— 长久` :
							`${formData.legal_idcard_expiry_start} —— ${formData.legal_idcard_expiry_end}`;
					}
					delete formData.legal_idcard_expiry_start
					delete formData.legal_idcard_expiry_end
					delete formData.contact_phone
					delete formData.contact_type
					delete formData.contact_name
					delete formData.invite_code_other
					if (Array.isArray(formData.qualifications_sector)) {
						formData.qualifications_sector = JSON.stringify(formData.qualifications_sector);
					}
					if (Array.isArray(formData.qualifications_other)) {
						formData.qualifications_other = JSON.stringify(formData.qualifications_other);
					}
					console.log(formData, 'formData请求参数');
					const res = await request.post('/sj/userSjAuth/apply', formData);
					uni.hideLoading();
					if (res.state == 1 || res.code == 200) {
						this.successData = res.data ? (res.data.customer_service || {}) : {};
						uni.showToast({
							title: '提交成功',
							icon: 'none'
						});
						setTimeout(() => {
							this.currentStep = 4;
						}, 1500);
					} else {
						uni.showToast({
							title: res.msg || '提交失败了',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('提交失败：', error);
					uni.hideLoading();
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'none'
					});
				}
			},

			goPrev() {
				if (this.currentStep > 0) {
					this.currentStep--;
				}
			},
			scrollToTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				});
			},
			async getXieyi(type) {
				this.loading = true;
				this.error = null;
				try {
					const res = await request.post('/user/getsystemtext', {
						type
					});
					this.textData = res.data;
				} catch (err) {
					console.error('获取协议失败:', err);
					this.error = '获取协议内容失败，请重试';
					uni.showToast({
						title: '获取协议内容失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
		}
	}
</script>

<style>
	.ruzhu-page {
		background: #f5f5f5;
	}

	.content {
		padding: 20rpx 20rpx 50rpx 20rpx;
		box-sizing: border-box;
	}

	.xieyi_content {
		padding: 20rpx;
		background: #ffffff;
		border-radius: 20rpx;
	}

	.ruzhu-cont {
		padding: 24rpx;
		background-color: #fff;
	}

	.ruzhu-text {
		font-size: 28rpx;
		color: #3D3D3D;
		font-weight: 400;
	}

	.kong {
		width: 100vw;
		height: 180rpx;
	}

	/* 底部按钮区域样式 */
	.bottom-fixed {
		position: fixed;
		left: 0;
		bottom: 0;
		right: 0;
		background-color: #ffffff;
		padding: 24rpx 0;
	}

	/* 步骤0按钮布局 */
	.step-0-buttons {
		display: flex;
		flex-flow: column nowrap;
		justify-content: center;
		align-items: center;
	}

	/* 步骤0中的下一步按钮*/
	.step-0-buttons .next-btn {
		width: 702rpx;
		height: 98rpx !important;
		display: flex;
		justify-content: center;
		align-items: center;
		background: #FF4767;
		border-radius: 49rpx;
	}

	.step-0-buttons .next-text {
		color: #ffffff;
		font-size: 32rpx;
		font-weight: 500;
	}

	/* 步骤1和步骤2按钮布局 */
	.step-1-buttons,
	.step-2-buttons {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* 步骤1中的按钮 */
	.step-1-buttons .next-btn {
		flex: 1;
		height: 98rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background: #FF4767;
		border-radius: 49rpx;
	}

	.step-1-buttons .next-text {
		color: #ffffff;
		font-size: 32rpx;
		font-weight: 500;
	}

	/* 步骤2中的提交按钮 */
	.step-2-buttons .submit-btn {
		flex: 1;
		height: 98rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background: linear-gradient(180deg, #ff8e9d 0%, #FF4767 100%);
		border-radius: 49rpx;
	}

	.step-2-buttons .submit-text {
		color: #ffffff;
		font-size: 32rpx;
		font-weight: 500;
	}

	/* 上一步按钮 - 统一所有步骤中的样式 */
	.prev-btn {
		width: 249rpx;
		height: 98rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #f8f8f8;
		border-radius: 60rpx;
	}

	.prev-text {
		color: #FF4767;
		font-size: 36rpx;
		font-weight: 500;
	}

	.button-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 702rpx;
		height: 147rpx;
		gap: 20rpx;
	}

	.agree {
		display: flex;
		flex-flow: row nowrap;
		justify-content: center;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.agree-btn {
		width: 32rpx;
		height: 32rpx;
		margin-right: 13rpx;
	}

	.agree-tip {
		font-size: 26rpx;
		font-weight: 400;
		color: #666666;
	}

	.next-text {
		color: #ffffff;
		font-size: 32rpx;
		font-weight: 500;
	}

	.prev-text {
		color: #333;
		font-size: 32rpx;
		font-weight: 500;
	}

	.submit-text {
		color: #ffffff;
		font-size: 32rpx;
		font-weight: 500;
	}

	.showziliao {
		width: 690rpx;
		height: 98rpx;
		background: #FF4767;
		border-radius: 49rpx;
	}

	.showziliaotext {
		height: 40rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #FFFFFF;
		line-height: 96rpx;
		font-style: normal;
		margin: 0 0 0 281rpx;
		align-items: center;
	}
</style>