<template>
	<a-modal class="patient-form" :width="600" :maskClosable="false" :confirmLoading="confirmLoading" :closable="false"
		:destroyOnClose="true" v-model="createVisible" :title="title" @ok="handleSubmit" :footer="null">
		<a-form-model ref="form" :model="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" labelAlign="left"
			class="create-form" :rules="rules">
			<a-row :gutter="20">
				<a-col :span="12">
					<a-form-model-item label="姓名">
						<a-input v-model="form.name" placeholder="请输入姓名" />
					</a-form-model-item>
				</a-col>
				<a-col :span="12">
					<a-form-model-item label="民族">
						<a-select v-model="form.nation" placeholder="请选择民族">
							<a-select-option v-for="item in nationList" :key="item" :value="item">
								{{ item }}
							</a-select-option>
						</a-select>
					</a-form-model-item>
				</a-col>
				<a-col :span="12">
					<a-form-model-item label="性别">
						<a-select v-model="form.gender" placeholder="请选择性别">
							<a-select-option :value="0">男</a-select-option>
							<a-select-option :value="1">女</a-select-option>
						</a-select>
					</a-form-model-item>
				</a-col>
				<a-col :span="12">
					<a-form-model-item label="身高">
						<a-input v-model="form.height" placeholder="请输入身高 (cm)" />
					</a-form-model-item>
				</a-col>
				<a-col :span="12">
					<a-form-model-item label="体重">
						<a-input v-model="form.weight" placeholder="请输入体重 (kg)" />
					</a-form-model-item>
				</a-col>
				<a-col :span="16">
					<a-form-model-item label="身份证号" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
						placeholder="请输入身份证号">
						<keyboard placeHolder="请输入身份证号" :index-num="indexNum" @keyboard-input="handleKeyBoard"
							:old-value="idcard" />

					</a-form-model-item>
				</a-col>
				<a-col :span="8" style="padding-top: 0.15vw;">
					<a-button type="primary" class="idcard" @click="openCamera">扫描身份证</a-button>
				</a-col>
				<a-col :span="16">
					<a-form-model-item label="联系方式" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
						placeholder="请输入联系方式">
						<a-input v-model="form.contract" placeholder="请输入联系方式" />
					</a-form-model-item>
				</a-col>
				<a-col :span="24">
					<a-divider />
				</a-col>
				<a-col :span="12">
					<a-form-model-item label="急救类型" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
						<a-select v-model="form.type" placeholder="请选择类型">
							<a-select-option :value="0">卒中急救</a-select-option>
							<a-select-option :value="1">胸痛</a-select-option>
							<a-select-option :value="2">创伤</a-select-option>
						</a-select>
					</a-form-model-item>
				</a-col>
				<a-col :span="12">
					<a-form-model-item label="平车">
						<!-- <a-select v-model="form.carNo" placeholder="请选择平车号">
							<a-select-option  :value="0" >否</a-select-option>
							<a-select-option  :value="1" >是</a-select-option>
						</a-select> -->
						<a-select v-model="form.carNo" placeholder="请选择平车号">
							<a-select-option v-for="item in carList" :key="item.id" :value="item.deviceNo">
								{{ item.deviceNo }}
							</a-select-option>
						</a-select>
					</a-form-model-item>
				</a-col>
				<a-col :span="16">
					<a-form-model-item label="绿道状态" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
						<a-switch v-model="form.greenRoadFlag" />
					</a-form-model-item>
				</a-col>
				<a-col :span="24" class="footer-btns">
					<a-button class="footer-btn" type="primary" block @click="handleSubmit">提交</a-button>
				</a-col>
				<a-col :span="24" class="footer-btns">
					<a-button class="footer-btn cencelBtn" block @click="close">取消</a-button>
				</a-col>
			</a-row>
		</a-form-model>
	</a-modal>
</template>
<script>
	import keyboard from '@/components/keyboard.vue';
	import {
		createPatient,
		uploadIdcard,
		idcardInfo,
		idcardInfoBase64,
		queryById,
		eduitPatient
	} from 'api';
	import {
		mapState
	} from 'vuex';
	export default {
		name: 'create',
		components: {
			keyboard,
		},
		props: ['firstAidData', 'carList', 'carNo', 'patientId'],
		data() {
			return {
				title: "新建患者",
				indexNum: 0, //必填字段，为键盘索引，每个键盘必须具有唯一值
				idcard: '',
				keyboard: false,
				createVisible: false,
				inputFile: '',
				file: '',
				form: {},
				rules: {},
				confirmLoading: false,
			};
		},
		computed: {
			...mapState('storm', ['nationList', 'anyringToken']),

		},
		create() {

		},
		methods: {
			handleKeyBoard(value) {
				//value为在输入框里面输入的值
				this.idcard = value;
			},
			open(data) {
				this.createVisible = true;
				this.confirmLoading = false;
				if (data.firstAidId) {
					this.title = "编辑患者";
					queryById({
						firstAidId: data.firstAidId,
					}).then(res => {
						if (res.code === 200) {
							this.form = res.data;
						}
					})


				} else {
					this.idcard = '';
					this.form = data || {}
				}

			},
			close() {
				this.createVisible = false;
				this.confirmLoading = false;
				this.form = {}
				this.idcard = '';
			},
			openCamera() {
				const cmr = plus.camera.getCamera();
				const res = cmr.supportedImageResolutions[0];
				const fmt = cmr.supportedImageFormats[0];
				cmr.captureImage(
					(path) => {
						plus.io.resolveLocalFileSystemURL(
							path,
							(entry) => {
								//压缩图片
								this.compressImage(entry.toLocalURL(), entry.name);
							},
							(e) => {
								plus.nativeUI.toast(
									'读取拍照文件错误：' + e.message
								);
							}
						);
					},
					(error) => {
						// alert("Capture image failed: " + error.message);
					}, {
						resolution: res,
						format: fmt,
						filter: 'image',
					}
				);
			},
			//压缩图片
			compressImage(url, filename) {
				var name = '_doc/upload/' + filename;
				plus.zip.compressImage({
						src: url, //src: (String 类型 )压缩转换原始图片的路径
						dst: name, //压缩转换目标图片的路径
						quality: 90, //quality: (Number 类型 )压缩图片的质量.取值范围为1-100
						overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
						width: '250',
						height: '320',
					},
					(zip) => {
						//页面显示图片
						this.showPics(zip.target, name);
					},
					(error) => {
						plus.nativeUI.toast('压缩图片失败，请稍候再试');
					}
				);
			},
			//显示图片
			showPics(url, name) {
				let _this = this;
				//根据路径读取到文件
				plus.io.resolveLocalFileSystemURL(url, (entry) => {
					entry.file((file) => {
						var fileReader = new plus.io.FileReader();
						fileReader.readAsDataURL(file);
						fileReader.onloadend = (e) => {
							var picUrl = e.target.result.toString();
							this.idcardInfoBase64(picUrl);
						};
					});
				});
			},
			dataURLToFile(dataUrl, fileName) {
				const dataArr = dataUrl.split(',');
				const mime = dataArr[0].match(/:(.*);/)[1];
				const originStr = atob(dataArr[1]);
				return new File([originStr], fileName, {
					type: mime,
				});
			},
			async idcardInfoBase64(url) {
				let res = await idcardInfoBase64(url);
				const {
					data,
					code,
					msg
				} = res;
				if (code === 200) {
					const {
						name,
						sex,
						idCardNo,
						nation
					} = data;
					this.form.name = name
					this.form.gender = sex
					this.form.nation = nation
					this.idcard = idCardNo;
				} else {
					this.$message.error(res.msg);
				}
			},
			// 上传前校检格式和大小
			handleBeforeUpload(file) {
				const isLt10M = file.size / 1024 / 1024 < 10000;
				// 校检文件大小
				if (!isLt10M) {
					this.$message.error('上传头像图片大小不能超过 10MB!');
				}
				this.file = file;
				return isLt10M;
			},
			// 上传成功回
			async handleUploadAdd() {
				if (!this.file) return '您还未选择文件';
				// 使用FormData传参数和文件
				var form = new FormData();
				// 文件
				form.append('file', this.file);
				uploadIdcard(form).then((res) => {
					if (res.code === 200) {
						const {
							name,
							sex,
							idCardNo,
							nation
						} = res.data;
						this.form.setFieldsValue({
							['name']: name,
							['gender']: sex,
							['nation']: nation,
						});
						this.idcard = idCardNo;
					} else {
						this.$message.error(res.msg);
					}
				});
			},
			onDelete() {
				this.idcard = '';
			},
			handleSubmit(e) {
				e.preventDefault();
				this.$refs.form.validate(async (valid) => {
					if (valid) {
						const reg =
							/^(^[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 (!reg.test(this.idcard) && this.idcard) {
							this.$message.error('身份证格式不正确');
							return;
						}
						// if (typeof this.firstAidData.greenRoadFlag == 'boolean') {
						// 	this.firstAidData.greenRoadFlag = 0;
						// }
						console.log(this.patientId)
						if (this.form.id) {

							let res = await createPatient({
								param: {
									...this.form,
									idcard: this.idcard,
									// id:this.patientId
								},
							});
							const {
								data,
								code,
								msg
							} = res;
							if (code === 200) {
								this.confirmLoading = true;
								this.createVisible = false;
								this.$message.success('修改成功');
								this.$emit('on-success', data);
							} else {
								this.confirmLoading = false;
							}


						} else {
							let res = await createPatient({
								param: {
									...this.form,
									idcard: this.idcard,
								},
							});
							const {
								data,
								code,
								msg
							} = res;
							if (code === 200) {
								this.confirmLoading = true;
								this.createVisible = false;
								this.$message.success('创建成功');
								this.$emit('on-success', data);
							} else {
								this.confirmLoading = false;
							}

						}

					}
				});
			},
		},
	};
</script>
<style scoped lang="less">
	.patient-form {
		.create-form {
			padding: 0 .6rem 1rem .6rem;

			.ant-form-item {
				margin-bottom: .5rem;

				.ant-form-item-label {}

				.ant-input {
					font-size: 1rem;
					border: none;
					background: #F5F5F5;
					border-radius: .3rem;

					.acitve {
						border: none !important;
					}
				}

				.ant-select {
					font-size: 1rem;
					border: none;
					background: #F5F5F5;
					border-radius: 6px;

					.ant-select-selection {
						border: none;
						background-color: #F5F5F5;
						font-size: 13px;
					}
				}

			}

			.footer-btns {
				margin-top: 1.2rem;
				padding: 0 1.5rem;
				text-align: center;

				.ant-btn.footer-btn {
					width: 80%;
					border-radius: .8rem;
					height: 3.64vw;
					line-height: 3.64vw;
				}
			}

		}
	}
</style>
<style lang="less">
	.patient-form {
		.ant-modal-body {
			padding-top: 0;
		}

		.ant-modal-content {
			border-radius: 1rem;
			overflow: hidden;

			.ant-modal-header {
				border-bottom: none;
				padding-top: 2rem;

				.ant-modal-title {
					font-size: 2rem;
					font-weight: bold;
					font-family: Source Han Sans CN, Source Han Sans CN-Medium;
					text-align: left;
					color: #393d4e;
					padding: 10px 0;
				}
			}

			.ant-select {

				.ant-select-selection,
				.inputText {
					background-color: #F5F5F5;
					border: none;

					.acitve {
						border: none !important;
					}

				}

				.ant-input:hover {
					border: none
				}

				.ant-select-arrow {
					position: absolute;
					top: 36%;

					svg {
						font-size: 1rem;
						color: #ccc;
					}
				}
			}

			.input-container {
				background-color: #F5F5F5;
				border: none;
			}

			.ant-switch {
				height: 2.73vw;
				width: 4.55vw;
				color: #f5f5f5;
				background-color: #f5f5f5;
			}

			.ant-switch::after {
				width: 2.3vw;
				height: 2.3vw;
				top: 1.5px;
			}

			.ant-switch-checked {
				background-color: #34C759;
			}

			.cencelBtn {
				background: #ddd;
			}
		}


	}
</style>