<template>
	<div class="BasicInfo">
		<div class="basic-content">
			<!-- 患者基本信息 -->
			<div class='basicr-back'>
				<a-form class="detail-form" :form="baseForm" labelWitch="260px" :labelCol="{span: 6}"  :wrapperCol="{span: 16}">
					<a-form-item label="扫描身份证">
						<div class="detail-form-control">
							<a-upload :disabled="writeAble" class="idcard-upload" accept=".img,.png,.jpg"
								:before-upload="handleBeforeUpload" :showUploadList="false" name="file"
								:multiple="false" :customRequest="handleUploadAdd">
								<a-icon type="scan" class="fz24" />
							</a-upload>
						</div>
					</a-form-item>
					<a-form-item label="姓名">
						<div class="detail-form-control" >
							<a-input :disabled="writeAble" v-decorator="['patientName']" style="width: 448px;"
								@blur="onBaseChange($event.target.value, 'patientName')" placeholder='请输入' />
						</div>
					</a-form-item>
					<a-form-item label="性别">
						<div class="detail-form-control">
							<a-radio-group :disabled="writeAble" v-decorator="['patientGender']"  style="width: 448px;"
								@change="onBaseChange($event.target.value, 'patientGender')">
								<a-radio :value='0'> 男 </a-radio>
								<a-radio :value='1'> 女 </a-radio>
							</a-radio-group>
						</div>
					</a-form-item>
					<a-form-item label="民族">
						<div class="detail-form-control">
							<a-select :disabled="writeAble" ref="select" v-decorator="['patientNation']"  style="display: block;width: 448px;"
								@change="handleChange($event, 'patientNation', 'default')" placeholder='请选择'>
								<a-select-option v-for="item in nationList" :key="item" :value="item">
									{{item}}
								</a-select-option>
							</a-select>
						</div>
					</a-form-item>
					<a-form-item label="身份证号">
						<div class="detail-form-control">
							<a-input :disabled="writeAble" v-decorator="['patientIdCardNo']" placeholder='请输入'
								@blur="onBaseChange($event.target.value, 'patientIdCardNo')"  style="width: 448px;" />
						</div>
					</a-form-item>
					<a-form-item v-for="(k,v) in BASE_CODE" :key="v" :label="k.text" v-if="computeShow(v, codeForm)">
						<div class="detail-form-control">
							<!-- radio -->
							<a-radio-group :disabled="writeAble" v-if="k.type==='radio'"  style="width: 448px;" v-decorator="[
					      v,
					      {initialValue: codeForm[k] },
					    ]" @change="handleChange($event.target.value, v)">
								<a-radio v-for="(item,index) in k.range" :key="item" :value="item">
									{{item}}
								</a-radio>
							</a-radio-group>
							<!-- input -->
							<a-input :disabled="writeAble" v-if="k.type==='input'" :type="k.inputType" v-decorator="[
						  v]" @blur="handleChange($event.target.value, v)" placeholder='请输入'  style="width: 448px;">
							</a-input>
							<!-- datetime -->
							<a-input :disabled="writeAble" v-if="k.type==='datetime'" readOnly @click="selectOption(v)"  style="width: 448px;"
								v-decorator="[
						  v,
						]" placeholder='请选择'>
							</a-input>
							<a-select :disabled="writeAble" v-if="k.type==='select'" v-decorator="[
						v]" @change="handleChange($event, v)" placeholder='请选择' style="display: block;width: 448px;">
								<a-select-option v-for="item in k.range" :key="item" :value="item">
									{{item}}
								</a-select-option>
							</a-select>
						</div>
					</a-form-item>
				</a-form>
			</div>
			<!-- 疑似诊断 -->
			<div class='diagnosis'>
				<v-head text='疑似诊断'></v-head>
				<div class='back-ff'>
					<a-radio-group :disabled="writeAble" v-model:value="firstAidZlType"  style="width: 448px;"
						@change="onBaseChange($event.target.value, 'firstAidZlType')">
						<a-radio :style="radioStyle" v-for="(k,v) in FIRSTAIDZLTYPE_DICT" :key="v"
							:value="v">{{k}}</a-radio>
					</a-radio-group>
				</div>
			</div>
			<div class="common-picker">
				<van-datetime-picker v-if="pickerVisable" v-model="currentDate" :formatter="formatter"
					@cancel="pickerVisable = false" @confirm="onConfirm" style="width: 448px;" />
			</div>
		</div>
		<div class="basic-footer">
			<a-button :disabled="writeAble" class="common-button" block type="primary" size="large"
				@click="onSubmit">{{patientId ? '保存' : '下一步'}}</a-button>
			<!-- <a-button :disabled="writeAble" type="link" size="large" @click="onSubmit">
				保存<a-icon type="check" />
			</a-button> -->
		</div>
	</div>
</template>

<script>
	import head from '@/views/Patient/components/title.vue';
	import {
		uploadIdcard,
		updateFirstAid,
		queryAidRecord
	} from 'api'
	import {
		mapMutations,
		mapState
	} from 'vuex'
	import {
		BASE_CODE
	} from '@/config/code.js'
	import {
		FIRSTAIDZLTYPE_DICT
	} from '@/config/dict.js'
	export default {
		name: 'BasicInfo',
		data() {
			return {
				BASE_CODE,
				FIRSTAIDZLTYPE_DICT,
				// 当前选中日期
				currentDate: new Date(),
				//日期选择器是否展示
				pickerVisable: false,
				radioStyle: {
					display: 'block',
					height: '30px',
					lineHeight: '30px',
				},
				baseForm: this.$form.createForm(this, {
					name: 'BasicInfo'
				}),
				//页面中使用code
				codeForm: {
					'JBXX-SFXHCZ': '已知',
					'JBXX-FBSJ': '',
					'JBXX-ZHZC-TIME': '',
					'JBXX-SFYNCZ': '是',
					'JBXX-DDJZ-TIME': '',
					'JBXX-TZCZYS-TIME': '',
					'JBXX-CZYSDC-TIME': '',
					'JBXX-LYFS': '',
				},
				firstAidZlType: 0, //疑似诊断
				selectCode: '' // 当前选中code
			}
		},
		props: ['patientId'],
		components: {
			'v-head': head
		},
		computed: {
			...mapState('patient', ['patientData', 'writeAble']),
			...mapState('storm', ['nationList'])
		},
		async mounted() {
			console.log('patientId', this.patientId)
			if (this.patientId) {
				const res = await queryAidRecord(this.patientId)

				this.$nextTick(() => {
					this.echo(res.data)
				})
			} else {
				this.$nextTick(() => {
					if (this.patientData) {
						this.echo(this.patientData)
					}
				})
			}

		},
		methods: {
			echo(data) {
				const {
					recordValDict,
					patientName,
					patientGender,
					patientNation,
					patientIdCardNo,
					firstAidZlType
				} = data
				this.firstAidZlType = firstAidZlType && firstAidZlType.toString() || '0'
				this.baseForm.getFieldDecorator([patientName,
					patientGender,
					patientNation,
					patientIdCardNo
				], {
					preserve: true, //即便字段不再使用，也保留该字段的值
				})
				this.baseForm.setFieldsValue({
					patientName,
					patientGender,
					patientNation,
					patientIdCardNo
				});
				for (let k in recordValDict) {
					if (recordValDict[k]) {
						const {
							answer
						} = recordValDict[k][0]
						if (Object.keys(this.codeForm).includes(k)) {
							this.codeForm[k] = answer.toString()
						}
						this.baseForm.getFieldDecorator([`${k}`], {
							preserve: true, //即便字段不再使用，也保留该字段的值
						})
						this.baseForm.setFieldsValue({
							[`${k}`]: answer.toString(),
						});
					}
				}
			},
			computeShow(code, codeForm) {
				return this.utils.computeShow(code, codeForm)
			},
			selectOption(v) {
				this.selectCode = v
				this.pickerVisable = true
			},
			//格式化日期
			formatter(type, val) {
				if (type === 'year') {
					return val + '年';
				}
				if (type === 'month') {
					return val + '月';
				}
				if (type === 'day') {
					return val + '日';
				}
				if (type === 'hour') {
					return val + '时';
				}
				if (type === 'minute') {
					return val + '分';
				}
				return val;
			},
			//
			onConfirm(date) {
				this.baseForm.setFieldsValue({
					[`${this.selectCode}`]: this.utils.format(date),
				});
				this.pickerVisable = false
				// this.updateAidBase(this.selectCode, this.utils.format(date))
			},
			handleChange(value, code, type) {
				const codes = ['patientGender', 'patientIdCardNo', 'patientName', 'patientNation']
				if (!codes.includes(code)) {
					this.codeForm[code] = value
				}
				// this.updateAidBase(code, value, type)
			},
			async onBaseChange(value, code) {
				if (code === 'patientIdCardNo') {
					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(value)) {
						this.$message.error('身份证格式不正确')
						return
					}
				}
				// await this.home.updateAidCode({
				// 	[`${code}`]: value
				// }, false)
			},
			//更新基本信息
			async updateAidBase(code, value, type) {
				let params
				let codeAndAnswerList = []
				if (type) {
					params = {
						[`${code}`]: value
					}
				} else {
					let answer = [value]
					if (typeof value !== 'string') {
						answer = value
					}
					codeAndAnswerList.push({
						questionCode: code,
						answer,
						time: ''
					})
				}
				await this.home.updateAidCode({
					...params,
					codeAndAnswerList
				}, false)
			},
			// 上传前校检格式和大小
			handleBeforeUpload(file) {
				this.file = file
				const isLt10M = file.size / 1024 / 1024 < 10000;
				// 校检文件大小
				if (!isLt10M) {
					this.$message.error('上传头像图片大小不能超过 10MB!');
				}
				return isLt10M;
			},
			async onSubmit(e) {
				e.preventDefault();
				let firstAidId = this.patientData.firstAidId
				let codeAndAnswerList = [],
					params = {
						firstAidId
					}
				const codes = ['patientGender', 'patientIdCardNo', 'patientName', 'patientNation']
				this.$nextTick(async () => {
					this.baseForm.validateFields(async (err, values) => {
						for (var k in values) {
							if (Object.keys(this.codeForm).includes(k)) {
								let answer = [values[k]]
								if (typeof values[k] !== 'string') {
									answer = values[k]
								}
								if (values[k]) {
									codeAndAnswerList.push({
										questionCode: k,
										answer,
										time: ''
									})
								}
							} else if (codes.includes(k)) {
								params[`${k}`] = values[k]
							}
						}
						var res = await updateFirstAid(params)
						await this.home.updateAidCode({
							codeAndAnswerList
						}, false)
						this.$message.success(res.msg)
						this.$emit('next')
					})
				})
			},
			// 上传成功回
			handleUploadAdd() {
				// 使用FormData传参数和文件
				var form = new FormData();
				// 文件
				form.append('file', this.file);
				uploadIdcard(form).then((res) => {
					if (res.code === 200) {
						if (res.data) {
							const {
								name,
								sex,
								idCardNo,
								nation
							} = res.data;
							this.baseForm.setFieldsValue({
								['patientName']: name,
								['patientGender']: sex,
								['patientNation']: nation,
								['patientIdCardNo']: idCardNo
							});
						} else {
							this.$message.error('请扫描正确身份证');
						}
					} else {
						this.$message.error(res.msg);
					}
				});

			}
		}
	}
</script>

<style scoped lang="less">
	p {
		margin: 0;
	}

	.basic-content {
		flex: 1;
		overflow-y: auto;
	}

	.BasicInfo {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.basic-footer {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 20px;
		padding: 0 10%;
	}
</style>
<style scoped>
	>>>.ant-btn-link {
		color: #7690e5;
		font-size: 24px;
		font-weight: bold;
	}

	>>>.ant-radio-wrapper {
		text-align: left;
		font-size: 24px;
		height: 58px !important;
		line-height: 58px !important;
		box-sizing: border-box;
		border-bottom: 1px solid #f0f0f0 !important;
	}

	>>>.ant-col.ant-form-item-control-wrapper {
		flex: 2;
	}

	>>>.ant-radio-wrapper:last-child {
		border-bottom: none !important;
	}

	>>>.ant-radio {
		font-size: 24px;
	}

	>>>.ant-radio-inner::after {
		width: 16px;
		height: 16px;
	}

	>>>.ant-radio-inner {
		width: 24px;
		height: 24px;
	}

	>>>.container-left-header {
		padding-bottom: 0;
	}

	.back-ff {
		box-shadow: 0 2px 12px 0 rgba(52, 52, 52, .1);
		background: #fff;
		padding: 10px 20px;
		border-radius: 12px;
	}
</style>