<template>
	<div class="patient-detail">
		<div class="patient-info-box">
			<a-card class="patient-info-card">
				<div class="patient-info-header">
					<div class="patient-info-header-title">患者基本信息</div>
					<div class="patient-info-header-btn"><a-button @click="goEditPatient"
							v-if="!authEdit && patientDataCur.id">编辑</a-button>
					</div>
				</div>
				<div class="patient-info-body">
					<a-form-model ref="ruleForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" labelAlign="left"
						class="create-form" :model="form" :rules="rules">

						<a-row :gutter="20">
							<a-col :span="12">
								<a-form-model-item label="姓名" prop="patientName1">
									<a-input v-model="form.patientName" placeholder="请输入姓名" v-if="authEdit"></a-input>
									<div v-else class="edititem"> {{patientDataCur.patientName}} </div>
								</a-form-model-item>
							</a-col>
							<a-col :span="12">
								<a-form-model-item label="民族">
									<a-select v-model="form.patientNation" placeholder="请选择民族" v-if="authEdit">
										<a-select-option v-for="item in nationList" :key="item" :value="item">
											{{ item }}
										</a-select-option>
									</a-select>
									<div v-else class="edititem"> {{patientDataCur.patientNation}} </div>
								</a-form-model-item>
							</a-col>
							<a-col :span="12">
								<a-form-model-item label="性别">
									<a-select v-model="form.patientGender" placeholder="请选择性别" v-if="authEdit">
										<a-select-option :value="0">男</a-select-option>
										<a-select-option :value="1">女</a-select-option>
									</a-select>
									<div v-else class="edititem">
										<span v-if="patientDataCur.patientGender == 0">男</span>
										<span v-else-if="patientDataCur.patientGender == 1">女</span>
									</div>
								</a-form-model-item>
							</a-col>
							<a-col :span="12">
								<a-form-model-item label="身高">
									<a-input v-model="form.height" placeholder="请输入身高 (cm)" @change="bmiChange($event, 'height')" v-if="authEdit" />
									<div v-else class="edititem"> {{patientDataCur.height}} </div>
								</a-form-model-item>
							</a-col>
							<a-col :span="12">
								<a-form-model-item label="体重">
									<a-input v-model="form.weight" placeholder="请输入体重 (kg)" @change="bmiChange($event, 'weight')" v-if="authEdit" />
									<div v-else class="edititem"> {{patientDataCur.weight}} </div>
								</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="form.patientIdCardNo" v-if="authEdit" />
									<div v-else class="edititem">
										{{patientDataCur.patientIdCardNo ? utils.maskIDCard(patientDataCur.patientIdCardNo) : '-'}}
									</div>
								</a-form-model-item>
							</a-col>
							<a-col :span="8" style="padding-top: 0.15vw;" v-if="authEdit">
								<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="请输入联系方式" v-if="authEdit" />
									<div v-else class="edititem">{{patientDataCur.contract}}</div>
								</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="请选择类型" v-if="authEdit">
										<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>
									<div v-else class="edititem">
										<span v-if="patientDataCur.type == 0">卒中急救</span>
										<span v-else-if="patientDataCur.type == 1">胸痛</span>
										<span v-else-if="patientDataCur.type == 2">创伤</span>
									</div>
								</a-form-model-item>
							</a-col>
							<a-col :span="12">
								<a-form-model-item label="平车">
									<!-- <a-select v-model="form.carNo" placeholder="请选择平车号" v-if="authEdit">
										<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="请选择平车号" v-if="authEdit">
										<a-select-option v-for="item in carList" :key="item.id" :value="item.deviceNo">
											{{ item.deviceNo }}
										</a-select-option>
									</a-select>
									<div v-else class="edititem">{{patientDataCur.carNo}}</div>
								</a-form-model-item>
							</a-col>
							<a-col :span="12">
								<a-form-model-item label="绿道状态" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
									<a-switch v-model="form.greenRoadFlag" v-if="authEdit" />
									<div v-else class="edititem">{{patientDataCur.greenRoadFlag}}</div>
								</a-form-model-item>
							</a-col>
							<a-col :span="12" >
								<a-form-model-item label="BMI">
									<div class="edititem" v-if="authEdit">{{form.BMI}}</div>
									<div class="edititem" v-else>{{patientDataCur.BMI}}</div>
								</a-form-model-item>
							</a-col>
						</a-row>
					</a-form-model>
				</div>
				<div class="patient-info-footer">
					<template v-if="!authEdit">
						<!-- <a-button block @click="goPatientList">返回</a-button> -->
						<a-button block type="primary" class="next" @click="goNext">下一步</a-button>
					</template>
					<template v-else>
						<a-button block @click="handleCancel">取消</a-button>
						<a-button block type="primary" class="next" @click="handleSubmit"
							:loading="confirmLoading">完成</a-button>
					</template>


				</div>
			</a-card>
		</div>
		<patient-create ref="patientCreate"></patient-create>
	</div>
</template>

<script>
	import {
		mapMutations,
		mapState
	} from 'vuex';
	import PatientCreate from './patient-create.vue';
	import PatientList from './patient-list.vue';
	import keyboard from '@/components/keyboard.vue';
	import {
		create,
		uploadIdcard,
		idcardInfo,
		idcardInfoBase64,
		createFirstAid,
		createPatient,
		eduitPatient
	} from 'api';
	export default {
		data() {
			return {
				indexNum: 0, //必填字段，为键盘索引，每个键盘必须具有唯一值
				patientIdCardNo: '',
				confirmLoading: false,
				authEdit: false,
				form: {},
				firstAidId: '',
				rules: {
					patientName: [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur'
					}, ],
				}
			}
		},
		props: ['firstAidData', 'carList', 'carNo'],
		components: {
			PatientCreate,
			PatientList,
			keyboard
		},
		computed: {
			...mapState('storm', ['nationList', 'APP_DEVICE_NO']),
			...mapState('patient', ['patientData', 'timerData', 'patientDataCur']),
		},
		async created() {

		},
		watch: {
			patientData() {
				const {
					firstAidId
				} = this.patientData;
				console.log('firstAidId', this.patientData)
				if (!firstAidId) return;
				this.firstAidId = firstAidId
			}
		},
		methods: {
			...mapMutations('patient', [
				'setPatientData',
				'setOverviewType',
				'setTimerData',
				'setVideo',
				'setBook',
			]),
			bmiChange(e, filed){
				if(this.form.height && this.form.weight){
					const bmi = this.utils.computeBMI(this.form.weight, this.form.height)
					// console.log(this.form.height, this.form.weight, bmi)
					if(!isNaN(bmi)) this.form.BMI = bmi
				}
			},
			goPatientList() {
				this.$emit('change', 'patient-list')
			},
			async goNext(e) {

				e.preventDefault();
				this.$refs.ruleForm.validate(async (valid) => {
					if (valid) {
						this.confirmLoading = true;
						// 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.patientIdCardNo) && this.patientIdCardNo) {
						// 	this.$message.error('身份证格式不正确');
						// 	return;
						// }
						// if (typeof this.firstAidData.greenRoadFlag == 'boolean') {
						// 	this.firstAidData.greenRoadFlag = 0;
						// }
						let res = await create({
							param: {
								...this.patientDataCur,
								// patientIdCardNo: "142422199802281819",
								// identityNo: "142422199802281819",
							},
						});

						const {
							data,
							code,
							msg
						} = res;
						if (code === 200) {

							this.home.queryAid(data.firstAidId, false);
							// this.setPatientData({ ...this.patientDataCur, firstAidId: data.firstAidId })
							this.authEdit = false
							this.$message.success('更新成功');
							this.$router.push('/firstaid/thrombolysis')
							// this.$emit('on-success', data);
						}
						this.confirmLoading = false;
					}
				});
				// this.$router.push('/firstaid/thrombolysis')
			},
			goEditPatient() {
				this.form = JSON.parse(JSON.stringify(this.patientDataCur))
				this.authEdit = true
			},
			handleCancel() {
				this.authEdit = false
				this.confirmLoading = false
				this.form = {}
			},
			handleSubmit(e) {
				e.preventDefault();
				this.$refs.ruleForm.validate(async (valid) => {
					if (valid) {
						this.confirmLoading = true;
						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.patientIdCardNo) && this.patientIdCardNo) {
							this.$message.error('身份证格式不正确');
							this.confirmLoading = false;
							return;
						}
						// if (typeof this.firstAidData.greenRoadFlag == 'boolean') {
						// 	this.firstAidData.greenRoadFlag = 0;
						// }
						let res = await eduitPatient({
							param: {
								...this.patientDataCur,
								...this.form
								// patientIdCardNo: this.patientIdCardNo,
							},
						});

						const {
							data,
							code,
							msg
						} = res;
						if (code === 200) {
							this.setPatientData(this.form)
							this.authEdit = false
							this.$message.success('更新成功');
							// this.$router.push('/firstaid/thrombolysis')
							this.$emit('on-success', data);
						}
						this.confirmLoading = false;
					}
				});
			},
			handleClickPatient(item) {
				const {
					sourceId,
					patientName,
					patientAge,
					patientGender,
					firstAidId,
				} = item;
				this.setPatientData({
					sourceId,
					patientName,
					patientAge,
					patientGender,
					firstAidId,
				});
			},
			handleKeyBoard(value) {
				//value为在输入框里面输入的值
				this.patientIdCardNo = value;
			},

			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);
						};
					});
				});
			},
			async idcardInfoBase64(url) {
				let res = await idcardInfoBase64(url);
				const {
					data,
					code,
					msg
				} = res;
				if (code === 200) {
					const {
						name,
						sex,
						idCardNo,
						nation
					} = data;
					this.form.patientName = name
					this.form.patientGender = sex
					this.form.patientNation = nation
					this.patientIdCardNo = idCardNo;
				} else {
					this.$message.error(res.msg);
				}
			},
		}
	}
</script>

<style lang="less" scoped>
	.patient-detail {
		display: flex;
		height: calc(100vh - 180px);
		overflow-y: auto;

		.patient-dlist {
			flex: 1;
		}

		.patient-info {
			flex: 1;
		}

		.patient-info-box {
			flex: 2;
			// padding: 0 2rem 1rem;

			.patient-info-card {
				border-color: rgba(0, 0, 0, 0.09);
				border-radius: .2rem;
				box-shadow: 0 0.18vw 0.73vw rgba(0, 0, 0, 0.09);
				padding: 1rem;
				box-sizing: border-box;
				font-size: 1.3rem;

				.patient-info-header {
					display: flex;
					justify-content: space-between;

					.patient-info-header-title {
						font-size: 1rem;
						font-weight: bold;
						color: #000;
					}

					.patient-info-header-btn {}
				}

				.patient-info-body {
					margin: 1rem 0;
					// .ant-col{
					// 	margin-bottom: 1rem;
					// }
				}

				.patient-info-footer {
					padding: 2rem 15%;

					.ant-btn {
						margin-top: 1rem;
					}
				}
			}
		}


	}
</style>

<style lang="less">
	.patient-detail {
		.ant-card-body {
			padding: 1rem;
		}

		.ant-form-item {
			margin-bottom: .5rem;
			.ant-form-item-label > label::after{
				content: '：';
			}
			.ant-form-item-label {
				label {
					// font-size: 0.75rem;
				}
				
			}

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

				.acitve {
					border: none !important;
				}
			}

			.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;
			}
		}

		.edititem {
			font-size: 16px;
			color: #000;
			// font-weight: 600;
		}
	}
</style>