<template>
	<view class="page">
		<u-alert-tips
			v-if="vk.pubfn.isNotNull(vk.vuex.get('$user.agentInfo.verify_status'))"
			:type="vk.vuex.get('$user.agentInfo.verify_status') == 0 ? 'warning' : vk.vuex.get('$user.agentInfo.verify_status') == 1 ? 'success' : 'error'"
			title="当前状态:"
			:description="
				vk.vuex.get('$user.agentInfo.verify_status') == 0
					? '当前资料审核中，修改提交后将重新进入审核流程'
					: vk.vuex.get('$user.agentInfo.verify_status') == 1
					? '当前资料已审核通过，修改提交将重新进入审核流程'
					: '申请被拒绝，清理联系客服咨询'
			"
		></u-alert-tips>
		<view class="form">
			<u-form :model="form" ref="uForm">
				<u-form-item label-width="150" label="姓名" prop="relname"><u-input placeholder="请输入您的真实姓名" v-model="form.relname" type="text"></u-input></u-form-item>
				<u-form-item label-width="150" label="性别" prop="gender">
					<u-radio-group v-model="form.gender" active-color="#2979ff">
						<u-radio name="male">男</u-radio>
						<u-radio name="female">女</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label-width="150" label="手机号" prop="mobile"><u-input placeholder="请输入您的手机号" v-model="form.mobile" type="text"></u-input></u-form-item>
				<u-form-item label-width="150" label="身份证号" prop="id_card_no">
					<u-input placeholder="请输入您的身份证号" v-model="form.id_card_no" type="text" @input="inputIdcard()"></u-input>
				</u-form-item>

				<u-form-item label-width="150" label="选择身份" prop="type">
					<u-input type="select" :select-open="agentTypeSelectShow" v-model="form.agent_type_name" placeholder="请选择身份" @click="agentTypeSelectShow = true"></u-input>
				</u-form-item>
				<u-form-item label-width="150" label="选择机构" prop="agency_id" v-if="form.type == 2">
					<u-input
						type="select"
						:select-open="agencySelectShow"
						v-model="form.agency_name"
						placeholder="请选择所属机构"
						@click="agencyList.length > 0 ? (agencySelectShow = true) : vk.toast('暂无可选经纪机构')"
					></u-input>
				</u-form-item>

				<u-form-item label-width="150" label="项目名称" prop="property_name" v-if="form.type == 3">
					<u-input type="text" v-model="form.property_name" placeholder="请输入拥有产权项目名称"></u-input>
				</u-form-item>
				<u-form-item label-width="150" label="项目房号" prop="house_no" v-if="form.type == 3">
					<u-input type="text" v-model="form.house_no" placeholder="请输入拥有产权项目名称"></u-input>
				</u-form-item>

				<u-form-item label-position="top" label-width="150" label="身份证头像页" prop="id_card_front_image">
					<view class="id_card" @click="uploadFrontImage">
						<u-icon v-if="form.id_card_front_image == null" name="plus" size="32" color="#606266"></u-icon>
						<text v-if="form.id_card_front_image == null">{{ idCradFrontImageDisabled ? '请先输入身份证号' : '点击上传图片' }}</text>

						<image v-if="form.id_card_front_image != null" :src="form.id_card_front_image" mode="aspectFill"></image>
					</view>
				</u-form-item>
				<u-form-item label-position="top" label-width="150" label="身份证国徽页" prop="id_card_back_image">
					<view class="id_card" @click="uploadBackImage">
						<u-icon v-if="form.id_card_back_image == null" name="plus" size="32" color="#606266"></u-icon>
						<text v-if="form.id_card_back_image == null">{{ idCradBackImageDisabled ? '请先上传身份证头像页照片' : '点击上传图片' }}</text>

						<image v-if="form.id_card_back_image != null" :src="form.id_card_back_image" mode="aspectFill"></image>
					</view>
				</u-form-item>
			</u-form>
			<u-gap height="60"></u-gap>
			<u-button type="primary" :disabled="submitButtonDisabled" @click="submitModalShow = true">提交</u-button>
			<u-gap></u-gap>
			<view class="footer">
				提交即代表同意
				<text class="agreement" @click="vk.navigateTo('/pages/agreement/agreement?type=user_agreement')">《用户协议》</text>
				、
				<text class="agreement" @click="vk.navigateTo('/pages/agreement/agreement?type=privacy_agreement')">《隐私协议》</text>
			</view>
		</view>
		<!-- 列表选择 -->
		<u-select mode="single-column" :list="agentTypeList" v-model="agentTypeSelectShow" @confirm="agentTypeConfirm"></u-select>
		<u-select mode="single-column" :list="agencyList" v-model="agencySelectShow" @confirm="agencySelectConfirm"></u-select>

		<!-- modal -->
		<u-modal v-model="submitModalShow" content="请务必仔细确认各项信息是否正确" :show-cancel-button="true" @confirm="submit()"></u-modal>
		<u-modal v-model="modalShow" :content="modalContent" :show-cancel-button="true" @cancel="modalCancel()" @confirm="modalConfirm()"></u-modal>
		
		<!-- mask -->
		<u-mask :show="maskShow" @click="maskShow = false">
			<view class="warp">
				<u-image src="https://zdcdn.2bwin.cn/uploads/20220513/90abe6fe85d6c17f6bdc069955fbb878.png" mode="widthFix" width="400rpx" border-radius="20rpx"></u-image>
				<u-gap></u-gap>
				<u-button size="medium" type="primary" @click="maskShow = false">确定</u-button>
			</view>
		</u-mask>
		<!-- utoast -->
		<u-toast ref="uToast" />
	</view>
</template>
<script>
var that;
export default {
	data() {
		return {
			maskShow: true,
			form: {
				relname: null,
				gender: 'male',
				mobile: '',
				id_card_no: '',
				id_card_front_image: null,
				id_card_back_image: null,
				type: '', // 身份
				agent_type_name: '请选择', // 名称
				agency_id: null,
				agency_name: '请选择',
				property_name: null,
				house_no: null
			},
			idCradFrontImageDisabled: true,
			idCradBackImageDisabled: true,
			submitButtonDisabled: true,
			rules: {
				relname: [
					{
						required: true,
						message: '姓名不得为空',
						trigger: ['change', 'blur']
					},
					{
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							return this.$u.test.chinese(value);
						},
						message: '姓名格式不正确',
						trigger: ['change', 'blur']
					}
				],
				mobile: [
					{
						required: true,
						message: '手机号不得为空',
						trigger: ['change', 'blur']
					},
					{
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							return vk.pubfn.test(value,'mobile');
						},
						message: '手机号格式不正确',
						trigger: ['change', 'blur']
					}
				],
				id_card_no: [
					{
						required: true,
						message: '身份证号不得为空',
						trigger: ['change', 'blur']
					},
					{
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							return this.$u.test.idCard(value);
						},
						message: '身份证号格式不正确',
						trigger: ['change', 'blur']
					}
				],
				id_card_back_image: [
					{
						required: true,
						message: '身份证头像页照片不得为空',
						trigger: ['change', 'blur']
					}
				],
				back_image: [
					{
						required: true,
						message: '身份证国徽页照片不得为空',
						trigger: ['change', 'blur']
					}
				],
				agency_id: [
					{
						required: true,
						message: '所属机构不得为空',
						trigger: ['change', 'blur']
					}
				],
				property_name: [
					{
						required: true,
						message: '所属项目不得为空',
						trigger: ['change', 'blur']
					}
				],
				house_no: [
					{
						required: true,
						message: '房号不得为空',
						trigger: ['change', 'blur']
					}
				]
			},
			// 给百度识别用的
			idcard_name: '',
			idcard_code: '',

			// 经纪人身份等
			agentTypeSelectShow: false,
			agentTypeList: [
				{
					label: '自由经纪人',
					value: 1
				},
				{
					label: '渠道经纪人',
					value: 2
				},
				{
					label: '老业主',
					value: 3
				}
			],
			agencySelectShow: false, // 中介机构
			agencyList: [], // 中介机构
			propertyInputShow: false, // 老业主

			disabled: true,
			submitModalShow: false,
			
			modalType: 1,
			modalShow: false,
			modalContent: '',
			guideShow: false,
			updateMethod: 'update'
		};
	},
	onLoad(params) {
		that = this;

		if (!vk.checkToken()) {
			vk.toast('请先登录', 'none', 1500, true, function() {
				vk.navigateToLogin();
			});
		} else {
			vk.callFunction({
				url: 'client/agent/kh/getAgentInfo',
				title: '请求中...',
				needAlert: false
			})
				.then(res => {
					if (vk.pubfn.isNull(res.info)) {
						that.updateMethod = 'create';
						vk.toast('请补全您的资料', 'none');
					} else {
						// 更新审核状态
						vk.vuex.set('$user.agentInfo', res.info);
						console.log(vk.vuex.get('$user.agentInfo'));

						that.form.relname = res.info.relname;
						that.form.mobile = res.info.mobile;
						that.form.id_card_no = res.info.id_card_info.no;

						// 已设置类型
						if (vk.pubfn.isNotNull(res.info.type)) {
							that.form.type = res.info.type;
							let typeItem = vk.pubfn.getListItem(that.agentTypeList, 'value', res.info.type);
							that.form.agent_type_name = typeItem.label;

							if (res.info.type == 2 && vk.pubfn.isNotNull(res.info.agencyInfo)) {
								that.form.agency_id = res.info.agency_id;
								that.form.agency_name = res.info.agencyInfo.name;
							}

							if (res.info.type == 3) {
								that.form.property_name = res.info.property_info.name;
								that.form.house_no = res.info.property_info.house_no;
							}
						}

						that.form.id_card_front_image = res.info.id_card_info.front_image;
						that.form.id_card_back_image = res.info.id_card_info.back_image;

						if (vk.pubfn.isNotNull(res.info.id_card_info.no)) {
							that.idcard_name = res.info.relname;
							that.idcard_code = res.info.id_card_info.no;
							that.idCradFrontImageDisabled = false;
						}
						if (vk.pubfn.isNotNull(res.info.id_card_info.front_image)) {
							that.idCradBackImageDisabled = false;
						}
						if (vk.pubfn.isNotNull(res.info.id_card_info.back_image)) {
							that.submitButtonDisabled = false;
						}
					}
				})
				.catch(res => {
					console.log(res);
				});
		}
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	methods: {
		// 选择所属项目回调
		agentTypeConfirm(e) {
			e.map((val, index) => {
				that.form.type = val.value;
				that.form.agent_type_name = val.label;
				// 如果是渠道经纪人，需要选择渠道公司名称
				if (val.value == 2) {
					vk.callFunction({
						url: 'client/agent/kh/getAgencyList',
						needAlert: false
					}).then(res => {
						if (res.list.length == 0) {
							that.form.agency_name = '可联系客服添加';
							vk.toast('暂无可选经纪机构', 'none');
							return;
						}
						that.agencyList = res.list;
					});
				}
			});
		},
		// 选择经纪机构后回调
		agencySelectConfirm(e) {
			e.map((val, index) => {
				this.form.agency_id = val.value;
				this.form.agency_name = val.label;
			});
		},
		// 选择、验证、上传正面照片
		uploadFrontImage() {
			if (vk.pubfn.isNullOne(that.form.relname, that.form.id_card_no) || !vk.pubfn.test(that.form.relname, 'chinese') || !vk.pubfn.test(that.form.id_card_no, 'card')) {
				vk.toast('请检查姓名、身份证号', 'none');
				return;
			}
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				success: function(res) {
					let file = res.tempFiles[0];
					// 这里需要自己配置百度的secret
					vk.openapi.baidu.open.ocr.idcard({
						title: '识别中...',
						data: {
							file
						},
						success: function(ocrRes) {
							console.log(ocrRes);
							if (that.form.relname !== ocrRes['words_result']['姓名']['words']) {
								vk.toast('身份证姓名不符');
								return;
							}
							if (that.form.id_card_no !== ocrRes['words_result']['公民身份号码']['words']) {
								vk.toast('身份证号不符');
								return;
							}
							vk.toast('身份信息验证通过', 'success');

							that.idcard_code = ocrRes['words_result']['公民身份号码']['words'];
							that.idcard_name = ocrRes['words_result']['姓名']['words'];

							// 上传至 unicloud云储存
							vk.callFunctionUtil.uploadFile({
								title: '上传中...',
								filePath: res.tempFilePaths[0],
								suffix: 'png', // 不传suffix会自动获取，但H5环境下获取不到后缀，但可以通过file.name 获取
								provider: 'unicloud',
								success(uploadRes) {
									console.log(uploadRes);
									// 上传成功
									that.form.id_card_front_image = uploadRes.url;
									that.idCradBackImageDisabled = false;
								}
							});
						},
						fail: err => {
							console.log(err);
						}
					});
				}
			});
		},
		// 选择、上传身份证背面
		uploadBackImage() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				success: function(res) {
					// 上传至 unicloud云储存
					vk.callFunctionUtil.uploadFile({
						title: '上传中...',
						filePath: res.tempFilePaths[0],
						suffix: 'png', // 不传suffix会自动获取，但H5环境下获取不到后缀，但可以通过file.name 获取
						provider: 'unicloud',
						success(res) {
							// 上传成功
							that.form.id_card_back_image = res.url;
						}
					});
				}
			});
		},
		submit() {
			that.$refs.uForm.validate(valid => {
				if (valid) {
					if (that.form.relname !== that.idcard_name) {
						vk.toast('身份证姓名不符');
						console.log(that.idcard_name);
						return;
					}
					if (that.form.id_card_no !== that.idcard_code) {
						vk.toast('身份证号不符');
						console.log(that.idcard_code);
						return;
					}
					let id_card_info = {
						no: that.form.id_card_no,
						front_image: that.form.id_card_front_image,
						back_image: that.form.id_card_back_image
					};
					let property_info = {
						name: that.form.property_name,
						house_no: that.form.house_no
					};
					vk.callFunction({
						url: 'client/agent/kh/updateAgentInfo',
						title: '请求中...',
						needAlert: false,
						data: {
							method: that.updateMethod,
							type: that.form.type,
							relname: that.form.relname,
							gender: that.form.gender,
							mobile: that.form.mobile,
							id_card_info: id_card_info,
							property_info: property_info,
							agency_id: that.form.agency_id
						}
					})
						.then(res => {
							console.log(res);
							vk.vuex.set('$user.agentInfo.relname', that.form.relname);
							vk.vuex.set('$user.userInfo.mobile', that.form.mobile);
							vk.vuex.set('$user.agentInfo.id_card_info', id_card_info);
							vk.vuex.set('$user.agentInfo.verify_status', 0); // 审核中
							vk.toast('更新成功，等待审核', 'none', 1500, true, function() {
								vk.navigateToHome();
							});
						})
						.catch(res => {
							console.log(res);
						});
				} else {
					console.log('验证失败');
				}
			});
		},
		// 监听身份证号
		inputIdcard() {
			that.idCradFrontImageDisabled = true;
			// 判断身份证格式
			if (vk.pubfn.test(that.form.id_card_no, 'card') && vk.pubfn.isNotNull(that.form.relname)) {
				that.idCradFrontImageDisabled = false;
			}
		},

		// 以下是工具函数
		// 格式化日期的月份或天数的显示（小于10，在前面增加0）
		getFormatDate(value) {
			if (value == undefined || value == '') {
				return '';
			}
			var str = value;
			if (parseInt(value) < 10) {
				str = '0' + value;
			}
			return str;
		}
	}
};
</script>
<style lang="scss">
.page {
	background-color: #ffffff;
}

.form {
	border-radius: 10rpx;
	padding: 0 40rpx;
}

.popup-body {
	.tips-title {
		font-size: $u-p;
		margin-bottom: 20rpx;
	}

	.tips-content {
		font-size: $u-p2;
		color: $u-tips-color;
		margin-bottom: 60rpx;
	}
}

.id_card {
	color: #606266;
	width: 100%;
	height: 350rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #f4f5f6;
	font-size: $u-p2;
	border-radius: 10rpx;

	image {
		border-radius: 10rpx;
	}
}

.footer {
	position: relative;
	text-align: center;
	font-size: $u-p2;
	left: 0;
	bottom: 20rpx;
	.agreement {
		color: $u-theme-color;
	}
}

.slot-content {
	font-size: 28rpx;
	color: $u-content-color;
	padding: 20rpx;
}

.warp {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100%;
}

.rect {
	width: 400rpx;
	height: 400rpx;
	background-color: #fff;
}
</style>
