<template>
	<view class="container" :style="appThemeStyle">
		<view class="reject" v-if="form.apply_status == 10">
			<u-alert-tips type="error" title="申请已提交:" description="请耐心等待工作人员的审核"></u-alert-tips>
		</view>
		<view class="reject" v-else-if="form.apply_status == 30">
			<u-alert-tips type="error" title="您的申请已被驳回:" :description="form.reject_reason"></u-alert-tips>
		</view>
		<u-form :model="form" ref="uForm" label-width="140rpx">
			<!-- 标题 -->
			<view class="page-title">基本信息</view>
			<view class="form-wrapper">
				<u-form-item label="站点名称" prop="company">
					<u-input v-model="form.company" :disabled="disabled" placeholder="请输入站点名称" />
				</u-form-item>
				<u-form-item label="门脸照" prop="shopImage">
					<u-upload ref="shopImage" :fileList="fileList1" :action="action" :header="headers"
						@delete="deletePic" index="1" name="file" :maxCount="1" @afterRead="afterRead">
					</u-upload>
				</u-form-item>
			</view>
			<!-- 标题 -->
			<view class="page-title">经营信息</view>
			<!-- 表单组件 -->
			<view class="form-wrapper">
				<u-form-item label="所在地区" prop="region">
					<!-- {{form.region}}
					<u-select v-if="show" :disabled="disabled" :list="cityList" v-model="form.region"></u-select>
					<text @click="openSelect">{{ cityName }}</text> -->
					<select-region ref="sRegion" :disabled="disabled" v-model="form.region" />
				</u-form-item>
				<u-form-item label="站点地址" prop="address">
					<u-input v-model="form.address" :disabled="disabled" placeholder="请输入站点地址" />
				</u-form-item>
				<u-form-item label="食品经营许可证" prop="shipincard">
					<u-upload ref="shipinCardImage" :fileList="fileList2" :action="action" :header="headers"
						@delete="deletePic" index="2" name="file" :maxCount="1">
					</u-upload>
				</u-form-item>
				<u-form-item label="法定代表人身份证" prop="sfz">
					<u-upload ref="sfzImage" :fileList="fileList3" :action="action" :header="headers"
						@delete="deletePic" index="3" name="file" :maxCount="2">
					</u-upload>
				</u-form-item>
				<u-form-item label="营业执照" prop="yyzz">
					<u-upload ref="yyzzImage" :fileList="fileList4" :action="action" :header="headers"
						@delete="deletePic" index="4" name="file" :maxCount="1">
					</u-upload>
				</u-form-item>
				<u-form-item label="姓名" prop="real_name">
					<u-input v-model="form.real_name" :disabled="disabled" placeholder="请输入姓名" />
				</u-form-item>
				<u-form-item label="手机号码" prop="mobile">
					<u-input v-model="form.mobile" maxlength="11" :disabled="disabled" placeholder="请输入手机号" />
				</u-form-item>
				<u-form-item label="微信号" prop="weixin">
					<u-input v-model="form.weixin" :disabled="disabled" placeholder="请输入微信号" />
				</u-form-item>
			</view>
		</u-form>
		<view class="btn">
			<u-button type="primary" shape="circle" @click="handleSubmit()">
				{{ submitText }}
			</u-button>
		</view>
		<view class="btn"></view>
	</view>
</template>

<script>
	import store from '@/store'
	import SelectRegion from '@/components/select-region/select-region'
	import {
		isMobile
	} from '@/utils/verify'
	import * as ApplyApi from '@/api/apply.js'
	import * as UploadApi from '@/api/upload'
	import * as RegionApi from '@/api/region.js'
	import SettingModel from '@/common/model/dealer/Setting'
	// 入驻类型
	const dataType = [
		"partner", // 合伙人
		"teamer", // 团长
		"delivery", // 配送员
		"personal" // 个人商户
	]

	// 表单字段元素
	const form = {
		// 入驻类型 （合伙人10001,配送员10002,社区门店10003,省代10004）
		grade_id: 10001,
		company: '',
		real_name: '',
		phone: '',
		mobile: '',
		region: [],
		detail: '',
		address: '',
		shop_image: '',
		shipin_card_image: '',
		sfz_image1: '',
		sfz_image2: '',
		yyzz_image: '',
		cityList: [],
	}

	// 表单验证规则
	const rules = {
		real_name: [{
			required: true,
			message: '请输入您的真实姓名',
			trigger: ['blur', 'change']
		}],
		company: [{
			required: true,
			message: '请输入您的商户名称',
			trigger: ['blur', 'change']
		}],
		address: [{
			required: true,
			message: '请输入站点地址',
			trigger: ['blur', 'change']
		}],
		weixin: [{
			required: true,
			message: '请输入微信号',
			trigger: ['blur', 'change']
		}],
		mobile: [{
			required: true,
			message: '请输入手机号',
			trigger: ['blur', 'change']
		}, {
			// 自定义验证函数
			validator: (rule, value, callback) => {
				// 返回true表示校验通过，返回false表示不通过
				return isMobile(value)
			},
			message: '手机号码不正确',
			// 触发器可以同时用blur和change
			trigger: ['blur'],
		}],
		region: [{
			required: true,
			message: '请选择省市区',
			trigger: ['blur', 'change'],
			type: 'array'
		}]
	}


	export default {
		components: {
			SelectRegion
		},
		data() {
			return {
				dataType,
				fileList1: [],
				fileList2: [],
				fileList3: [],
				fileList4: [],
				form,
				rules,
				show: false,
				cityName: '选择所在城市',
				// 按钮禁用
				disabled: false,
				submitText: '申请创建商户',

				// 文字设置
				words: undefined,
				// 显示入驻协议弹窗
				showLicense: false,
				// 入驻协议
				license: undefined,
				// 入驻协议阅读状态
				isRead: false,
				// 显示入驻协议弹窗
				showLicense: false,
				action: 'https://dev.gxwebsoft.com/ylx/api/upload/image',
				headers: {
					'storeId': 10001,
					'Access-Token': uni.getStorageSync('AccessToken'),
					'platform': store.getters.platform
				}
			}
		},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			const app = this
			app.getSetting()
			// 获取用户坐标及当前入驻申请记录
			app.getLocation((res) => {
				app.getData(res.longitude, res.latitude)
			})
			app.getRegion()
		},

		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},

		methods: {
			openSelect() {
				this.show = !this.show
			},
			// 删除图片
			deletePic(event) {
				if (this.disabled) {
					return false
				}
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 获取用户坐标
			// 参考文档：https://uniapp.dcloud.io/api/location/location?id=getlocation
			getLocation(callback) {
				const app = this
				uni.getLocation({
					type: 'wgs84',
					success: callback,
					fail(e) {
						app.$toast('获取定位失败，请点击右下角按钮重新尝试定位')
						app.isAuthor = false
					}
				})
			},

			// 加载数据
			getData(longitude, latitude) {
				const app = this
				app.form.longitude = longitude
				app.form.latitude = latitude
				ApplyApi.detail().then(res => {
					const detail = res.data.detail
					// 编辑信息
					if (detail) {
						app.form = detail
						if (detail.apply_status == 10) {
							app.submitText = '待审核'
						}
						if (detail.apply_status == 20) {
							app.submitText = '审核通过'
						}
						if (detail.apply_status == 30) {
							app.submitText = '重新提交'
						}
						app.createFormData(detail)
					}
				})
			},
			
			onAfterRead(e){
				console.log("e: ",e);
			},

			getRegion() {
				RegionApi.list({
					status: 20,
					level: 2
				}).then(res => {
					this.cityList = res.data.list.map(d => {
						return {
							label: d.name,
							value: d.id,
							code: d.code,
							id: d.id,
							name: d.name,
							pid: d.pid,
							status: d.status
						}
					})
				})
			},

			// 生成默认的表单数据
			createFormData(detail) {
				const {
					form
				} = this
				form.company = detail.company
				form.phone = detail.phone
				form.mobile = detail.mobile
				form.region = this.createRegion(detail)

				// 加载图片
				this.fileList1.push({
					'url': detail.shop_image
				})
				this.fileList2.push({
					'url': detail.shipin_card_image
				})
				this.fileList3.push({
					'url': detail.sfz_image1
				})
				this.fileList3.push({
					'url': detail.sfz_image2
				})
				this.fileList4.push({
					'url': detail.yyzz_image
				})

				// 是否可编辑
				this.disabled = true
				// 状态
				if (form.apply_status == 10) {
					this.submitText = '待审核'
				}
				if (form.apply_status == 20) {
					this.submitText = '审核通过'
				}
				if (form.apply_status == 30) {
					this.submitText = '重新提交'
					this.disabled = false
				}
			},

			createRegion(detail) {
				return [{
					label: detail.region.province,
					value: detail.province_id
				}, {
					label: detail.region.city,
					value: detail.city_id
				}, {
					label: detail.region.region,
					value: detail.region_id
				}]
			},

			// 获取分销设置
			getSetting() {
				const app = this
				SettingModel.data()
					.then(setting => {
						// 赋值属性
						app.words = setting.words.apply.words
						app.background = setting.background.apply
						app.license = setting.license.license
						// 设置当前页面标题
						app.setPageTitle(setting.words.apply.title)
					})
			},

			// 显示入驻协议弹窗
			handleShowLicense() {
				this.showLicense = true
			},

			// 设置当前页面标题
			setPageTitle(title) {
				uni.setNavigationBarTitle({
					title: '商户入驻'
				})
			},

			// 选择微信地址
			// #ifdef MP-WEIXIN
			chooseAddress() {
				const {
					form,
					$refs
				} = this
				uni.chooseAddress({
					success(res) {
						const names = $refs.sRegion.getOptionItemByNames(res)
						form.name = res.userName
						form.phone = res.telNumber
						form.detail = res.detailInfo
						form.region = names.length > 0 ? names : []
					}
				})
			},
			// #endif
			
			afterRead(e){
				console.log("e: ",e);
			},

			// 表单提交
			handleSubmit() {
				const app = this
				if (app.disabled) {
					return false
				}
				const {
					form
				} = this
				if(app.$refs.shopImage.lists.length == 0){
					app.$toast('请上传门脸照')
					return false
				}
				if(app.$refs.shipinCardImage.lists.length == 0){
					app.$toast('请上传食品经营许可证')
					return false
				}
				if(app.$refs.sfzImage.lists.length != 2){
					app.$toast('请上传法定代表人身份证正反面')
					return false
				}
				if(app.$refs.yyzzImage.lists.length == 0){
					app.$toast('请上传营业执照')
					return false
				}
				app.$refs.uForm.validate(valid => {
					if (valid) {
						// 上传图片
						if (app.fileList1.length == 0) {
							form.shop_image = app.$refs.shopImage.lists[0].response.data.fileInfo.preview_url;
						}
						if (app.fileList2.length == 0) {
							form.shipin_card_image = app.$refs.shipinCardImage.lists[0].response.data.fileInfo.preview_url;
						}
						if (app.fileList3.length == 0) {
							form.sfz_image1 = app.$refs.sfzImage.lists[0].response.data.fileInfo.preview_url;
							form.sfz_image2 = app.$refs.sfzImage.lists[1].response.data.fileInfo.preview_url;
						}
						if (app.fileList4.length == 0) {
							form.yyzz_image = app.$refs.yyzzImage.lists[0].response.data.fileInfo.preview_url;
						}
						form.phone = form.mobile
						ApplyApi.checkAvailable(form).then(res => {
							app.disabled = true
							app.onSubmit()
						})
					}
				})
			},

			// 提交到后端
			onSubmit() {
				const app = this
				const {
					form
				} = this
				let req;
				if (form.apply_status == 30) {
					req = ApplyApi.edit(form.apply_id, form)
				} else {
					console.log('add');
					req = ApplyApi.add(form)
				}
				req.then(result => {
						console.log("result: ", result);
						app.$toast(result.message)
						setTimeout(function() {
							uni.navigateBack()
						}, 2000)

					})
					.finally(() => app.disabled = false)
			}
		}
	}
</script>

<style>
	page {
		background: #f7f8fa;
	}
</style>
<style lang="scss" scoped>
	.page-title {
		width: 94%;
		margin: 0 auto;
		padding-top: 40rpx;
		font-size: 28rpx;
		color: rgba(69, 90, 100, 0.6);
	}

	.form-wrapper {
		margin: 20rpx auto 20rpx auto;
		padding: 0 40rpx;
		width: 94%;
		box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
		border-radius: 16rpx;
		background: #fff;
	}

	/* 底部操作栏 */

	.footer {
		margin-top: 80rpx;

		.btn-wrapper {
			height: 100%;
			// display: flex;
			// align-items: center;
			padding: 0 20rpx;
		}

		.btn-item {
			flex: 1;
			font-size: 28rpx;
			height: 86rpx;
			color: #fff;
			border-radius: 50rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.btn-item-wechat {
			background: #0ba90b;
			margin-bottom: 26rpx;
		}

		.btn-item-main {
			background: linear-gradient(to right, $main-bg, $main-bg2);

			// 禁用按钮
			&.disabled {
				opacity: 0.6;
			}
		}

	}

	// 上传凭证
	.row-voucher {
		padding: 24rpx 20rpx;

		.image-list {
			padding: 0 20rpx;
			margin-top: 20rpx;
			margin-bottom: -20rpx;

			&:after {
				clear: both;
				content: " ";
				display: table;
			}

			.image {
				display: block;
				width: 100%;
				height: 100%;
			}

			.image-picker,
			.image-preview {
				width: 184rpx;
				height: 184rpx;
				margin-right: 30rpx;
				margin-bottom: 30rpx;
				float: left;

				&:nth-child(3n+0) {
					margin-right: 0;
				}
			}

			.image-picker {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				border: 1rpx dashed #ccc;
				color: #ccc;

				.choose-icon {
					font-size: 48rpx;
					margin-bottom: 6rpx;
				}

				.choose-text {
					font-size: 24rpx;
				}
			}

			.image-preview {
				position: relative;

				.image-delete {
					position: absolute;
					top: -15rpx;
					right: -15rpx;
					height: 42rpx;
					width: 42rpx;
					background: rgba(0, 0, 0, 0.64);
					border-radius: 50%;
					color: #fff;
					font-weight: bolder;
					font-size: 22rpx;
					z-index: 10;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}
	}

	.form-license {
		padding: 20rpx;
	}

	.pops-content {
		padding: 20rpx;
	}

	.sfz,
	.sfz1,
	.sfz2,
	.yyzz {
		width: 140rpx;
		padding-top: 20rpx;
		padding-right: 10rpx;
	}

	.btn {
		width: 700rpx;
		margin: 20rpx auto;
		height: 100rpx;
	}

	.reject {
		width: 700rpx;
		margin: 20rpx auto;
	}
</style>
