<template>
	<view class="container">
		<!-- 顶部进度条（红底胶囊三段） -->
		<view class="step-bar">
			<view class="step-pill" :class="{ active: currentTab >= 1 }">填写信息</view>
			<view class="step-pill" :class="{ active: currentTab >= 4 }">提交审核</view>
			<view class="step-pill" :class="{ active: currentTab >= 5 }">入驻成功</view>
		</view>

		<!-- Tab 切换 -->
		<view class="tab-bar">
			<view class="tab-item" :class="{ active: currentTab === 1 }" @click="switchTab(1)">基本信息</view>
			<view class="tab-item" :class="{ active: currentTab === 2 }" @click="switchTab(2)">资质信息</view>
			<view class="tab-item" :class="{ active: currentTab === 3 }" @click="switchTab(3)">结算信息</view>
		</view>

		<!-- ============ Tab 1: 基本信息 ============ -->
		<view v-show="currentTab === 1">
			<!-- 文本字段 -->
			<view class="form-card">
				<view class="field">
					<view class="field-label"><text class="star">*</text>门店名称</view>
					<view class="field-input">
						<input type="text" v-model="store_name" placeholder="需与门牌照名称一致" />
					</view>
				</view>

				<view class="field">
					<view class="field-label"><text class="star">*</text>所在地区</view>
					<view class="field-input" @click="openRegion">
						<view class="field-value" :class="{ placeholder: !regionLabel }">
							{{ regionLabel || '请选择省/市/区' }}
						</view>
						<u-icon name="arrow-right" color="#C8C8C8" size="24"></u-icon>
					</view>
				</view>

				<view class="field">
					<view class="field-label"><text class="star">*</text>详细地址</view>
					<view class="field-input">
						<input type="text" v-model="address" placeholder="请输入详细地址" />
					</view>
				</view>

				<view class="field">
					<view class="field-label"><text class="star">*</text>商家类目</view>
					<view class="field-input" @click="openClassify">
						<view class="field-value" :class="{ placeholder: !confirmClassify.cate_name }">
							{{ confirmClassify.cate_name || '选择经营品类' }}
						</view>
						<u-icon name="arrow-right" color="#C8C8C8" size="24"></u-icon>
					</view>
				</view>

				<view class="field">
					<view class="field-label"><text class="star">*</text>营业状态</view>
					<view class="field-input" @click="showBizStatus = true">
						<view class="field-value" :class="{ placeholder: !bizStatusLabel }">
							{{ bizStatusLabel || '选择营业状态' }}
						</view>
						<u-icon name="arrow-right" color="#C8C8C8" size="24"></u-icon>
					</view>
				</view>

				<view class="field">
					<view class="field-label"><text class="star">*</text>联系人</view>
					<view class="field-input">
						<input type="text" v-model="contact_name" placeholder="请输入联系人姓名" />
					</view>
				</view>

				<view class="field">
					<view class="field-label"><text class="star">*</text>手机号</view>
					<view class="field-input">
						<input type="number" v-model="contact_phone" placeholder="请输入联系方式" maxlength="11" />
					</view>
				</view>
			</view>

			<!-- 店内环境 -->
			<view class="form-card">
				<view class="upload-section">
					<view class="upload-title">
						<text class="star">*</text>店内环境<text class="count">({{ imgList3.length }}/3张)</text>
					</view>
					<u-upload :fileList="imgList3" @afterRead="afterReadImg2" @delete="deletePic2" name="2" :maxCount="3" multiple>
						<view class="upload-add">
							<view class="upload-add-icon">+</view>
							<text>{{ imgList3.length }}/3</text>
						</view>
					</u-upload>
				</view>
			</view>

			<!-- 门头环境 -->
			<view class="form-card">
				<view class="upload-section">
					<view class="upload-title">
						<text class="star">*</text>门头环境<text class="count">({{ imgList.length }}/3张)</text>
					</view>
					<u-upload :fileList="imgList" @afterRead="afterReadImg" @delete="deletePic" name="1" :maxCount="3" multiple>
						<view class="upload-add">
							<view class="upload-add-icon">+</view>
							<text>{{ imgList.length }}/3</text>
						</view>
					</u-upload>
				</view>
			</view>

			<!-- 红色提示框 -->
			<view class="tip-box">
				<view class="tip-icon">!</view>
				<view class="tip-content">
					<view class="tip-title">门店信息要求</view>
					<view class="tip-item">· 门店名称需与门店招牌上的名称一致</view>
					<view class="tip-item">· 门店品类需与门店主要经营范围的分类一致</view>
					<view class="tip-item">· 门店地址需与门店实际经营地址一致</view>
				</view>
			</view>
		</view>

		<!-- Tab 2: 资质信息 -->
		<view v-show="currentTab === 2">
			<view class="Msg">
				<view class="row" v-if="enterType === 'enterprise'">
					<view class="row_label">统一社会信用代码<text class="red">*</text></view>
					<view class="row_con">
						<input type="text" v-model="credit_code" placeholder="请输入统一社会信用代码">
					</view>
				</view>
				<view class="row" v-if="enterType === 'enterprise'">
					<view class="row_label">法人姓名<text class="red">*</text></view>
					<view class="row_con">
						<input type="text" v-model="legal_person" placeholder="请输入法人姓名">
					</view>
				</view>
				<view class="row" v-if="enterType === 'enterprise'">
					<view class="row_label">法人身份证号<text class="red">*</text></view>
					<view class="row_con nonebor">
						<input type="text" v-model="legal_id_card" placeholder="请输入法人身份证号">
					</view>
				</view>
			</view>
			<view class="Msg mt">
				<view class="row2">
					<view class="row_label">营业执照<text class="red">*</text></view>
					<view class="row_con2">
						<u-upload :fileList="imgList5" @afterRead="afterReadImg3" @delete="deletePic3" name="1" :maxCount="1">
							<view class="imgCon">
								<image src="https://static.hshuishang.com/property-img-file/com_imageImg.png" mode="widthFix"></image>
								上传图片
							</view>
						</u-upload>
						<view class="example-link" @click="showExample('license')">查看示例</view>
					</view>
				</view>
				<view class="row2 mt2">
					<view class="row_label">{{ enterType === 'enterprise' ? '法人身份证正面' : '身份证正面' }}<text class="red">*</text></view>
					<view class="row_con2">
						<u-upload :fileList="idCardFrontList" @afterRead="afterReadIdFront" @delete="deleteIdFront" name="1" :maxCount="1">
							<view class="imgCon">
								<image src="https://static.hshuishang.com/property-img-file/com_imageImg.png" mode="widthFix"></image>
								上传图片
							</view>
						</u-upload>
						<view class="example-link" @click="showExample('idcard')">查看示例</view>
					</view>
				</view>
				<view class="row2 mt2">
					<view class="row_label">{{ enterType === 'enterprise' ? '法人身份证反面' : '身份证反面' }}<text class="red">*</text></view>
					<view class="row_con2">
						<u-upload :fileList="idCardBackList" @afterRead="afterReadIdBack" @delete="deleteIdBack" name="1" :maxCount="1">
							<view class="imgCon">
								<image src="https://static.hshuishang.com/property-img-file/com_imageImg.png" mode="widthFix"></image>
								上传图片
							</view>
						</u-upload>
					</view>
				</view>
			</view>
			<view class="btn-group">
				<view class="prevBtn" @click="currentTab = 1">上一步</view>
				<view class="nextBtn" @click="nextTab(3)">下一步</view>
			</view>
		</view>

		<!-- Tab 3: 结算信息 -->
		<view v-show="currentTab === 3">
			<view class="Msg">
				<template v-if="enterType === 'personal'">
					<view class="row">
						<view class="row_label">开户人姓名</view>
						<view class="row_con">
							<input type="text" v-model="account_name" placeholder="请输入开户人姓名">
						</view>
					</view>
					<view class="row">
						<view class="row_label">银行卡号</view>
						<view class="row_con">
							<input type="text" v-model="bank_card" placeholder="请输入银行卡号">
						</view>
					</view>
					<view class="row">
						<view class="row_label">开户银行</view>
						<view class="row_con">
							<input type="text" v-model="bank_name" placeholder="请输入开户银行">
						</view>
					</view>
					<view class="row">
						<view class="row_label">开户支行</view>
						<view class="row_con nonebor">
							<input type="text" v-model="bank_branch" placeholder="请输入开户支行">
						</view>
					</view>
				</template>
				<template v-else>
					<view class="row">
						<view class="row_label">企业开户名称</view>
						<view class="row_con">
							<input type="text" v-model="account_name" placeholder="请输入企业开户名称">
						</view>
					</view>
					<view class="row">
						<view class="row_label">对公银行账号</view>
						<view class="row_con">
							<input type="text" v-model="bank_card" placeholder="请输入对公银行账号">
						</view>
					</view>
					<view class="row">
						<view class="row_label">开户银行</view>
						<view class="row_con">
							<input type="text" v-model="bank_name" placeholder="请输入开户银行">
						</view>
					</view>
					<view class="row">
						<view class="row_label">开户支行</view>
						<view class="row_con nonebor">
							<input type="text" v-model="bank_branch" placeholder="请输入开户支行">
						</view>
					</view>
				</template>
			</view>
			<!-- 协议勾选 -->
			<view class="agreement">
				<view class="agreement-check" @click="agreeProtocol = !agreeProtocol">
					<u-icon :name="agreeProtocol ? 'checkmark-circle-fill' : 'checkmark-circle'" :color="agreeProtocol ? '#FF370B' : '#ccc'" size="36"></u-icon>
				</view>
				<view class="agreement-text">
					我已阅读并同意<text class="agreement-link" @click.stop="viewProtocol">《商家入驻协议》</text>
				</view>
			</view>
			<view class="btn-group">
				<view class="prevBtn" @click="currentTab = 2">上一步</view>
				<view class="nextBtn" @click="submit">提交入驻</view>
			</view>
		</view>

		<!-- 所在地区弹层（多列联动） -->
		<view class="popup-mask" v-if="showRegion" @click.self="showRegion = false">
			<view class="popup-sheet">
				<view class="popup-header">
					<text class="pop-cancel" @click="showRegion = false">取消</text>
					<text class="pop-title">所在地区</text>
					<text class="pop-confirm" @click="confirmRegion">确定</text>
				</view>
				<view class="popup-body" style="height: 50vh;">
					<scroll-view class="popup-col" scroll-y>
						<view v-for="item in pro" :key="item.ad_code"
							class="popup-col-item" :class="{ selected: tempProv.ad_code === item.ad_code }"
							@click="tapProv(item)">
							<text>{{ item.ad_name }}</text>
							<text class="check" v-if="tempProv.ad_code === item.ad_code">✓</text>
						</view>
					</scroll-view>
					<scroll-view class="popup-col" scroll-y>
						<view v-for="item in city" :key="item.ad_code"
							class="popup-col-item" :class="{ selected: tempCity.ad_code === item.ad_code }"
							@click="tapCity(item)">
							<text>{{ item.short_name }}</text>
							<text class="check" v-if="tempCity.ad_code === item.ad_code">✓</text>
						</view>
					</scroll-view>
					<scroll-view class="popup-col" scroll-y>
						<view v-for="item in buss" :key="item.ad_code"
							class="popup-col-item" :class="{ selected: tempBuss.ad_code === item.ad_code }"
							@click="tapBuss(item)">
							<text>{{ item.short_name }}</text>
							<text class="check" v-if="tempBuss.ad_code === item.ad_code">✓</text>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>

		<!-- 类目选择弹层（多选示意 + 搜索框） -->
		<view class="popup-mask" v-if="showClassifyPop" @click.self="showClassifyPop = false">
			<view class="popup-sheet">
				<view class="popup-header">
					<text class="pop-cancel" @click="showClassifyPop = false">取消</text>
					<text class="pop-title">选择类目</text>
					<text class="pop-confirm" @click="confirmClassifyPop">确定</text>
				</view>
				<view class="popup-search">
					<u-icon name="search" color="#B7B7B7" size="28"></u-icon>
					<text>搜索类目</text>
				</view>
				<scroll-view class="popup-list" scroll-y style="max-height: 50vh;">
					<view v-for="item in classify" :key="item.id"
						class="popup-list-item" :class="{ selected: tempClassify.id === item.id }"
						@click="tempClassify = item">
						{{ item.cate_name }}
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 营业状态弹层 -->
		<view class="popup-mask" v-if="showBizStatus" @click.self="showBizStatus = false">
			<view class="popup-sheet">
				<view class="popup-header">
					<text class="pop-cancel" @click="showBizStatus = false">取消</text>
					<text class="pop-title">营业状态</text>
					<text class="pop-confirm" @click="showBizStatus = false">确定</text>
				</view>
				<view class="popup-list">
					<view v-for="opt in bizStatusList" :key="opt.value"
						class="popup-list-item" :class="{ selected: bizStatus === opt.value }"
						@click="selectBizStatus(opt)">
						{{ opt.label }}
					</view>
				</view>
			</view>
		</view>

		<!-- 底部固定按钮：仅 Tab1 显示，其余 tab 沿用各自原按钮（暂未改造） -->
		<view class="bottom-bar" v-if="currentTab === 1">
			<view class="btn-primary" @click="nextTab(2)">下一步</view>
		</view>

	</view>
</template>

<script>
import {
	apiArr
} from '../../../api/v2local';

import { apiArr as MapApi } from '../../../api/area';
import {
	isPhone,
	picUrl,
	request,
	upload,
	NavgateTo
} from '../../../utils';
import { signPrivateView } from '../../../utils/uploadOSS.js';
export default {
	data() {
		return {
			picUrl,
			currentTab: 1,
			enterType: 'personal',
			area: "",
			confirmCity: "",
			confirmArea: "",
			confirmBusiness: "",
			imgList: [],
			imgList2: [],

			imgList3: [],
			imgList4: [],
			imgList5: [],
			imgList6: [],

			// 身份证照片
			idCardFrontList: [],
			idCardFrontPath: [],
			idCardBackList: [],
			idCardBackPath: [],

			contact_name: "",
			contact_phone: "",
			bank_card: "",
			bank_name: "",
			bank_branch: "",
			account_name: "",
			store_name: "",
			address: "",

			// 企业入驻额外字段
			credit_code: "",
			legal_person: "",
			legal_id_card: "",

			confirmProv: "",
			confirmCity: "",
			confirmBusiness: "",
			confirmClassify: "",
			pro: [],
			show: false,
			city: [],
			show2: false,
			buss: [],
			show3: false,
			classify: [],
			show4: false,

			itemObj: {},
			agreeProtocol: false,

			// 新版弹层相关
			showRegion: false,
			showClassifyPop: false,
			showBizStatus: false,
			tempProv: {},
			tempCity: {},
			tempBuss: {},
			tempClassify: {},
			bizStatus: 0, // 1 营业中 2 即将开业 3 休息中
			bizStatusList: [
				{ value: 1, label: '营业中' },
				{ value: 2, label: '即将开业' },
				{ value: 3, label: '休息中' },
			],
		}
	},
	computed: {
		regionLabel() {
			const a = this.confirmProv && this.confirmProv.ad_name
			const b = this.confirmCity && this.confirmCity.short_name
			const c = this.confirmBusiness && this.confirmBusiness.short_name
			if (!a) return ''
			return [a, b, c].filter(Boolean).join('/')
		},
		bizStatusLabel() {
			const opt = this.bizStatusList.find(o => o.value === this.bizStatus)
			return opt ? opt.label : ''
		},
	},
	methods: {
		// ===== 新版弹层交互 =====
		async openRegion() {
			if (!this.pro || !this.pro.length) await this.getPro()
			this.tempProv = this.confirmProv && this.confirmProv.ad_code ? this.confirmProv : {}
			this.tempCity = this.confirmCity && this.confirmCity.ad_code ? this.confirmCity : {}
			this.tempBuss = this.confirmBusiness && this.confirmBusiness.ad_code ? this.confirmBusiness : {}
			if (this.tempProv.ad_code) await this.getCity(this.tempProv.ad_code)
			if (this.tempCity.ad_code) await this.getBuss(this.tempCity.ad_code)
			this.showRegion = true
		},
		async tapProv(item) {
			this.tempProv = item
			this.tempCity = {}
			this.tempBuss = {}
			this.city = []
			this.buss = []
			await this.getCity(item.ad_code)
		},
		async tapCity(item) {
			this.tempCity = item
			this.tempBuss = {}
			this.buss = []
			await this.getBuss(item.ad_code)
		},
		tapBuss(item) {
			this.tempBuss = item
		},
		confirmRegion() {
			if (!this.tempProv.ad_code) {
				uni.showToast({ title: '请选择省', icon: 'none' }); return
			}
			if (!this.tempCity.ad_code) {
				uni.showToast({ title: '请选择市', icon: 'none' }); return
			}
			if (!this.tempBuss.ad_code) {
				uni.showToast({ title: '请选择区', icon: 'none' }); return
			}
			this.confirmProv = this.tempProv
			this.confirmCity = this.tempCity
			this.confirmBusiness = this.tempBuss
			this.showRegion = false
		},
		async openClassify() {
			if (!this.classify || !this.classify.length) await this.getClassify()
			this.tempClassify = this.confirmClassify && this.confirmClassify.id ? this.confirmClassify : {}
			this.showClassifyPop = true
		},
		confirmClassifyPop() {
			if (!this.tempClassify.id) {
				uni.showToast({ title: '请选择类目', icon: 'none' }); return
			}
			this.confirmClassify = this.tempClassify
			this.showClassifyPop = false
		},
		selectBizStatus(opt) {
			this.bizStatus = opt.value
			this.showBizStatus = false
		},

		switchTab(tab) {
			// 点击 Tab 切换时需要校验前面的 Tab
			if (tab > this.currentTab) {
				if (this.currentTab === 1 && !this.validateTab1()) return;
				if (tab === 3 && !this.validateTab2()) return;
			}
			this.currentTab = tab;
			uni.pageScrollTo({ scrollTop: 0, duration: 200 });
		},
		nextTab(tab) {
			if (tab === 2) {
				if (!this.validateTab1()) return;
			}
			if (tab === 3) {
				if (!this.validateTab2()) return;
			}
			this.currentTab = tab;
			uni.pageScrollTo({ scrollTop: 0, duration: 200 });
		},
		validateTab1() {
			// 基本信息校验
			if (!this.store_name) { uni.showToast({ title: '请输入门店名称', icon: 'none' }); return false; }
			if (!this.confirmProv.ad_code) { uni.showToast({ title: '请选择所在省', icon: 'none' }); return false; }
			if (!this.confirmCity.ad_code) { uni.showToast({ title: '请选择所在市', icon: 'none' }); return false; }
			if (!this.confirmBusiness.ad_code) { uni.showToast({ title: '请选择所在区', icon: 'none' }); return false; }
			if (!this.address) { uni.showToast({ title: '请输入详细地址', icon: 'none' }); return false; }
			if (!this.contact_name) { uni.showToast({ title: '请输入联系人姓名', icon: 'none' }); return false; }
			if (!this.contact_phone) { uni.showToast({ title: '请输入联系人手机号', icon: 'none' }); return false; }
			if (!isPhone(this.contact_phone)) { uni.showToast({ title: '联系人手机号格式不正确', icon: 'none' }); return false; }
			if (!this.confirmClassify.id) { uni.showToast({ title: '请选择商家分类', icon: 'none' }); return false; }
			return true;
		},
		validateTab2() {
			// 资质信息校验
			if (this.enterType === 'enterprise') {
				if (!this.credit_code) { uni.showToast({ title: '请输入统一社会信用代码', icon: 'none' }); return false; }
				if (!/^[0-9A-HJ-NPQRTUWXY]{18}$/.test(this.credit_code.toUpperCase())) {
					uni.showToast({ title: '统一社会信用代码格式不正确（18位）', icon: 'none' });
					return false;
				}
				if (!this.legal_person) { uni.showToast({ title: '请输入法人姓名', icon: 'none' }); return false; }
				if (!this.legal_id_card) { uni.showToast({ title: '请输入法人身份证号', icon: 'none' }); return false; }
				if (!/(^\d{15}$)|(^\d{17}([0-9X])$)/.test(this.legal_id_card.toUpperCase())) {
					uni.showToast({ title: '法人身份证号格式不正确', icon: 'none' });
					return false;
				}
			}
			if (!this.imgList6.length) { uni.showToast({ title: '请上传营业执照', icon: 'none' }); return false; }
			if (!this.idCardFrontPath.length) { uni.showToast({ title: '请上传身份证正面照片', icon: 'none' }); return false; }
			if (!this.idCardBackPath.length) { uni.showToast({ title: '请上传身份证反面照片', icon: 'none' }); return false; }
			return true;
		},
		validateTab3() {
			// 结算信息校验（个人 / 企业都需要银行四要素）
			if (!this.account_name) {
				uni.showToast({
					title: this.enterType === 'enterprise' ? '请输入企业开户名称' : '请输入开户人姓名',
					icon: 'none'
				});
				return false;
			}
			if (!this.bank_card) {
				uni.showToast({
					title: this.enterType === 'enterprise' ? '请输入对公银行账号' : '请输入银行卡号',
					icon: 'none'
				});
				return false;
			}
			if (!/^\d{15,20}$/.test(this.bank_card)) {
				uni.showToast({ title: '银行账号格式不正确（15-20位数字）', icon: 'none' });
				return false;
			}
			if (!this.bank_name) { uni.showToast({ title: '请输入开户银行', icon: 'none' }); return false; }
			if (!this.bank_branch) { uni.showToast({ title: '请输入开户支行', icon: 'none' }); return false; }
			return true;
		},
		showExample(type) {
			// 跳转到资质示例页
			NavgateTo('/packages/shopEnter/example/index?type=' + type);
		},

		// 身份证正面上传（私密 bucket，不能直链回显）
		afterReadIdFront(e) {
			const files = Array.isArray(e.file) ? e.file : [e.file]
			files.forEach(item => {
				upload(item.url, res => {
					// 私密文件：上传 UI 用本地预览，path 单独保存供提交
					this.idCardFrontList.push({ url: item.url })
					this.idCardFrontPath.push(res.data.path)
				}, 'merchant_private')
			})
		},
		deleteIdFront(e) {
			this.idCardFrontList.splice(e.index, 1);
			this.idCardFrontPath.splice(e.index, 1);
		},
		// 身份证反面上传（私密 bucket）
		afterReadIdBack(e) {
			const files = Array.isArray(e.file) ? e.file : [e.file]
			files.forEach(item => {
				upload(item.url, res => {
					this.idCardBackList.push({ url: item.url })
					this.idCardBackPath.push(res.data.path)
				}, 'merchant_private')
			})
		},
		deleteIdBack(e) {
			this.idCardBackList.splice(e.index, 1);
			this.idCardBackPath.splice(e.index, 1);
		},

		// 根据ad_code解析省市区信息
		parseAdCode(adCode) {
			if (!adCode) return;

			// 提取省级ad_code（前2位）
			const provinceCode = adCode.toString().substring(0, 2) + '0000';
			// 提取市级ad_code（前4位）
			const cityCode = adCode.toString().substring(0, 4) + '00';
			// 区县级ad_code（完整6位）
			const districtCode = adCode.toString();

			// 查找省份信息
			const province = this.pro.find(item => item.ad_code == provinceCode);
			if (province) {
				this.confirmProv = province;

				// 获取对应城市列表并查找城市信息
				this.getCity(provinceCode).then(() => {
					const city = this.city.find(item => item.ad_code == cityCode);
					if (city) {
						this.confirmCity = city;

						// 获取对应区县列表并查找区县信息
						this.getBuss(cityCode).then(() => {
							const district = this.buss.find(item => item.ad_code == districtCode);
							if (district) {
								this.confirmBusiness = district;
							}
						});
					}
				});
			}
		},

		cancelBuss() {
			this.show3 = false;
		},
		clickBuss(e) {
			this.show3 = false;
			this.confirmBusiness = e.value[0]
		},

		cancelCity() {
			this.show2 = false;
		},
		clickCity(e) {
			this.show2 = false;
			this.getBuss(e.value[0].ad_code)
			this.confirmCity = e.value[0]
		},

		cancelPro() {
			this.show = false;
		},
		clickPro(e) {
			this.show = false;
			this.getCity(e.value[0].ad_code)
			this.confirmProv = e.value[0]
		},
		cancelClassify() {
			this.show4 = false;
		},
		clickClassify(e) {
			this.show4 = false;
			this.confirmClassify = e.value[0]
		},
		chooseCity() {
			this.show = true;
		},
		chooseCity2() {
			this.show2 = true;
		},
		chooseCity3() {
			this.show3 = true;
		},
		chooseClassify() {
			this.show4 = true;
		},
		afterReadImg(e) {
			e.file.forEach(item => {
				upload(item.url, res => {
					this.imgList.push({ url: this.picUrl + res.data.path })
					this.imgList2.push(res.data.path)
				})
			})
		},
		deletePic(e) {
			this.imgList.splice(e.index, 1);
			this.imgList2.splice(e.index, 1);
		},

		afterReadImg2(e) {
			e.file.forEach(item => {
				upload(item.url, res => {
					this.imgList3.push({ url: this.picUrl + res.data.path })
					this.imgList4.push(res.data.path)
				})
			})
		},
		afterReadImg3(e) {
			// 营业执照（私密 bucket）
			const files = Array.isArray(e.file) ? e.file : [e.file]
			files.forEach(item => {
				upload(item.url, res => {
					this.imgList5.push({ url: item.url })
					this.imgList6.push(res.data.path)
				}, 'merchant_private')
			})
		},
		deletePic2(e) {
			this.imgList3.splice(e.index, 1);
			this.imgList4.splice(e.index, 1);
		},
		deletePic3(e) {
			this.imgList5.splice(e.index, 1);
			this.imgList6.splice(e.index, 1);
		},
		viewProtocol() {
			// 查看商家入驻协议
			uni.showModal({
				title: '商家入驻协议',
				content: '本协议是您与平台之间关于商家入驻服务的法律协议。入驻后您需遵守平台规则，按时提供商品或服务，保证信息真实有效。平台有权对违规商家进行处罚。',
				showCancel: false,
				confirmText: '我知道了'
			});
		},
		// 给私密 bucket 中的多张图批量签名 URL，写到目标 fileList
		async signPrivatePaths(paths, listKey) {
			if (!paths || !paths.length) {
				this[listKey] = []
				return
			}
			const result = []
			for (const p of paths) {
				try {
					const r = await signPrivateView(p)
					result.push({ url: r.url })
				} catch (e) {
					console.error('签发私密 URL 失败:', p, e)
					result.push({ url: '' })
				}
			}
			this[listKey] = result
		},
		submit() {
			let that = this
			if (!that.validateTab3()) return;
			if (!that.agreeProtocol) {
				uni.showToast({ title: '请先阅读并同意商家入驻协议', icon: 'none' });
				return;
			}
			let interior_photo = that.imgList4.join(",")
			let facade_photo = that.imgList2.join(",")
			let license_photo = that.imgList6.join(",")
			let id_card_front = that.idCardFrontPath.join(",")
			let id_card_back = that.idCardBackPath.join(",")

			let params = {
				enter_type: that.enterType === 'enterprise' ? 2 : 1,
				contact_name: that.contact_name,
				phone: that.contact_phone,
				bank_card: that.bank_card,
				bank_name: that.bank_name,
				bank_branch: that.bank_branch,
				account_name: that.account_name,
				merchant_name: that.store_name,
				address: that.address,
				ad_code: that.confirmBusiness.ad_code,
				facade_photo,
				interior_photo,
				license_photo,
				id_card_front,
				id_card_back,
				merchant_cate_id: that.confirmClassify.id,
			}

			if (that.enterType === 'enterprise') {
				params.credit_code = that.credit_code;
				params.legal_person = that.legal_person;
				params.legal_id_card = that.legal_id_card;
				params.account_type = 2;
			} else {
				params.account_type = 1;
			}

			request(apiArr.createStore, "POST", params).then(res => {
				// 提交成功后用最新表单 + 服务端返回拼一个 itemObj 给 auditStatus 页用
				const newItem = {
					...params,
					id: res && res.id,
					status: 1,
					create_time: new Date().toLocaleString('sv-SE').replace('T', ' '),
					handle_time: '',
					merchant_code: '',
					remark: ''
				}
				NavgateTo("../auditStatus/index?itemObj=" + encodeURIComponent(JSON.stringify(newItem)))
			}).catch(res => {
				const msg = res && res.message ? res.message : '提交失败，请稍后重试'
				if (msg.includes("agent_nil")) {
					uni.showModal({
						title: '提交失败',
						content: '未找到对应的代理商信息，请联系平台',
						showCancel: false
					})
					return
				}
				// 其余后端校验错误统一弹窗，避免被吞
				uni.showModal({
					title: '提交失败',
					content: msg,
					showCancel: false
				})
			})
		},

		// 省市区
		getPro() {
			return request(MapApi.getArea, "POST", {}, {}, false).then(res => {
				this.pro = res.rows
			})
		},
		getCity(e) {
			return request(MapApi.getArea, "POST", {
				parent_ad_code: e
			}, {}, false).then(res => {
				this.city = res.rows
			})
		},
		getBuss(e) {
			return request(MapApi.getArea, "POST", {
				parent_ad_code: e
			}, {}, false).then(res => {
				this.buss = res.rows
			})
		},
		getClassify() {
			const params = {
				is_shop: 1,
			}
			return request(apiArr.getMerChantCateList, "POST", params, {}, false).then(res => {
				this.classify = res.rows
			})
		},

	},
	onLoad(options) {
		// 获取入驻类型
		if (options.enterType) {
			this.enterType = options.enterType;
		}

		// 先执行数据获取方法
		Promise.all([this.getPro(), this.getClassify()]).then(() => {
			// 数据获取完成后再进行赋值操作（编辑回显）
			if (options.itemObj) {
				this.itemObj = JSON.parse(options.itemObj)
				this.store_name = this.itemObj.merchant_name
				this.address = this.itemObj.address
				this.contact_name = this.itemObj.contact_name
				this.contact_phone = this.itemObj.phone
				this.confirmClassify = this.classify.find(item => item.id == this.itemObj.merchant_cate_id)
				this.bank_card = this.itemObj.bank_card
				this.bank_name = this.itemObj.bank_name || ''
				this.bank_branch = this.itemObj.bank_branch || ''
				this.account_name = this.itemObj.account_name || ''
				this.credit_code = this.itemObj.credit_code || ''
				this.legal_person = this.itemObj.legal_person || ''
				this.legal_id_card = this.itemObj.legal_id_card || ''

				// 入驻类型回显
				if (this.itemObj.enter_type === 2) {
					this.enterType = 'enterprise';
				}

				// 解析ad_code回显省市区
				if (this.itemObj.ad_code) {
					this.parseAdCode(this.itemObj.ad_code);
				}
				this.imgList = this.itemObj.facade_photo ? this.itemObj.facade_photo.split(",").map(item => ({ url: this.picUrl + item })) : []
				this.imgList2 = this.itemObj.facade_photo ? this.itemObj.facade_photo.split(",") : []
				this.imgList3 = this.itemObj.interior_photo ? this.itemObj.interior_photo.split(",").map(item => ({ url: this.picUrl + item })) : []
				this.imgList4 = this.itemObj.interior_photo ? this.itemObj.interior_photo.split(",") : []

				// 营业执照、身份证 —— 私密 bucket，需要签名 URL 才能回显
				this.imgList6 = this.itemObj.license_photo?.split(",").filter(Boolean) || []
				this.idCardFrontPath = this.itemObj.id_card_front ? this.itemObj.id_card_front.split(",").filter(Boolean) : []
				this.idCardBackPath = this.itemObj.id_card_back ? this.itemObj.id_card_back.split(",").filter(Boolean) : []
				this.signPrivatePaths(this.imgList6, 'imgList5')
				this.signPrivatePaths(this.idCardFrontPath, 'idCardFrontList')
				this.signPrivatePaths(this.idCardBackPath, 'idCardBackList')
			}
		})
	}
}
</script>

<style>
@import url("./index.css");
</style>
