<template>
  <uni-card :is-shadow="false" :border="false" style="width: 40vw" padding="10px">
    <template v-slot:title>
      <view class="text-center u-font-16 font-bold uni-mt-10">
        患者信息
      </view>
    </template>

    <uni-forms ref="formRef" :modelValue="formData" :rules="rules">
      <uni-forms-item label="姓名" name="name">
        <uni-easyinput type="text" v-model="formData.name" placeholder="请输入姓名" />
      </uni-forms-item>
      <uni-forms-item name="gender" label="性别">
        <uni-data-checkbox v-model="formData.gender" :localdata="genders" />
      </uni-forms-item>
      <uni-forms-item label="身份证" name="idCard">
        <uni-easyinput type="text" v-model="formData.idCard" placeholder="请输入身份证号" />
      </uni-forms-item>
      <uni-forms-item label="民族" name="nation">
        <uni-easyinput type="text" v-model="formData.nation" placeholder="请输入民族" />
      </uni-forms-item>
    </uni-forms>

    <template v-slot:actions>
      <view class="flex primary justify-center uni-pb-10" @click="$emit('on-scan')">
        扫描身份证
      </view>
      <view class="flex justify-between uni-mb-16">
        <u-button size="medium" shape="circle" @click="onCancel">取消</u-button>
        <u-button size="medium" type="primary" shape="circle" class="bg-main" @click="onConfirm">确定</u-button>
      </view>
    </template>
  </uni-card>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';

const emits = defineEmits(['on-cancel', 'on-confirm', 'on-scan'])

const formData = reactive({
  name: '',
  gender: 0,
  idCard: '',
  nation: '汉'
})

const rules = {
  name: { rules: [{ required: true, errorMessage: '请输入姓名' }] },
  idCard: {
    rules: [
      { required: true, errorMessage: '请输入身份证号' },
      {
        validateFunction(_rule, value: string, _data, callback: Function) {
          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)) {
            callback('身份证格式不正确')
          }
          return true
        }
      }]
  },
  nation: { rules: [{ required: true, errorMessage: '请输入民族' }] },
}

const genders = [
  { label: '男', value: 0, text: '男' },
  { label: '女', value: 1, text: '女' }
]

const formRef = ref()

function onCancel() {
  emits('on-cancel')
}

function onConfirm() {
  if (!formRef.value) return
  formRef.value.validate().then(res => {
    console.log(res);
    emits('on-confirm', formData)
  }).catch(error => {
    console.log(error);

  })
}
</script>

<style lang="scss" scoped>
</style>
