<template>
	<view class="container" :style="appThemeStyle">

		<!-- 表单组件 -->
		<view class="form-wrapper">
			<u-form :model="form" ref="uForm" label-width="140rpx">
				<u-form-item label="所在地区" prop="region">
					<select-region ref="sRegion" :disabled="disabled" v-model="form.region" />
				</u-form-item>
				<u-form-item label="公司名称" prop="company">
					<u-input v-model="form.company" :disabled="disabled" placeholder="请输入公司名称" />
				</u-form-item>
				<u-form-item label="联系电话" prop="phone">
					<u-input v-model="form.phone" :disabled="disabled" placeholder="请输入联系电话" />
				</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 v-for="(item,imageIndex) in imageList" :key="imageIndex" :label="itemLabel[imageIndex]"
					:prop="itemProp[imageIndex]">
					<view class="image-preview">
						<image mode="widthFix" :src="item.path" class="sfz" @click="chooseImage(imageIndex)"></image>
						<text class="image-delete iconfont icon-shanchu" @click="deleteImage(imageIndex)"></text>
					</view>
				</u-form-item>
				<view class="form-license dis-flex flex-x-center flex-y-center">
					<view class="license-radio dis-flex flex-y-center" @click="isRead = !isRead">
						<text class="license-icon f-38 iconfont icon-radio"
							:class="[isRead ? 'c-violet' : 'col-bb']"></text>
						<text class="f-28 col-80">我已阅读并了解{{words}}</text>
					</view>
					<text @click="handleShowLicense()" class="f-28 c-violet">【{{ words.license.value }}】</text>
				</view>
			</u-form>
		</view>
		<!-- 操作按钮 -->
		<view class="footer">
			<view class="btn-wrapper">
				<view class="btn-item btn-item-main" :class="{ disabled }" @click="handleSubmit()">{{ submitText }}
				</view>
			</view>
		</view>
		<!-- 入驻协议弹窗 -->
		<u-modal v-model="showLicense" title="申请协议">
			<scroll-view class="pops-content" :scroll-y="true">
				<text>{{ license }}</text>
			</scroll-view>
		</u-modal>
	</view>
</template>

<script>
	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 SettingModel from '@/common/model/dealer/Setting'
	// 入驻类型
	const dataType = [
		"partner",  	// 合伙人
		"teamer",  		// 团长
		"delivery",  	// 配送员
		"personal"  	// 个人商户
	]
	// 图片上传类型
	const itemProp = ["sfz", "yyzz"]
	// 图片上传名称
	const itemLabel = ["身份证", "营业执照"]

	// 用户选择的图片列表
	const imageList = [{
			path: 'http://dev.gxwebsoft.com/hainiu/uploads/10001/20220522/6b52b67ed9291757163c10ef96be1a54.png',
			size: 100
		},
		{
			path: 'http://dev.gxwebsoft.com/hainiu/uploads/10001/20220522/55faad35f5ee30f3e8791bdfd2f75eb9.png',
			size: 100
		}
	]

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

	// 表单验证规则
	const rules = {
		real_name: [{
			required: true,
			message: '请输入您的真实姓名',
			trigger: ['blur', 'change']
		}],
		company: [{
			required: true,
			message: '请输入您的公司名称',
			trigger: ['blur', 'change']
		}],
		phone: [{
			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'
		}],
		detail: [{
			required: true,
			message: '请输入详细地址',
			trigger: ['blur', 'change']
		}],
	}

	const maxImageLength = 2

	export default {
		components: {
			SelectRegion
		},
		data() {
			return {
				dataType,
				itemProp,
				itemLabel,
				imageList,
				form,
				rules,
				// 按钮禁用
				disabled: false,
				submitText: '提交申请',

				// 文字设置
				words: undefined,
				// 显示入驻协议弹窗
				showLicense: false,
				// 入驻协议
				license: undefined,
				// 入驻协议阅读状态
				isRead: false,
				// 显示入驻协议弹窗
				showLicense: false,
			}
		},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			this.getSetting()
			this.getData()
		},

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

		methods: {
			// 加载数据
			getData() {
				const app = this
				ApplyApi.detail().then(res => {
					const detail = res.data.detail
					// 编辑信息
					if (detail) {
						app.form = detail
						app.createFormData(detail)
					}
				})
			},

			// 生成默认的表单数据
			createFormData(detail) {
				const {
					form
				} = this
				form.company = detail.company
				form.phone = detail.phone
				form.region = this.createRegion(detail.shop)
				// 是否可编辑
				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
				}

				// 加载图片
				this.imageList = detail.images.map(d => {
					return {
						path: d.image_url,
						size: 101
					}
				})
				form.images = detail.images.map(d => {
					return d.image_id
				})
			},

			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() {
				console.log("setting: ");
				const app = this
				SettingModel.data()
					.then(setting => {
						// 赋值属性
						app.words = setting.words.apply.words
						app.background = setting.background.apply
						app.license = setting.license.license
					})
			},

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

			// 选择图片
			chooseImage(imageIndex) {
				const app = this
				const oldImageList = app.imageList
				const {
					form
				} = this
				// 是否可编辑
				if (form.apply_status && form.apply_status != 30) {
					app.disabled = true
					return false
				}
				// 选择图片
				uni.chooseImage({
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success({
						tempFiles
					}) {
						// 删除第imageIndex个元素，并在数组的第imageIndex个位置添加新元素:
						app.imageList.splice(imageIndex, 1, tempFiles[0])
					}
				});
			},

			// 删除图片
			deleteImage(imageIndex) {
				const {
					disabled
				} = this
				if (disabled == true) {
					return false
				}

				this.imageList[imageIndex].path = '../../static/not-dealer.png'
			},

			// 选择微信地址
			// #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

			// 表单提交
			handleSubmit() {
				const app = this
				if (app.disabled) {
					return false
				}
				const {
					form
				} = this
				const {
					imageList
				} = this
				app.$refs.uForm.validate(valid => {
					if (valid) {
						app.disabled = true
						ApplyApi.checkShop(form).then(res => {
							// 判断是否需要上传图片
							if (imageList[0].size == 100 || imageList[1].size == 100) {
								app.$toast('请上传图片！')
								app.disabled = false
								return false
							}
							if (imageList.length > 0 && imageList[0].size != 101) {
								app.uploadFile()
									.then(() => app.onSubmit())
									.catch(err => {
										app.disabled = false
										if (err.statusCode !== 0) {
											app.$toast(err.errMsg)
										}
										console.log('err', err)
									})
							} else {
								app.onSubmit()
							}
						}).catch(err => {
							console.log("err: ", err);
							if (err.statusCode == 0) {
								app.disabled = false
								app.$toast(err.errMsg)
								return false
							}
						})

					}
				})
			},

			// 上传图片
			uploadFile() {
				const app = this
				const {
					imageList,
					form
				} = app
				// 批量上传
				return new Promise((resolve, reject) => {
					if (imageList.length > 0) {
						UploadApi.image(imageList)
							.then(fileIds => {
								form.images = fileIds
								resolve(fileIds)
							})
							.catch(reject)
					} else {
						resolve()
					}
				})
			},

			// 提交到后端
			onSubmit() {
				const app = this
				const {
					form
				} = this
				let req;
				if (form.apply_status == 30) {
					req = ApplyApi.edit(form.apply_id, form)
				} else {
					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;
	}

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