<script setup>
	/**
	 * 商家入驻
	 * 进入页面获取最新的数据 如果发生变化 同步用户信息
	 * 1 待申请 显示入驻须知 是否缴纳押金
	 * 2 已申请/待审核 已缴纳押金并且提交表单
	 * 3 审核驳回 可选择取消押金 或 修改表单内容继续提交审核
	 * 4 审核成功 已成为商家 可选择取消商家身份 拿回押金 修改店铺信息重新提交审核
	 */
	import {
		ref,
		reactive,
		computed,
		getCurrentInstance,
	} from 'vue';
	import {
		onLoad,
		onReady,
	} from '@dcloudio/uni-app';
	// vuex
	import {
		useStore
	} from 'vuex'
	// 
	import api from '@/api/index.js';
	// 工具库
	import util from '@/common/js/util.js'
	// 选择省市区
	import regionSelection from '@/components/public/regionSelection/regionSelection.vue';
	// 二级密码验证
	import payPwd from '@/components/mine/payPwd.vue'
	// 
	const store = useStore()
	const {
		proxy
	} = getCurrentInstance();
	// 表单
	const form = reactive({
		rectangleLogo: '',
		qualificationPicture: [],
		idCardFront: '',
		idCardBack: '',
	})
	// 当前模式 code 0待缴纳1待申请2待审核3已通过4已拒绝 form表单
	const mode = reactive({
		code: 0,
	})
	// 文本内容
	const content = ref({})
	// 字典列表
	const dictList = reactive([])
	// 选择下标分类
	const dictIndex = ref('')
	// 二级密码回调
	const pwdCb = ref('')
	// 用户信息
	const userinfo = computed(() => {
		return store.state.userinfo
	})

	onLoad(() => {
		// 获取商家入驻状态
		getShopStatus()
	})

	onReady(() => {
		// 测试缴纳接口
		// callPwd('depositsPay')
	})

	// 获取表单信息
	function getForm() {
		Promise.all([getDetail(), getDict()]).then(rs => {
			// 获取详情
			const detail = rs[0]
			// 获取字典分类
			const dict = rs[1]
			if (!detail) return
			form.id = detail.id
			form.rectangleLogo = detail.rectangleLogo
			form.qualificationPicture = detail.qualificationPicture.split(',')
			form.idCardFront = detail.idCardFront
			form.idCardBack = detail.idCardBack
			form.name = detail.name
			form.phone = detail.phone
			form.addressDetail = detail.addressDetail
			form.categoryId = detail.categoryId
			form.province = detail.province
			form.city = detail.city
			form.district = detail.district
			// 赋值
			dictIndex.value = dict.findIndex(item => item.id == detail.categoryId)
		})
	}

	// 获取申请信息
	function getDetail() {
		return new Promise((resolve, reject) => {
			api.shop.getStoreDetail().then(rs => {
				if (rs.code == 200) {
					resolve(rs.data)
					return
				}
				util.alert({
					showCancel: false,
					content: rs.msg,
				})
			})
		})
	}

	// 切换模式code
	function handleModeCode(code) {
		// 模式
		mode.code = code
		switch (code) {
			case 0:
				// 获取文章
				getarticle()
				break;
			case 1:
				// 获取文章
				getarticle()
				break;
			case 'form':
				// 获取表单信息
				getForm()
				break;
		}
	}

	// 获取字典分类
	function getDict() {
		return new Promise((resolve, reject) => {
			api.shop.categoryAll({}).then(rs => {
				if (rs.code == 200) {
					resolve(rs.data)
					dictList.length = 0
					dictList.push(...rs.data)
					resolve()
					return
				}
				util.alert({
					showCancel: false,
					content: rs.msg,
				})
			})
		})
	}

	// 获取商家入驻状态
	function getShopStatus() {
		api.shop.getShopStatus().then(rs => {
			if (rs.code == 200) {
				Object.assign(mode, rs.data)
				handleModeCode(mode.code)
				return
			}
			util.alert({
				showCancel: false,
				content: rs.msg,
			})
		})
	}

	// 商家缴纳押金
	function depositsPay() {
		api.shop.depositsPay().then(rs => {
			if (rs.code == 200) {
				// 修改状态 变为已缴纳
				mode.code = 1
				return
			}
			util.alert({
				showCancel: false,
				content: rs.msg,
			})
		})
	}

	// 获取文章
	function getarticle() {
		api.getArticle({
			query: {
				agreementId: 4,
			},
		}).then(rs => {
			if (rs.code == 200) {
				content.value = rs.data
				return
			}
			util.alert({
				showCancel: false,
				content: rs.msg,
			})
		})
	}

	/**
	 * 上传图片
	 * @param {String} key 键值
	 * @param {String} type 类型 1单 2多
	 */
	function uploadImg(key, type) {
		util.upload_image({
			value: form[key],
			success: rs => {
				switch (type) {
					case 1:
						form[key] = rs.value
						break
					case 2:
						form[key].push(rs.value)
						break
				}
			},
		})
	}

	/**
	 * 移除文件
	 * @param {Number} index 下标
	 * @param {String} key 键
	 */
	function removeMedia(index, key) {
		util.alert({
			content: '确认删除？',
		}).then(rs => {
			if (rs.confirm) form[key].splice(index, 1)
		})
	}

	/**
	 * 选择省市区
	 * @param {Object} ev
	 */
	function handleRegion(ev) {
		console.log('handleRegion', ev)
		form.province = ev.province.regionName
		form.city = ev.city.regionName
		form.district = ev.area.regionName
	}

	/**
	 * 切换产品分类
	 * @param {Object} ev 默认事件
	 */
	function handleDict(ev) {
		if (!ev || typeof ev.detail.value === 'undefined') {
			console.error('Invalid event object or missing value');
			return
		}
		const index = ev.detail.value;
		if (index === dictIndex.value) return;
		if (index >= 0 && index < dictList.length) {
			dictIndex.value = index;
			form.categoryId = dictList[index].id;
		} else {
			console.error('Invalid index:', index);
		}
	}

	// 商家入驻
	function handleSubmit() {
		const data = {
			...form
		}
		console.log('data', data)

		// 验证必填项
		if (!data.rectangleLogo) {
			util.alert('商家头像不能为空')
			return
		}
		if (!data.name) {
			util.alert('商家名称不能为空')
			return
		}
		if (!data.phone) {
			util.alert('联系方式不能为空')
			return
		}
		if (!data.province) {
			util.alert('产品所在地不能为空')
			return
		}
		if (!data.categoryId) {
			util.alert('产品类别不能为空')
			return
		}
		if (!data.qualificationPicture[0]) {
			util.alert('营业执照不能为空')
			return
		}
		if (!data.idCardFront) {
			util.alert('身份证正面不能为空')
			return
		}
		if (!data.idCardBack) {
			util.alert('身份证反面不能为空')
			return
		}
		// 营业执照
		data.qualificationPicture = data.qualificationPicture.join(',')

		api.shop.application({
			data: data,
		}).then(rs => {
			if (rs.code === 200) {
				util.alert({
					content: '资料已申请，请等待后台审核',
					showCancel: false,
				}).then(rs => {
					uni.navigateBack()
				})
			} else {
				util.alert({
					content: rs.msg,
					showCancel: false,
				})
			}
		})
	}

	// 退出缴纳押金
	function outDepositsPayAlt() {
		util.alert({
			content: '确认缴纳押金并放弃商家身份？',
		}).then(rs => {
			if (!rs.confirm) return
			// 调用二级密码
			callPwd('outDepositsPay')
		})
	}

	// 商家退出押金
	function outDepositsPay() {
		// 商家退出押金
		api.shop.outDepositsPay().then(rs => {
			if (rs.code == 200) {
				// 修改状态 变为待缴纳
				handleModeCode(0)
				return
			}
			util.alert({
				showCancel: false,
				content: rs.msg,
			})
		})
	}

	/**
	 * 调用二级密码
	 * @param {Object} key 后续方法key
	 */
	function callPwd(key) {
		util.isAuth({
			success: () => {
				pwdCb.value = {
					// 缴纳押金
					'depositsPay': depositsPay,
					// 取消押金并退出商家身份
					'outDepositsPay': outDepositsPay,
				} [key]
				console.log('pwdCb', pwdCb.value)
				// 拉起弹窗
				proxy.$refs.payPwdRef.open()
			}
		})
	}

	// 二级密码验证
	function handlePayPwd() {
		// 执行二级密码确认回调	
		pwdCb.value()
	}
</script>

<template>
	<!-- 须知 -->
	<template v-if="[0,1].includes(mode.code)">
		<view class="app">
			<view class="notice oh mtb30 mlr30 plr30 ptb20 bfff br20">
				<view class="title tac f34 c333 b">商家入驻须知</view>
				<view class="content mtb50">
					<rich-text :nodes="content.content"></rich-text>
				</view>
			</view>

			<view class="tac c666 f28">继续即代表同意《商家入驻须知》</view>

			<view class="fill" style="height: 160rpx;" />

			<view class="footer plr30 bfff shadow">
				<!-- 未缴纳押金 -->
				<template v-if="mode.code == 0">
					<view class="btn black" @click="callPwd('depositsPay')">缴纳押金</view>
				</template>
				<template v-else>
					<view class="rows">
						<view class="btn cancel plr30" @click="outDepositsPayAlt">退回押金</view>
						<view class="btn colourful f1" @click="handleModeCode('form')">申请入驻</view>
					</view>
				</template>
			</view>
		</view>
	</template>

	<!-- 待审核 -->
	<template v-else-if="mode.code == 2">
		<view class="app">
			<view class="result ver">
				<uni-icons type="checkbox-filled" color="#20D200" size="160rpx" />
				<view class="title mtb30 f34">申请中</view>
				<view class="value f30">
					<text class="c333">提交成功，请等待后台审核</text>
				</view>
			</view>

			<view class="fill" style="height: 160rpx;"></view>

			<view class="footer rows plr30 bfff shadow">
				<view class="btn cancel f1" @click="outDepositsPayAlt">取消申请并退回押金</view>
			</view>
		</view>
	</template>

	<!-- 审核驳回 -->
	<template v-else-if="mode.code == 4">
		<view class="app">
			<view class="result ver">
				<uni-icons type="clear" color="#ff0000" size="160rpx" />
				<view class="title mtb30 f34">审核驳回</view>
				<view class="value f30">
					<text class="c666">驳回原因：</text>
					<text class="c333">{{mode.msg}}</text>
				</view>
				<view class="reject mtb30 c666 f28">
					<view>驳回结果异议？ 可在个人中心-设置里面联系我们</view>
				</view>
			</view>

			<view class="fill" style="height: 160rpx;"></view>

			<view class="footer rows plr30 bfff shadow">
				<view class="btn cancel plr30" @click="outDepositsPayAlt">退回押金</view>
				<view class="btn colourful f1" @click="handleModeCode('form')">修改信息</view>
			</view>
		</view>
	</template>

	<!-- 申请成功 -->
	<template v-else-if="mode.code == 3">
		<view class="app">
			<view class="result ver">
				<uni-icons type="checkbox-filled" color="#20D200" size="160rpx" />
				<view class="title mtb30 f34">恭喜您，您已成为商家</view>
			</view>

			<view class="fill" style="height: 160rpx;"></view>

			<view class="footer plr30 bfff shadow">
				<view class="btn cancel plr30" @click="outDepositsPayAlt">退回押金并放弃商家身份</view>
			</view>
		</view>
	</template>

	<!-- 表单申请 -->
	<template v-else-if="mode.code == 'form'">
		<view class="appbw plr30">
			<!-- 头像 -->
			<view class="avatarBox ver mt50">
				<view class="avatar oh pr wh220 br20" @click="uploadImg('rectangleLogo',1)">
					<image class="img br20" :src="form.rectangleLogo" mode="aspectFill" v-if="form.rectangleLogo" />
					<view class="pfull fmid" v-else>
						<uni-icons type="plusempty" color="#999" size="80rpx" />
					</view>
				</view>
				<view class="name mt20 c666 f24">店铺头像</view>
			</view>

			<!-- 表单 -->
			<view class="form mt60 c333 f32">
				<view class="title  f36">我的资料</view>

				<view class="item rows ptb20">
					<view class="key c666">店铺名称</view>
					<view class="value f1 ml20 tar">
						<input v-model="form.name" type="text" placeholder="请输入店铺名称" />
					</view>
				</view>

				<view class="item rows ptb20">
					<view class="key c666">联系方式</view>
					<view class="value f1 ml20 tar">
						<input v-model="form.phone" type="number" placeholder="请输入联系方式" />
					</view>
				</view>

				<view class="item rows ptb20" @click="$refs.regionSelectionRef.open()">
					<view class="key c666">产品所在地</view>
					<view class="value f1 ml20 tar">
						<!-- 省市区选择 -->
						<regionSelection ref="regionSelectionRef" :province="form.province" :city="form.city"
							:area="form.district" @change="handleRegion" />
					</view>
				</view>

				<view class="item rows ptb20">
					<view class="key c666">详细所在地</view>
					<view class="value f1 ml20 tar">
						<input v-model="form.addressDetail" type="text" placeholder="请选择产品所在地" />
					</view>
				</view>

				<view class="item ptb20">
					<picker :range="dictList" range-key="name" :vlaue="dictIndex" @change="handleDict">
						<view class="rows">
							<view class="key c666">产品类别</view>
							<view class="value f1 ml20 tar">
								<text class="placeholderStyle" v-if="dictIndex === ''">请选择产品类别</text>
								<text v-else>{{dictList[dictIndex].name}}</text>
							</view>
						</view>
					</picker>
				</view>

				<view class="item ptb20">
					<view class="key c666">营业执照</view>
					<view class="value imgList f1 mt20 tar">
						<view class="imgs wh200" v-for="(item, index) in form.qualificationPicture" :key="index">
							<image class="img br10" :src="item" mode="aspectFill" />
							<view class="close" @click="removeMedia(index,'qualificationPicture')">
								<uni-icons type="clear" size="50rpx" color="#f00" />
							</view>
						</view>
						<view class="upload imgs fmid wh200 br10" @click="uploadImg('qualificationPicture',2)">
							<uni-icons type="plusempty" color="#E8E8E8" size="80rpx" />
						</view>
					</view>
				</view>

				<view class="item ptb20">
					<view class="key c666">身份证正面</view>
					<view class="value imgList f1 mt20 tar">
						<view class="imgs wh200" v-if="form.idCardFront" @click="uploadImg('idCardFront',1)">
							<image class="img br10" :src="form.idCardFront" mode="aspectFill" />
						</view>
						<view class="upload imgs fmid wh200 br10" v-else @click="uploadImg('idCardFront',1)">
							<uni-icons type="plusempty" color="#E8E8E8" size="80rpx" />
						</view>
					</view>
				</view>

				<view class="item ptb20">
					<view class="key c666">身份证反面</view>
					<view class="value imgList f1 mt20 tar">
						<view class="imgs wh200" v-if="form.idCardBack" @click="uploadImg('idCardBack',1)">
							<image class="img br10" :src="form.idCardBack" mode="aspectFill" />
						</view>
						<view class="upload imgs fmid wh200 br10" v-else @click="uploadImg('idCardBack',1)">
							<uni-icons type="plusempty" color="#E8E8E8" size="80rpx" />
						</view>
					</view>
				</view>

			</view>
			<view class="fill" style="height: 150rpx;"></view>
		</view>

		<view class="footer plr30 bfff shadow">
			<view class="rows">
				<view class="btn cancel plr30" @click="outDepositsPayAlt">退回押金</view>
				<view class="btn colourful f1" @click="handleSubmit">申请入驻</view>
			</view>
		</view>
	</template>

	<!-- 二级密码 -->
	<payPwd ref="payPwdRef" :check="true" @confirm="handlePayPwd" />
</template>

<style lang="scss">
	.img {
		width: 100%;
		height: 100%;
	}

	// 头像
	.avatar {
		background-color: #F6F8FE;
	}

	// 上传
	.upload {
		background-color: #f4f4ff;
	}

	// 审核结果
	.result {
		margin-top: 30rpx;
		padding: 50rpx 0;
		background-color: #fff;
	}

	// 发布
	.menu {
		.line {
			padding: 20rpx 10rpx;

			&+.line {
				border-top: 2rpx solid #eee;
			}
		}
	}
</style>