<template>
	<view class="container">
		<u-navbar :title="title" leftIconColor="#333" titleStyle="color:#333" :autoBack="true" placeholder></u-navbar>

		<view class="form-box">
			<u--form labelWidth="140rpx" :model="formData" :rules="rules" ref="uForm">
				<u-form-item label="常驻医院" prop="hospitalName" borderBottom @click="showHospital = true">
					<u-input :border="none" disabled v-model="formData.hospitalName" disabledColor="#ffffff"
						placeholder="请选择医院" inputAlign="right" />
					<u-icon slot="right" name="arrow-right" color="#999999"></u-icon>
				</u-form-item>
				<u-form-item label="护工姓名" prop="name" borderBottom required>
					<u--input v-model="formData.name" border="none" placeholder="请输入" :disabled="type == 'view'"
						maxlength="10" inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item label="形象照片" prop="photographUrl" borderBottom required labelPosition="top">
					<view class="upload-box">
						<u-upload :fileList="formData.photographUrlList" file="image" :multiple="false" :maxCount="1"
							@afterRead="afterRead" @delete="deletePic" name="upload1" width="75" height="75">
						</u-upload>
						<span class="tips">支持png、jpg和gif格式，限制1张</span>
					</view>
				</u-form-item>
				<u-form-item label="性别" prop="genderName" borderBottom @click="showSex = true" required>
					<u-input :border="none" disabled v-model="formData.genderName" disabledColor="#ffffff"
						placeholder="请选择" inputAlign="right" />
					<u-icon slot="right" name="arrow-right" color="#999999"></u-icon>
				</u-form-item>
				<u-form-item label="身份证号" prop="idCard" borderBottom required>
					<u--input v-model="formData.idCard" border="none" placeholder="请输入" :disabled="type == 'view'"
						maxlength="18" inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item label="年龄" prop="age" borderBottom required>
					<u--input type="number" maxlength="3" v-model="formData.age" placeholder-class="input-placeholder"
						border="none" clearable placeholder="请输入" :disabled="type == 'view'"
						inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item label="手机号" prop="phoneNumber" borderBottom required>
					<u--input type="number" v-model="formData.phoneNumber" placeholder-class="input-placeholder"
						border="none" clearable placeholder="必填，请输入手机号码" maxlength="11" :disabled="type == 'view'"
						inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item label="工作年限" prop="workYears" borderBottom required>
					<u--input type="number" maxlength="3" v-model="formData.workYears"
						placeholder-class="input-placeholder" border="none" clearable placeholder="请输入"
						:disabled="type == 'view'" inputAlign="right"></u--input>
				</u-form-item>

				<u-form-item label="从业证书" prop="name" borderBottom required labelPosition="top">
					<view class="upload-box" v-for="item,index in formData.nursingCertificateList" :key="index">
						<view class="name-box">
							<u--input v-model="item.certificateName" placeholder="请输入" maxlength="10"></u--input>
							<span class="btn btn1" @click="addUpload">新增</span>
							<span class="btn btn2" v-if="index > 0" @click="deleteUpload(index)">删除</span>
						</view>
						<u-upload :fileList="item.pictureUrlList" file="image" :multiple="false" :maxCount="1"
							@afterRead="(event) => afterRead2(event, index)"
							@delete="(event) => deletePic2(event, index)" :name="'upload_' + index" width="75"
							height="75">
						</u-upload>
						<span class="tips">支持png、jpg和gif格式，限制1张</span>
					</view>
				</u-form-item>
				<u-form-item label="接单状态" prop="orderReceivingStatus" borderBottom required>
					<view class="switch-box">
						<span class="name">开启或关闭接单</span>
						<u-switch v-model="formData.orderReceivingStatus" activeColor="#4B91D1" inactiveColor="#D8D8D8"
							inactiveValue="0" activeValue="1"></u-switch>
					</view>
				</u-form-item>

				<u-form-item label="排序号" prop="sortOrder" borderBottom required>
					<view class="switch-box">
						<u-number-box v-model="formData.sortOrder" max="999" min="1"></u-number-box>
					</view>
				</u-form-item>



			</u--form>

		</view>
		<!-- 底部按钮 -->
		<view class="footer-box" v-if="type != 'view'">
			<view class="btn-box">
				<view class="submit-btn" @click="submitForm">保存</view>
			</view>
		</view>

		<u-action-sheet :show="showSex" :actions="sexList" title="请选择性别" @close="showSex = false" @select="sexSelect"
			safeAreaInsetBottom>
		</u-action-sheet>

		<u-action-sheet :show="showHospital" :actions="hospitalList" title="请选择性别" @close="showHospital = false"
			@select="hospitalSelect" safeAreaInsetBottom>
		</u-action-sheet>
	</view>
</template>

<script>
	import {
		dictData
	} from "@/api/home.js"
	import {
		storage
	} from "@/utils/tools.js"

	import {
		getNurseDetail,
		getHospitalListByManage,
		updateNurseInfo,
		addNurseInfo
	} from "@/api/hospital.js"

	export default {
		data() {
			return {
				type: 'add',
				title: '新增护工',
				formData: {
					hospitalName: '',
					hospitalId: '',
					genderName: '',
					sex: '',
					name: '',
					age: '',
					photographUrlList: [],
					photographUrl: '',
					idCard: '',
					age: '',
					phoneNumber: '',
					workYears: undefined,
					nursingCertificateList: [{
						certificateName: '',
						pictureUrl: '',
						pictureUrlList: [],
					}],
					orderReceivingStatus: '1',
					sortOrder: 1,
					enableStatus: 0,
				},
				rules: {
					hospitalName: [{
						required: true,
						message: '请选择医院',
						trigger: ['blur', 'change'],
					}],
					name: [{
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change'],
					}],
					photographUrl: [{
						required: true,
						message: '请选择头像',
						trigger: ['blur', 'change'],
					}, {
						validator: (rule, value, callback) => {
							if (value && value.length > 0) {
								callback();
							} else {
								callback(new Error('请上传照片'));
							}
						},
						trigger: 'change'
					}],
					sex: [{
						required: true,
						message: '请选择性别',
						trigger: ['blur', 'change'],
					}],
					idCard: [{
							required: true,
							message: '请填写身份证号',
							trigger: ['blur', 'change'],
						},
						{
							// 自定义验证函数
							validator: (rule, value, callback) => {
								// 返回true表示校验通过，返回false表示不通过
								return this.$u.test.idCard(value)
							},
							message: '身份证不正确',
							// 触发器可以同时用blur和change
							trigger: ['blur', 'change'],
						}
					],
					age: [{
							required: true,
							message: '请填写年龄',
							trigger: ['blur', 'change'],
						},
						{
							pattern: /^[1-9]\d*$/,
							message: '请输入正确的年龄',
							trigger: 'blur',
						}
					],
					phoneNumber: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					workYears: [{
							required: true,
							message: '请填写工作年限',
							trigger: ['blur'],
						},
						{
							pattern: /^[1-9]\d*$/,
							message: '请输入正确的工作年限',
							trigger: 'blur',
						},
					],
					// sortOrder: [{
					// 	required: true,
					// 	message: '请填写排序号',
					// 	trigger: ['blur', 'change'],
					// }]
				},
				showHospital: false,
				hospitalList: [],

				showSex: false,
				sexList: [{
						name: '未知',
						value: 0
					},
					{
						name: '男',
						value: 1
					},
					{
						name: '女',
						value: 2
					},
				],
				certificateList: [{
					certificateName: '',
					pictureUrl: [],
				}],

				infoId: '',
			}
		},
		
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(option) {
			if (option.type) {
				this.type = option.type
				if (this.type == 'add') {
					this.title = '新增护工'
				} else if (this.type == 'edit') {
					this.title = '编辑护工'
				}
			}
			if (option.id) {
				this.infoId = option.id
				this.getNurseDetail(this.infoId);
			} else {
				this.getHospitalList()
				this.getSexList();
			}
		},
		methods: {
			//获取于老师关联的医院
			getHospitalList() {
				let that = this;
				getHospitalListByManage().then(res => {
						if (res.code == 200) {
							let data = res.data;
							that.hospitalList = data;
							if (that.infoId) {
								that.formData.hospitalName = that.hospitalList.find(item => item.id == that
									.formData
									.hospitalId).name
							}
						}

					})
					.catch((err) => {
						console.log(err);
					})
			},


			//获取性别字典
			getSexList() {
				let that = this;
				dictData('sys_user_sex').then(res => {
					let data = res.data;
					data.forEach(item => {
						item.name = item.dictLabel
					})
					that.sexList = data;
					if (that.infoId) {
						that.formData.genderName = that.sexList.find(item => item.dictValue == that
							.formData
							.sex).name
					}
				}, err => {
					console.log(err);
				}).finally(() => {

				});
			},

			getNurseDetail(id) {
				let that = this;
				getNurseDetail(id).then(res => {
						if (res.code == 200) {
							let data = res.data;
							//在hospitalList中查找和formData中hospitalId 一样的值，取值hospitalName
							data.photographUrlList = [{
								url: data.photographUrl,
							}]
							if (data.nursingCertificateList.length == 0) {
								data.nursingCertificateList.push({
									certificateName: '',
									pictureUrl: '',
									pictureUrlList: [],
								})
							} else {
								data.nursingCertificateList.forEach(item => {
									item.pictureUrlList = [{
										url: item.pictureUrl,
									}]

								})
							}
							data.workYears = JSON.stringify(data.workYears)
							that.formData = data;
							that.getSexList();
							that.getHospitalList();
						}

					})
					.catch((err) => {
						console.log(err);
					})

			},

			// valChange(e) {
			// 	console.log('当前值为: ' + e.value)
			// 	this.formData.sortOrder = e.value
			// },
			addUpload() {
				this.formData.nursingCertificateList.push({
					certificateName: '',
					pictureUrl: '',
					pictureUrlList: [],
				})
			},
			deleteUpload(index) {
				this.formData.nursingCertificateList.splice(index, 1)
			},
			hospitalSelect(e) {
				this.formData.hospitalName = e.name;
				this.formData.hospitalId = e.id
			},
			sexSelect(e) {
				this.formData.sex = e.dictValue;
				this.formData.genderName = e.dictLabel
			},

			afterRead(e) {
				console.log(e)
				uni.showLoading({
					title: '上传中',
				});
				uni.uploadFile({
					url: uni.$u.http.config.baseURL + '/common/upload',
					filePath: e.file.url,
					name: 'file',
					header: {
						apiToken: storage.get('apiToken')
					},
					success: (res) => {
						uni.hideLoading();
						let data = JSON.parse(res.data);
						console.log('data', data);
						if (data.code != 200) return
						this.formData.photographUrlList = [{
							url: data.data.url,
						}]
						this.formData.photographUrl = data.data.url;
						console.log('this.formData.photographUrl', this.formData.photographUrl);
						//验证photographUrl
						this.$refs.uForm.validateField('photographUrl');
						uni.showToast({
							title: '上传成功',
							icon: 'success',
							duration: 1000
						})
					},
					fail: (err) => {
						console.log(err);
						uni.hideLoading();
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						});
					}
				});
			},

			deletePic(e) {
				this.formData.photographUrl.splice(e.index, 1);
			},

			afterRead2(event, index) {
				console.log(`第${index}个循环上传组件上传前`, event);
				console.log(event)
				uni.showLoading({
					title: '上传中',
				});
				uni.uploadFile({
					url: uni.$u.http.config.baseURL + '/common/upload',
					filePath: event.file.url,
					name: 'file',
					header: {
						apiToken: storage.get('apiToken')
					},
					success: (res) => {
						uni.hideLoading();
						let data = JSON.parse(res.data);
						if (data.code != 200) return
						this.formData.nursingCertificateList[index].pictureUrl = data.data.url;
						this.formData.nursingCertificateList[index].pictureUrlList.push({
							url: data.data.url,
						})
						console.log('this.formData.nursingCertificateList', this.formData
							.nursingCertificateList);
						uni.showToast({
							title: '上传成功',
							icon: 'success',
							duration: 1000
						})
					},
					fail: (err) => {
						console.log(err);
						uni.hideLoading();
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						});
					}
				});
			},

			deletePic2(e, index) {
				this.formData.nursingCertificateList[index].pictureUrl = [];
			},

			submitForm() {
				console.log("formData", this.formData);
				this.$refs.uForm.validate().then((res) => {
						if (res) {
							if (this.type == 'add') {
								addNurseInfo(this.formData).then(res => {
									uni.$u.toast('新增成功');
									setTimeout(() => {
										uni.navigateBack({
											delta: 1,
										});
									}, 1000)
								}, err => {
									console.log(err);
								}).finally(() => {

								});

							} else {
								updateNurseInfo(this.formData).then(res => {
									uni.$u.toast('修改成功');
									setTimeout(() => {
										// uni.$emit('returnAddress', this.formData);
										uni.navigateBack({
											delta: 1,
										});
									}, 1000)
								}, err => {
									console.log(err);
								}).finally(() => {

								});

							}

						}
					})
					.catch((errors) => {
						console.log(",errors", errors);
						uni.$u.toast('校验失败');
					});
			},
		}
	}
</script>

<style scoped lang="scss">
	.container {
		padding: 20rpx;
		padding-bottom: 200rpx;

		.form-box {
			padding: 20rpx;
			background-color: #fff;

			::v-deep .u-input {
				padding: 15rpx !important;
			}

			::v-deep .u-upload {
				margin-top: 15rpx;
			}

			.upload-box {
				margin-top: 20rpx;

				.name-box {
					display: flex;
					align-items: center;
					margin-top: 20rpx;

					.btn {
						padding: 10rpx 20rpx;
						background-color: #4B91D1;
						color: #fff;
						border-radius: 10rpx;
						margin-left: 20rpx;
						border: 1rpx solid #4B91D1;
					}

					.btn2 {
						background-color: #fff;
						color: #FF0000;
						border: 1rpx solid #FF0000;
					}
				}
			}

			.switch-box {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding: 20rpx 0;

				.name {
					margin-right: 20rpx;
					font-size: 30rpx;
				}
			}
		}

		.footer-box {
			position: fixed;
			bottom: 0;
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 100%;
			padding: 50rpx 30rpx;
			box-sizing: border-box;
			font-size: 28rpx;
			background-color: #fff;
			box-shadow: 0 -2rpx 30rpx #c5c5c53a;

			.btn-box {
				width: 100%;

				.submit-btn {
					display: block;
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					text-align: center;
					color: #fff;
					background-color: #026EB7;
					border-radius: 50rpx;
				}
			}
		}

	}
</style>