<template>
	<view class="container">
		<uni-section title="基础信息" type="line">
			<uni-forms ref="infoForm" :rules="rules" :modelValue="formData" :label-width="90">
				<uni-forms-item required label="姓名" name="name">
					<uni-easyinput type="text" v-model="formData.name" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item required label="性别" name="sex">
					<uni-data-checkbox v-model="formData.sex" :localdata="sexs" />
				</uni-forms-item>
				<uni-forms-item required label="手机号" name="phone">
					<view class="phoneBox">
						<uni-easyinput disabled type="text" v-model="formData.phone" placeholder="手机号" />
						<button type="primary" :plain="true" style="border: none;"  size="mini" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">获取手机号</button>
					</view>
				</uni-forms-item>
				<uni-forms-item name="birthday" label="出生日期">
					<uni-datetime-picker type="date" v-model="formData.birthday" />
				</uni-forms-item>
			</uni-forms>
		</uni-section>
		<uni-data-checkbox class="isShowAddr" v-model="isShowAddr" multiple :localdata="isShowArr" />
		<uni-section title="地址信息" type="line" v-if="isShowAddr.length > 0">
			<uni-forms ref="addrForm" :modelValue="formData" :label-width="90">
				<uni-forms-item label="小区选择">
					<uni-data-picker v-model="formData.estateId" :map="pickerMap" :localdata="items" placeholder="请选择地址" popup-title="请选择地址" @change="onchange"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="楼栋选择" v-if="house.range && house.range.length > 0">
					<uni-data-picker v-model="formData.buildingId" :localdata="house.range" placeholder="请选择楼栋" popup-title="请选择楼栋" @change="selectChange"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="单元选择" v-if="house.unit && house.unit.length > 0">
					<uni-data-picker v-model="formData.unit" :localdata="house.unit" placeholder="请选择单元" popup-title="请选择单元" @change="unitChange"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="楼层选择" v-if="house.floor && house.unit.length > 0">
					<uni-data-picker v-model="formData.floor" :localdata="house.floor" placeholder="请选择楼层" popup-title="请选择楼层" @change="floorChange"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="门牌选择" v-if="house.number && house.number.length > 0">
					<uni-data-picker v-model="formData.houseId" :localdata="house.number" placeholder="请选择门牌" popup-title="请选择门牌" @change="houseChange"></uni-data-picker>
				</uni-forms-item>
			</uni-forms>
		</uni-section>
		<button class="btn" type="primary" @click="submit('infoForm')">提交</button>
	</view>
</template>

<script>
	import request from '../../api/user.js';
	import requestLogin from '../../api/login.js';
	const appid = uni.getAccountInfoSync().miniProgram.appId;
	export default {
		data() {
			return {
				role: '',
				path: null,
				formData: {},
				sexs: [
					{ text: '男', value: 1 },
					{ text: '女', value: 0 },
				],
				items: [],
				pickerMap: {
					text: 'label',
					value: 'interId'
				},
				// range: [],
				house: {},
				building: [],
				unit: '',
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					sex: {
						rules: [{
							required: true,
							errorMessage: '性别不能为空'
						}]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '电话不能为空'
						}]
					},
				},
				// 勾选成为居民
				isShowAddr: 0,
				isShowArr: [{ text: '我是富裕街道居民', value: 1 }],
			}
		},
		async mounted() {
			const res = await request.addrTreeSelect();
			this.items = res.data;
			this.role = uni.getStorageSync('role');
			if (this.role !== 'guest') this.queryInfo();
		},
		methods: {
			async queryInfo() {
				// const userinfo = await request.getUser();
				const userinfo = uni.getStorageSync('userinfo');
				this.formData = userinfo;
				this.setAddr(userinfo);
				this.isShowAddr = [1];
			},
			// 设置地址
			async setAddr(data) {
				// 小区存在
				if (data.estateId && data.estateId !== null) {
					await this.onchange({ detail: { value: [{ value: data.estateId }] }, isUpdate: true });
				}
				// 楼栋存在
				if(data.buildingId && data.buildingId !== null) {
				 	await this.selectChange({ detail: { value: [{ value: data.buildingId }] }, isUpdate: true });
				}
				// 单元存在
				if(data.unit && data.unit !== null) {
					await this.unitChange({ detail: { value: [{ value: data.unit }] }, isUpdate: true });
				}
				// 楼层存在
				if(data.floor && data.floor !== null) {
					await this.floorChange({ detail: { value: [{ value: data.floor }] }, isUpdate: true });
				}
				// 门牌存在
				if(data.houseId && data.houseId !== null) {
					await this.houseChange({ detail: { value: [{ value: data.houseId }] } });
				}
			},
			// 初始化选择器
			initPicker(e) {
				if (e.includes('range')) this.$set(this.house, 'range', []);
				if (e.includes('unit')) this.$set(this.house, 'unit', []);
				if (e.includes('floor')) this.$set(this.house, 'floor', []);
				if (e.includes('number')) this.$set(this.house, 'number', []);
			},
			// 获取手机号
			async decryptPhoneNumber(e) {
				const res = await requestLogin.getPhone({ code: e.detail.code, appid: appid });
				if (!res) {
					uni.showToast({
						title: '获取失败',
						icon: 'error',
						duration: 2000,
					});
					return
				}
				if (res.errcode !== 0) {
					uni.showToast({
						title: res.errMsg,
						icon: 'error',
						duration: 2000,
					});
					return
				}
				this.$set(this.formData, 'phone', res.phone_info.phoneNumber);
			},
			// 小区选择
			async onchange(e) {
				if (!e || e == '' || e.detail.value.length <= 0) {
					this.initPicker(['range', 'unit', 'floor', 'number']);
					return;
				}
				const val = e.detail.value[e.detail.value.length - 1].value;
				const res = await request.buildingList({ estateId: val });
				const range = res.rows.map(e => ({ ...e, text: `${e.number}栋`, value: e.buildingId }));
				this.$set(this.house, 'range', range);
				// 删除选项
				if (e.isUpdate) return;
				delete this.formData.buildingId
				delete this.formData.unit
				delete this.formData.floor
				delete this.formData.houseId
			},
			// 楼栋选择
			async selectChange(e) {
				if (!e || e == '' || e.detail.value.length <= 0) {
					this.initPicker(['unit', 'floor', 'number']);
					return;
				};
				const res = await request.houseList({ buildingId: e.detail.value[0].value });
				this.building = res.rows;
				const list = [];
				const numList = [];
				const unit = res.rows.filter(j => j.unit !== null).map(j => ({ ...j, text: `${j.unit}单元`, value: j.unit }));
				const number = res.rows.filter(j => j.number !== null).map(j => ({ ...j, text: `${j.number}号`, value: j.houseId }));
				unit.forEach(k => {
					const isunit = list.find(j => j.unit == k.unit);
					if (!isunit) list.push(k);
				});
				this.$set(this.house, 'unit', list);
				number.forEach(k => {
					const isunit = numList.find(j => j.number == k.number);
					if (!isunit) numList.push(k);
				});
				this.$set(this.house, 'number', numList);
				// 删除选项
				if (e.isUpdate) return;
				delete this.formData.unit
				delete this.formData.floor
				delete this.formData.houseId
			},
			// 单元选择
			unitChange(e) {
				if (!e || e == '' || e.detail.value.length <= 0) {
					this.initPicker([ 'floor', 'number']);
					return;
				}
				this.unit = e.detail.value[0].value;
				const list = [];
				const floor = this.building.filter(j => j.unit == e.detail.value[0].value).map(j => ({ ...j, text: `${j.floor}层`, value: j.floor }));
				floor.forEach(k => {
					const isunit = list.find(j => j.floor == k.floor);
					if (!isunit) list.push(k);
				});
				this.$set(this.house, 'floor', list);
				// 删除选项
				if (e.isUpdate) return;
				// delete this.formData.unit
				delete this.formData.floor
				delete this.formData.houseId
			},
			// 楼层选择
			floorChange(e) {
				if (!e || e == '' || e.detail.value.length <= 0) return;
				const list = [];
				const number = this.building.filter(j => j.floor == e.detail.value[0].value && j.unit == this.unit).map(j => ({ ...j, text: `${j.number}号`, value: j.houseId }));
				number.forEach(k => {
					const isunit = list.find(j => j.number == k.number);
					if (!isunit) list.push(k);
				});
				this.$set(this.house, 'number', list);
				// 删除选项
				if (e.isUpdate) return;
				// delete this.formData.unit
				// delete this.formData.floor
				delete this.formData.houseId
			},
			// 门牌选择
			houseChange(e) {
				if (!e || e == '' || e.detail.value.length <= 0) return;
				const dept = this.house.number.find(j => j.houseId == e.detail.value[0].value);
				this.formData.deptId = dept.deptId;
			},
			// 提交
			async submit(ref) {
				this.$refs[ref].validate(async (err, formdata) => {
					if (!err) {
						// 判断勾选后是否添加地址
						if (this.isShowAddr.length > 0) {
							if (!this.formData.estateId || !this.formData.buildingId || !this.formData.houseId == null) {
								uni.showToast({
									title: '请填写完整地址信息',
									icon: 'error',
									duration: 2000,
								});
								return;
							}
						}
						if (this.role == 'guest') {
							// 添加用户
							const res = await request.addUser(this.formData);
							uni.setStorageSync('token', res.data.token);
							uni.setStorageSync('userinfo', res.data.user);
							uni.setStorageSync('role', res.data.role);
							uni.showToast({
								title: '添加成功',
								duration: 2000
							});
						} else {
							// 修改用户
							const res = await request.updateUser(this.formData);
							uni.showToast({
								title: '修改成功',
								duration: 2000
							});
						}
						setTimeout(() => {
							uni.navigateBack();
						}, 1000)
					}
				})
			},
		},
		onLoad(option) {
			this.path == option.path;
		}
	}
</script>

<style>
	.uni-section {
		padding-bottom: 10px;
		margin-bottom: 10px;
	}
	.uni-select__selector {
		z-index: 999 !important;
	}
	.uni-forms, .btn {
		width: 90%;
		margin: 10px auto;
	}
	.phoneBox {
		display: flex;
	}
	.isShowAddr {
		width: 90%;
		margin: 0 auto;
		display: block;
	}
</style>
