<template>

	<view class="page">
		<!-- #ifdef APP-PLUS -->
		<!-- 状态栏占位 -->
		<view class="status_bar"></view>
		<view class="" style="margin-top: var(--status-bar-height);">
			<uni-nav-bar title="" left-icon="left" backgroundColor="#F35546" color="#fff" @clickLeft="back"></uni-nav-bar>
		</view>
		<view class="content-box">
			<u-form :model="formData" ref="uForm" label-align="right" label-width="50">
				<u-form-item label="ID号"><u-input v-model="formData.deviceCode" /></u-form-item>
			</u-form>
			
			<view class="form-box">
				<u-form :model="formData" ref="uForm" label-align="right" label-width="50">
					<u-form-item label="照片">
						<view class="pictrue" @click.stop='uploadpic'>
							<image :src='newAvatar ? newAvatar : formData.avatar'></image>
							<image src='../../static/images/alter.png' class="alter"></image>
						</view>
					</u-form-item>
					<u-form-item label="姓名"><u-input v-model="formData.nickName" placeholder="请输入姓名"/></u-form-item>
					<u-form-item label="证件号"><u-input v-model="formData.cardNumber" placeholder="请输入证件号" @blur="cardNumberBlur"/></u-form-item>
					<u-form-item label="性别" right-icon="arrow-right"><u-input v-model="formData.sexValue" placeholder="请选择性别" disabled/></u-form-item>
					<u-form-item label="生日" right-icon="arrow-right"><u-input v-model="formData.birthday" placeholder="请选择生日" disabled/></u-form-item>
					<u-form-item label="手机号"><u-input v-model="formData.tel" @blur="telBlur" placeholder="请输入手机号"/></u-form-item>
				</u-form>
			</view>
			<view class="form-box">
				<u-form :model="formData" ref="uForm" label-align="right" label-width="50">
					<!-- 问题：u-input在disabled得情况下点击事件失效 -->
					<u-form-item label="关系" right-icon="arrow-right" @click.native="goChooseRelation">
							<u-input disabled  v-model="formData.relationValue"  placeholder="请选择关系" input-align="right" />
					</u-form-item>
				</u-form>
			</view>

		</view>
		<!-- #endif -->

		<!-- #ifdef MP -->
		<view class="content_box">
			<van-field v-model="formData.deviceCode" readonly name="ID号" label="ID号" placeholder="ID号" />
			<view class="content">
				<van-form @submit="bindEqu" ref="formData" :model="formData" label-width="48" :colon="true">
					<van-field class="btn" v-model="formData.photo" name="照片" label="照片" placeholder="照片" readonly
						@click.native.stop.prevent="uploadpic" input-align="right">
						<template #button>
							<image src="/static/img/arrow.png" mode=""></image>
						</template>
					</van-field>
					<van-field v-model="formData.nickName" name="姓名" label="姓名" placeholder="请输入姓名"
						:rules="[{ required: true, message: '请填写姓名' }]" @change="formData.nickName = $event.detail" />

					<van-field v-model="formData.cardNumber" name="证件号" label="证件号" placeholder="请输入证件号"
						:rules="[{ required: true, message: '请填写证件号' }]" @blur="cardNumberBlur"
						@change="formData.cardNumber = $event.detail" />
					<van-field class="btn" readonly clickable name="picker" :value="formData.sexValue" label="性别"
						placeholder="请选择性别">
						<template #button>
							<image src="/static/img/arrow.png" mode=""></image>
						</template>
					</van-field>
					<van-field class="btn" readonly clickable name="calendar" :value="formData.birthday" label="生日"
						placeholder="年/月/日" @click.native.stop.prevent="showCalendarFn">
						<template #button>
							<image src="/static/image/calendar.png" mode=""></image>
						</template>
					</van-field>
					<van-field v-model="formData.tel" name="手机号" label="手机号" placeholder="请输入手机号"
						:rules="[{ required: true, message: '请填写手机号' }]" @blur="telBlur"
						@change="formData.tel = $event.detail" />

				</van-form>

				<van-popup :show="showPicker" position="bottom">
					<van-picker show-toolbar :columns="columns" @confirm="pickerConfirm" @cancel="showPicker = false" />
				</van-popup>
				<van-popup :show="showCalendar" position="bottom">
					<van-datetime-picker @cancel="showCalendar=false" @confirm="calendarConfirm" :value="currentDay"
						type="date" :min-date="minDate" />
				</van-popup>
			</view>
			<van-field readonly class="btn" v-model="formData.relationValue" label="关系" clearable
				placeholder="请选择与设备使用者关系" @click.native.stop.prevent="goChooseRelation">
				<template #button>
					<image src="/static/img/arrow.png" mode=""></image>
				</template>
			</van-field>

		</view>
		<!-- #endif -->
		<view class="footer_btn">
			<view class="footer" @click="bindEqu('formData')">
				绑定
			</view>
		</view>
	</view>
</template>

<script>
	import dayjs from "@/plugin/dayjs/dayjs.min.js";
	import * as infoApi from '@/api/sleep/equ.js';
	import {
		mapGetters
	} from "vuex";
	export default {
		data() {
			return {
				form: {
					name: '',
					intro: '',
					sex: ''
				},
				checkboxList: [{
						name: '苹果',
						checked: false,
						disabled: false
					},
					{
						name: '雪梨',
						checked: false,
						disabled: false
					},
					{
						name: '柠檬',
						checked: false,
						disabled: false
					}
				],
				radioList: [{
						name: '鲜甜',
						disabled: false
					},
					{
						name: '麻辣',
						disabled: false
					}
				],
				radio: '',
				switchVal: false,





				formData: {
					photo: '',
					deviceCode: '',
					nickName: '',
					relationId: null,
					relationValue: '',
					passWord: '',
					sex: null, //1 男 2女
					sexValue: '',
					birthday: '',
					cardNumber: '',
					tel: ''
				},

				username: '',
				password: '',
				showCalendar: false,
				showPicker: false,
				columns: ['男', '女'],
				currentDay: new Date().getTime(),
				minDate: new Date(1900, 0, 1).getTime(),
				id: '',
				list: [],
				newAvatar: '',
			}
		},
		computed: mapGetters(['uid', 'deviceId']),
		async onLoad(options) {
			console.log(options, 88888);
			this.formData.deviceCode = options.deviceCode ? options.deviceCode : ''
			if (options.id) {
				this.id = options.id
				await this.getList()
				this.getBindDetailInfo()
			}
		},
		methods: {
			back() {
				uni.navigateBack()
			},
			getList() {
				infoApi.getDetailList().then(res => {
					let obj = {
						name: '自定义',
						avatar: 'https://employmenter.oss-cn-beijing.aliyuncs.com/%E9%80%89%E6%8B%A9%E5%85%B3%E7%B3%BB_slices/%E7%BC%96%E7%BB%84%2013%402x.png',
						id: 99
					}
					this.list = [...res.data, obj]
				})
			},
			getBindDetailInfo() {
				infoApi.getBindDetailInfo({
					id: this.id
				}).then(res => {
					if (res.code === 0) {
						this.formData = res.data
						this.formData.sexValue = res.data.sex === 1 ? '男' : '女'
						this.formData.relationValue = this.list.find(item => item.id === res.data.relationId).name
					}
				})
			},
			bindEqu() {
				console.log(this.$refs.formData, 555);
				// this.$refs.formData.validate().then(() => {
				// 	this.$toast.success('提交成功')
				// }).catch(() => {
				// 	this.$toast.fail('提交失败')
				// })
				const {
					photo,
					nickName,
					cardNumber,
					relationId,
					passWord,
					sex,
					birthday,
					tel
				} = this.formData
				// if(photo == '') {
				// 	this.$util.Tips({
				// 		title: '请上传图片',
				// 		icon: 'none'
				// 	})
				// }else 
				if (nickName == '') {
					this.$util.Tips({
						title: '请填写姓名',
						icon: 'none'
					})
				} else if (cardNumber == '') {
					this.$util.Tips({
						title: '请填写证件号',
						icon: 'none'
					})
				} else if (tel == '') {
					this.$util.Tips({
						title: '请填写手机号',
						icon: 'none'
					})
				} else if (relationId == null) {
					this.$util.Tips({
						title: '请选择与设备使用者关系',
						icon: 'none'
					})
				} else {
					let params = {
						deviceId: this.deviceId,
						...this.formData,
						birthday: this.formData.birthday + ' ' + '00:00:00',
						memberId: this.uid
					}
					console.log(params, 7778);
					infoApi.bindEqu(params).then(res => {
							this.$util.Tips({
								title: '绑定成功',
								icon: 'success'
							}, () => {
								uni.navigateBack({
									delta: 2
								})
							})

						})
						.catch(err => {
							console.log(err);
							return this.$util.Tips({
								title: err,
								// icon: 'error'
							});
						});

				}

			},
			idCardValidator(rule, value, callback) {
				const regex =
					/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
				if (!value || value === '' || value === undefined) {
					callback(new Error('请输入证件号码'));
				} else if ((value.length === 15 || value.length === 18) && regex.test(value)) {
					callback();
				} else {
					callback(new Error('请输入正确的证件号码'));
				}
			},
			cardNumberBlur(e) {
				let value=''
				// #ifdef APP-PLUS 
					value = e
				// #endif 
				// #ifdef MP 
					value = e.detail.value
				// #endif 
				console.log(value, 2222)
				// 调用身份证号验证方法
				this.idCardValidator({}, value, (error) => {
					if (error) {
						// 这里可以根据验证结果处理逻辑
						this.$util.Tips({
							title: error.message,
							icon: 'none'
						})
					} else {
						console.log('身份证号格式正确');
						// 这里可以根据验证结果处理逻辑
						const {
							sex,
							sexValue,
							birthday
						} = this.parseIDCard(value);
						console.log('性别：', sexValue);
						console.log('出生年月日：', birthday);
						this.$set(this.formData, 'sex', sex)
						this.$set(this.formData, 'sexValue', sexValue)
						this.$set(this.formData, 'birthday', birthday)
					}
				});
			},
			telBlur(e) {
				let val=''
				// #ifdef APP-PLUS 
					val = e
				// #endif 
				// #ifdef MP 
					val = e.detail.value
				// #endif 
				console.log(val, 2222)
				if (!(/^1(3|4|5|7|8|9|6)\d{9}$/i.test(val))) {
					return this.$util.Tips({
						title: '请输入正确的手机号码！'
					});
				}
			},
			parseIDCard(idCard) {
				let birthday = '';
				let sex = '';
				let sexValue = '';

				if (idCard.length === 15) {
					birthday = '19' + idCard.substring(6, 12);
					sexValue = parseInt(idCard.substr(14, 1)) % 2 === 0 ? '女' : '男';
				} else if (idCard.length === 18) {
					birthday = idCard.substring(6, 14);
					sexValue = parseInt(idCard.substr(16, 1)) % 2 === 0 ? '女' : '男';
					sex = parseInt(idCard.substr(16, 1)) % 2 === 0 ? '2' : '1';
				}

				// 将出生年月日格式化为年-月-日
				const year = birthday.substring(0, 4);
				const month = birthday.substring(4, 6);
				const day = birthday.substring(6, 8);
				const formattedBirthday = year + '-' + month + '-' + day;

				console.log('性别：', sexValue);
				console.log('出生年月日：', formattedBirthday);

				return {
					sex: sex,
					sexValue: sexValue,
					birthday: formattedBirthday
				};
			},
			/**
			 * 上传文件
			 */
			uploadpic: function() {
				this.$util.uploadImageOne({}, res => {
					this.newAvatar = res.data;
				});
			},
			getValue(item) {
				console.log(item, 112233);
				this.formData.relationId = item.id
				this.formData.relationValue = item.name
			},
			goChooseRelation() {
				console.log('点击了跳转',666)
				uni.navigateTo({
					url: '/pages/equ_list/choose'
				})
			},
			showCalendarFn() {
				this.showCalendar = true
			},
			showPickerFn() {
				this.showPicker = true
			},
			pickerConfirm(value) {
				console.log(value, 66666);
				this.formData.sex = value.detail.index + 1;
				this.formData.sexValue = value.detail.value;
				this.showPicker = false;
			},
			calendarConfirm(date) {
				this.formData.birthday = this.formatDate(date.detail)
				this.showCalendar = false;
			},
			formatDate: function(date) {
				return dayjs(date).format("YYYY-MM-DD");
			},
		},
	}
</script>

<style lang="scss">
	::v-deep .u-form-item {
		background-color: #fff;
		padding:0 20rpx !important;
		border-bottom: 2rpx solid #F5F5F5;
	}
	::v-deep .u-form-item__body__right__content__slot{
		align-content: flex-end;
	}
	::v-deep .u-input{
		background-color: #fff !important;
	}

	.avatar_box {
		height: 342rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #F35546;

		image {
			width: 210rpx;
			height: 210rpx;
		}

	}

	.page {
		// padding: 60rpx 30rpx;
	}

	.content-box {
		padding: 60rpx 30rpx;

		.form-box {
			margin-top: 30rpx;
			.pictrue {
				width: 96rpx;
				height: 96rpx;
				position: relative;
				image {
					width: 100%;
					height: 100%;
					border-radius: 50%;
				}
				.alter {
					width: 30rpx;
					height: 30rpx;
					border-radius: 50%;
					position: absolute;
					bottom: 0;
					right: 0;
				}
			}
			// .pictrue image {
			// 	width: 100%;
			// 	height: 100%;
			// 	border-radius: 50%;
			// }
		}
	}

	.content_box {
		background-color: #F7F7F7;
		padding: 60rpx 30rpx;

		.btn {
			image {
				width: 32rpx;
				height: 32rpx;
			}
		}

		.content {
			/* height: 588rpx; */
			background-color: #fff;
			margin-top: 32rpx;
			// padding: 0 32rpx;
			// height: calc(100vh - 342rpx);
			margin-bottom: 30rpx;
			border-radius: 10rpx;
			overflow: hidden;

			.btn {
				image {
					width: 32rpx;
					height: 32rpx;
				}
			}
		}
	}

	.footer_btn {
		width: 100%;
		height: 98rpx;
		line-height: 98rpx;
		position: fixed;
		bottom: 68rpx;
		color: #fff;
		font-size: 32rpx;
		padding: 32rpx;
		box-sizing: border-box;

		.footer {
			background: #F35546;
			border-radius: 9rpx;
			text-align: center;
		}

	}

	::v-deep uni-image {
		width: 210rpx;
		height: 210rpx;
	}

	// ::v-deep .van-field__label{
	// 	font-size: 32rpx;
	// 	font-weight: 500;
	// 	color: #000000;
	// }
</style>