<template>
	<view>
		<u-toast ref="uToast" />
		<view class="top">
			<swiper class="screen-swiper" :indicator-dots="true" :circular="true" :autoplay="true" interval="5000"
				duration="1500">
				<swiper-item v-for="(item,index) in swiperList" :key="index">
					<image style="object-fit: contain; width:100%;height:100%" :src="item.url" mode="aspectFill">
					</image>
				</swiper-item>
			</swiper>
		</view>
		<view class="content">
			<u-form :model="form" ref="uForm">
				<u-form-item label="身份证" prop="identityCard" label-position='top' :required="true">
					<u-input v-model="form.identityCard" maxlength="18" @input='getGenderFromIdCard'/>
				</u-form-item>
				<u-form-item label="姓名" prop="staffName" label-position='top' :required="true">
					<u-input v-model="form.staffName" />
				</u-form-item>
				<u-form-item label="性别" label-position="top" prop="sex" :required="true">
					<u-radio-group v-model="form.sex" :disabled="true">
						<u-radio v-for="(item, index) in sexList" :key="index" :name="item.name">
							{{item.label}}
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="手机号" prop="mobilePhone" label-position='top' :required="true">
					<u-input v-model="form.mobilePhone" type="number" maxlength="11" />
				</u-form-item>
				<u-form-item label="紧急联系人" label-position='top' prop="urgentName" :required="true">
					<u-input v-model="form.urgentName" />
				</u-form-item>
				<u-form-item label="紧急联系人电话" label-position='top' prop="urgentPhone" :required="true">
					<u-input v-model="form.urgentPhone" type="number" maxlength="11" />
				</u-form-item>
				<u-form-item label="紧急联系人关系" label-position='top' prop="urgentRelationship" :required="true">
					<u-radio-group v-model="form.urgentRelationship">
						<u-radio v-for="(item, index) in relList" :key="index" :name="item.name">
							{{item.label}}
						</u-radio>
					</u-radio-group>
					<view class="prompt">优先选择配偶，父母，子女，兄弟姐妹</view>
				</u-form-item>
				<u-form-item label="入场时间" prop="email" label-position='top'>
					<picker mode="date" :start="currentDate" :value="date" @change="handleDate">
						<view class="uni-input">{{date}}</view>
					</picker>
				</u-form-item>
				<!--<u-form-item label="入职时间" prop="email" label-position='top'>
					<picker mode="time" :value="time" @change="handleTime">
						<view class="uni-input">{{time}}</view>
					</picker>
				</u-form-item> -->
				<u-form-item label="外包服务商" label-position='top' prop="remark">
					<u-input v-model="form.remark" />
				</u-form-item>
				<u-form-item label="服务类型" prop="job" label-position='top' :required="true">
					<u-radio-group v-model="form.job">
						<u-radio v-for="(item, index) in typeList" :key="index" :name="item.name">
							{{item.label}}
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="照片" prop="cj" label-position='top' :required="true">
					<view class="photo" @click="handlePhoto">
						<text style="font-size: 12px;color: #409eff;" v-if="!photo">点击上传</text>
						<img style="width:100%;height:100%" :src="photo" v-else></img>
					</view>
					<view class="prompt" style="color: red;">用于门禁出入</view>
				</u-form-item>
			</u-form>
		</view>
		<view class="agreement" style="width: 100%;text-align: center;margin: 22px 0;">
			<u-checkbox v-model="check"></u-checkbox>
			点击勾选<text style="color: #409EFF;" @click.stop="agreementshow2">《用户服务协议》 </text>和<text
				style="color: #409EFF;" @click.stop="agreementshow">《隐私政策》</text>
		</view>
		<view class='center'>
			<u-button type="primary" shape="square" :loadingShow='loadingShow' :ripple="true" @click="save">提交
			</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentDate: '',
				check: false,
				time: null,
				date: null,
				option: [],
				quName: "",
				loadingShow: false,
				show: false,
				relList: [{
						name: "配偶",
						label: "配偶"
					},
					{
						name: "父母",
						label: "父母"
					},
					{
						name: "子女",
						label: "子女"
					},
					{
						name: "兄弟姐妹",
						label: "兄弟姐妹"
					},
				],
				typeList: [{
						name: '0',
						label: '日结'
					},
					{
						name: '1',
						label: '月结'
					}

				],
				sexList: [{
						name: '0',
						label: '男'
					},
					{
						name: '1',
						label: '女'
					},
				],
				selectedValue: "",
				fontList: ['请正确填写个人信息,一人只能填写一次,请勿重复提交'],
				swiperList: [{
					url: '/static/image/member_card.jpg',
				}],
				form: {},
				photo: "",
				rules: {
					urgentName: [{
						required: true,
						message: '请输入紧急联系人',
						trigger: ['change', 'blur'],
					}],
					urgentRelationship: [{
						required: true,
						message: '请输入紧急联系人关系',
						trigger: ['change', 'blur'],
					}],
					staffName: [{
						required: true,
						message: '请输入姓名',
						trigger: ['change', 'blur'],
					}],
					sex: [{
						required: true,
						message: '请选择性别',
						trigger: ['change'],
					}],
					identityCard: [{
						required: true,
						message: '请输入身份证号',
						trigger: ['change', 'blur'],
					}, {
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							const regex = /^[1-9]\d{5}(19|20)\d{2}(0\d|1[012])([012]\d|3[01])\d{3}([0-9]|X)$/;
							return regex.test(value);
						},
						message: '身份证号码不正确',
						trigger: ['change', 'blur'],
					}],
					mobilePhone: [{
						required: true,
						message: '请输入手机号',
						trigger: ['change', 'blur'],
					}, {
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							const regex = /^1[0-9]{10}$/;
							return regex.test(value);
						},
						message: '手机号码不正确',
						trigger: ['change', 'blur'],
					}],
					job: [{
						required: true,
						message: '请输入结算方式',
						trigger: ['change', 'blur'],
					}],
					urgentPhone: [{
						required: true,
						message: '请输入紧急联系人手机号',
						trigger: ['change', 'blur'],
					}, {
						validator: (rule, value, callback) => {
							const regex = /^1[0-9]{10}$/;
							return regex.test(value);
						},
						message: '手机号码不正确',
						trigger: ['change', 'blur'],
					}],
				}
			}
		},
		mounted() {
			this.getCurrentDate();
		},
		methods: {
			getGenderFromIdCard(idCard) {
				if (idCard.length == 18) {
					const genderDigit = parseInt(idCard.charAt(idCard.length - 2)) % 2;
					if (genderDigit === 0) {
						this.form.sex = '1'
					} else {
						this.form.sex = '0'
					}
				}else{
					this.form.sex = ''
				}
			},
			getCurrentDate() {
				var today = new Date();
				var year = today.getFullYear();
				var month = (today.getMonth() + 1 < 10 ? '0' : '') + (today.getMonth() + 1);
				var day = (today.getDate() < 10 ? '0' : '') + today.getDate();
				this.currentDate = year + '-' + month + '-' + day;
			},
			agreementshow() {
				uni.navigateTo({
					url: '/pages/login/agreement/agreement'
				})
			},
			agreementshow2() {
				uni.navigateTo({
					url: '/pages/login/agreement/newAgreement'
				})
			},
			handleTime(time) {
				this.time = time.detail.value
			},
			handleDate(date) {
				this.date = date.detail.value
			},
			getDate() {
				const date = new Date(); // 创建一个Date对象
				const year = date.getFullYear(); // 获取当前年份(4位数字)
				const month = date.getMonth() + 1; // 获取当前月份(0-11)，需要加1才是真正的月份
				const day = date.getDate(); // 获取当前日期(1-31)
				// 将月份和日期转换为2位数的字符串形式
				const monthStr = month < 10 ? `0${month}` : `${month}`;
				const dayStr = day < 10 ? `0${day}` : `${day}`;
				const dateString = `${year}-${monthStr}-${dayStr}`;
				this.date = dateString
			},
			getTime() {
				const date = new Date(); // 创建一个Date对象
				const hours = date.getHours(); // 获取当前小时数(0-23)
				const minutes = date.getMinutes(); // 获取当前分钟数(0-59)
				// 将小时和分钟转换为2位数的字符串形式
				const hoursStr = hours < 10 ? `0${hours}` : `${hours}`;
				const minutesStr = minutes < 10 ? `0${minutes}` : `${minutes}`;
				const timeString = `${hoursStr}:${minutesStr}`;
				this.time = timeString
			},
			handlePhoto() {
				let _this = this
				uni.showModal({
					title: '要求',
					content: '人像居中、五官清晰、露出双耳，眼睛正视镜头，头发不得遮挡面部。',
					showCancel: false,
					success: function(res) {
						uni.chooseImage({
							count: 1, //默认9
							sizeType: ['original', 'compressed'],
							sourceType: ['camera'],
							success: function(res) {
								_this.photo = res.tempFilePaths[0]
								uni.getFileSystemManager().readFile({
									filePath: res.tempFilePaths[0],
									encoding: 'base64',
									success: res => {
										let base64 = 'data:image/jpeg;base64,' + res
											.data
										_this.form.facesInformation = base64
									},
									fail: (e) => {}
								})

							}
						});
					}
				})
				// });
			},
			confirm(val) {
				this.quName = val[0].label
				this.form.regionId = val[0].value
			},
			getQy(storeId) {
				let params = {
					pageNum: 1,
					pageSize: 99,
					storeId
				}
				this.$api.getStore(params).then(res => {
					if (res.code == '000000') {
						this.option = this.treeToList(this.replaceRegionListToChildren(res.data)) /*树转数组*/
					} else {
						uni.showToast({
							title: res.message,
							icon: 'error',
							duration: 2000
						});
					}
				})
			},
			treeToList(list) {
				let res = []
				for (const item of list) {
					const {
						children,
						...i
					} = item
					if (children && children.length) {
						res = res.concat(this.treeToList(children))
					}
					res.push(i)
				}
				return res
			},
			replaceRegionListToChildren(treeArray) {
				if (!Array.isArray(treeArray)) {
					return treeArray;
				}
				return treeArray.map((node) => {
					const newNode = {
						...node,
						label: node.regionName,
						value: node.id
					};
					if (Array.isArray(newNode.regionListVoList) && newNode.regionListVoList.length) {
						newNode.children = this.replaceRegionListToChildren(newNode.regionListVoList);
						delete newNode.regionListVoList;
					}

					return newNode;
				});
			},
			save() {
				if (!this.check) {
					return uni.showModal({
						title: '提示',
						content: '请同意勾选协议',
						showCancel: false,
						success: function(res) {}
					})
				}
				if (!this.photo) {
					return this.$refs.uToast.show({
						title: '请上传人像照片',
						type: 'error',
					})
				}
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.loadingShow = true
						let params = {
							...this.form,
							ruzhiTime: this.date + ' 09:00:00'
						}
						this.$api.staffAddByWeChat(params).then(res => {
							this.loadingShow = false
							if (res.code == '000000') {
								uni.setStorageSync('userInfo', res.data)
								this.$api.getById({
									id: res.data.id
								}).then(res => {
									if (res.code == '000000') {
										uni.setStorageSync('isUpdate', res.data.isUpdate)
										if(res.data.isOne){
											this.$refs.uToast.show({
												title: '登录完成',
												url: '/pages/tabBar/mySet/common/message/message'
											})
										}else{
											this.$refs.uToast.show({
												title: '注册已完成',
											})
										}
										
									}
								})
							} else {
								this.$refs.uToast.show({
									title: res.message,
									url: '/pages/login/login'
								})
							}
						})
					}
				});
			},
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			this.getDate()
			this.getTime()
		},
		onLoad(option) {
			// let storeId = decodeURIComponent(option.q) + ''
			// storeId = storeId.split('https://tt.tianyd.com?id=').join('')
			this.form.storeId = '369234373443874816'
			// this.getQy(storeId)
		}
	}
</script>

<style scoped>
	.prompt {
		color: #e6a23c;
		font-size: 12px;
	}

	.photo {
		width: 200upx;
		height: 200upx;
		border: 1px dotted #ccc;
		text-align: center;
		line-height: 200upx;
	}

	.btnLogin {
		opacity: 0;
	}

	/deep/.u-form-item {
		padding: 7upx 0px !important;
	}

	.content {
		padding-left: 30upx;
	}

	.center {
		width: 100%;
		padding: 0 100upx;
		margin-top: 50upx;
	}
</style>
