<template>
  <window-size>
    <div style="height: 5px"></div>
    <van-cell title="诊疗卡与我的关系">
      <template #right-icon>
        <van-radio-group v-model="inputInfo.relation" direction="horizontal">
          <van-radio :name="1">本人</van-radio>
          <van-radio :name="2">他人</van-radio>
        </van-radio-group>
      </template>
    </van-cell>
    <van-tag>请拍摄身份证的人像面照片</van-tag>
    <div :style="uploadHeight" id="capBox">
      <div :style="uploadWidth">
        <van-uploader style="width: 100%; height: 100%" v-model="fileList" :max-count="1">
          <img style="width: 100%; height: 100%" :src="capImg"/>
        </van-uploader>
      </div>
      <div class="cap-tip">
        <van-tag type="danger">拍摄要求</van-tag>
        <p>*&nbsp;&nbsp;身份证置于纯色背景上</p>
        <p>*&nbsp;&nbsp;拍摄身份证时请靠近证件并垂直拍摄</p>
        <div style="margin: 20px">
          <van-button type="primary" block :disabled="disableUpload" @click="resizeIdCard">确定上传</van-button>
          <div style="height: 10px"></div>
          <van-button block @click="showInputDialog = true">没带身份证，填写信息</van-button>
        </div>
      </div>
    </div>
    <van-dialog
        v-model:show="showInputDialog"
        width="90%"
        title="请补充以下信息"
        show-cancel-button
        confirm-button-text="绑定"
        :before-close="beforeClose"
    >
      <div style="padding: 20px">
        <van-field v-model="inputInfo.name" label="姓名" placeholder="请输入姓名"></van-field>
        <van-field v-model="inputInfo.socialNo" label="身份证" placeholder="请输入身份证号"></van-field>
        <van-field v-model="inputInfo.phone" type="tel" label="手机号" placeholder="请输入手机号"></van-field>
        <van-cell title="性别">
          <template #right-icon>
            <van-radio-group v-model="inputInfo.sex" direction="horizontal">
              <van-radio name="M">男</van-radio>
              <van-radio name="F">女</van-radio>
            </van-radio-group>
          </template>
        </van-cell>
        <van-field
            readonly
            clickable
            name="area"
            v-model="inputInfo.address"
            label="住址地区"
            placeholder="点击选择省市区"
            @click="showArea = true"
        />
        <van-popup v-model:show="showArea" position="bottom">
          <van-area :area-list="allArea" :value="defaultDistrict" @confirm="onConfirmArea" @cancel="showArea = false"/>
        </van-popup>
        <van-field v-model="inputInfo.street" label="街道、小区" type="text" placeholder="请输入住址所在街道、小区"/>
        &nbsp;&nbsp;&nbsp;&nbsp;<van-tag type="danger">* 13岁以下儿童建卡请填写监护人信息 *</van-tag>
        <van-field v-model="inputInfo.birthday" label="儿童出生日期" placeholder="例：20180601"></van-field>
        <van-field v-model="inputInfo.guardName" label="监护人姓名" placeholder="请输入监护人姓名"></van-field>
        <van-field v-model="inputInfo.guardIdNo" label="监护人身份证" placeholder="请输入监护人身份证号"></van-field>
      </div>
    </van-dialog>
  </window-size>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import store from '@/store'
import capImg from '@/assets/capture-img.png'
import allArea from '@/utils/area'
import {readImage, readInput} from '@/api/patient-id-cards'
import {isValidIdcard, isValidPhone} from '@/utils/validate'
import {showToast} from 'vant'
import router from '@/router'
import {resize} from '@/utils/image'

const screenSize = store.state.screenSize
const uploadWidth = {
  margin: '10px 60px',
  width: screenSize.w - 120 + 'px',
}
const uploadHeight = {
  height: ((screenSize.w - 120) / 3) * 2 + 'px',
}
const fileList = ref([])
const disableUpload = computed(() => {
  return fileList.value.length !== 1
})
const defaultDistrict = ref('430105')

const uploadIdCard = (base64) => {
  readImage({content: base64}).then((res) => {
    inputInfo.name = res.name
    inputInfo.socialNo = res.socialNo
    inputInfo.sex = res.sex
    inputInfo.district = res.district
    inputInfo.city = res.city
    inputInfo.province = res.province
    inputInfo.address = res.address
    inputInfo.street = res.street
    if (res.district) {
      defaultDistrict.value = res.district
    } else {
      defaultDistrict.value = '430105'
    }
    showInputDialog.value = true
  })
}

const resizeIdCard = () => {
  let content = fileList.value[0].content
  if (content.length / 1024 < 500) {
    uploadIdCard(content)
  } else {
    resize(content, uploadIdCard)
  }
}

const inputInfo = reactive({
  relation: 1,
  name: null,
  socialNo: null,
  phone: null,
  address: null,
  province: null,
  city: null,
  district: null,
  street: null,
  sex: null,
})
const showInputDialog = ref(false)
const showArea = ref(false)
const onConfirmArea = (values) => {
  inputInfo.province = values[0].code
  inputInfo.city = values[1].code
  inputInfo.district = values[2].code
  inputInfo.address = values
      .filter((item) => !!item)
      .map((item) => item.name)
      .join('/')
  showArea.value = false
}
const beforeClose = (action) =>
    new Promise((resolve) => {
      if (action === 'cancel') {
        showInputDialog.value = false
        resolve(false)
      } else {
        if (!inputInfo.name) {
          showToast({
            message: '请输入姓名',
            position: 'top',
          })
          resolve(false)
          return
        }
        if (!isValidIdcard(inputInfo.socialNo) && !isValidIdcard(inputInfo.guardIdNo)) {
          showToast({
            message: '请输入正确的身份证号码',
            position: 'top',
          })
          resolve(false)
          return
        }
        if (!isValidPhone(inputInfo.phone)) {
          showToast({
            message: '请输入正确的手机号码',
            position: 'top',
          })
          resolve(false)
          return
        }
        if (!inputInfo.sex) {
          showToast({
            message: '请选择性别',
            position: 'top',
          })
          resolve(false)
          return
        }
        if (!inputInfo.province || !inputInfo.city) {
          showToast({
            message: '请选择住址地区',
            position: 'top',
          })
          resolve(false)
          return
        }
        if (!inputInfo.street) {
          showToast({
            message: '请输入街道、小区',
            position: 'top',
          })
          resolve(false)
          return
        }
        if (inputInfo.guardName && !inputInfo.birthday) {
          showToast({
            message: '请输入儿童出生日期',
            position: 'top',
          })
          resolve(false)
          return
        }
        setTimeout(() => {
          readInput(inputInfo).then((res) => {
            store.dispatch({
              type: 'storePatientCards',
              cards: res.cards
            }).then(() => {
              showToast({
                message: '绑卡成功！',
                position: 'top'
              })
              resolve(true)
              router.go(-1)
            })
          }).catch(() => {
            resolve(false)
          })
        }, 500)
      }
    })
</script>

<style>
#capBox .van-uploader__upload,
#capBox .van-uploader__preview,
#capBox .van-uploader__preview-image {
  width: 100% !important;
  height: 100% !important;
}

.cap-tip p {
  font-size: 13px;
  margin-left: 10px;
  color: orangered;
}
</style>
