<template>
  <window-size :showTitle="false">
    <div class="tip-box">
      当前就诊人信息不是我，前往
      <span class="tip-link" @click="toMyCards">我的就诊人</span>
      修改默认就诊人。
    </div>
    <div class="u-demo-block__title" style="margin: 0 0 8px 18px">基本信息</div>
    <van-form ref="loginFormRef">
      <van-cell-group inset>
        <van-field
            v-model="crmPatientMi.pName"
            label="姓名"
            placeholder="请填写姓名"
            required
            :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <van-field
            v-model="crmPatientMi.sexLabel"
            label="性别"
            placeholder="请选择性别"
            required
            readonly
            @click="clickCommonPicker('sex')"
            :rules="[{ required: true, message: '请选择性别' }]"
        />
        <van-field
            v-model="crmPatientMi.age"
            label="年龄"
            placeholder="请填写年龄"
            required
            :rules="[{ required: true, message: '请填写年龄' }]"
        />
        <van-field
            v-model="crmPatientMi.socialNo"
            label="身份证号"
            placeholder="请填写身份证号"
            required
            :rules="[{ required: true, validator: socialNoPattern, message: '请填写正确的身份证号' }]"
        />
        <van-field
            v-model="crmPatientMi.relTel"
            label="手机号"
            placeholder="请填写本人手机号"
            required
            :rules="[{ required: true, message: '请填写本人手机号' }]"
        />
        <van-field
            v-model="crmPatientMi.typeLabel"
            label="患者来源"
            placeholder="请选择患者来源"
            required
            readonly
            @click="clickCommonPicker('pType')"
            :rules="[{ required: true, message: '请选择患者来源' }]"
        />
        <van-field
            v-model="crmPatientMi.chronicDiseaseTypeLabel"
            label="慢病类型"
            placeholder="请选择慢病类型"
            required
            readonly
            @click="clickCommonPicker('chronicDiseaseType')"
            :rules="[{ required: true, message: '请选择慢病类型' }]"
        />
        <van-field
            v-model="crmPatientMi.relNameTel"
            label="联系人电话"
            placeholder="请填写家属电话"
        />
        <van-field
            v-model="crmPatientMi.relLabel"
            label="联系人关系"
            placeholder="请选择联系人关系"
            readonly
            @click="clickCommonPicker('relCode')"
        />
        <van-field
            v-model="crmPatientMi.lastDate"
            label="确诊时间"
            placeholder="请选择确诊时间"
            readonly
            @click="showTimePicker = true"
        />
        <van-field
            v-model="crmPatientMi.districtLabel"
            label="省市区选择"
            placeholder="请选择省市区"
            readonly
            @click="showAddressPicker = true"
        />
        <van-field
            v-model="crmPatientMi.detailAdress"
            label="详细地址"
            placeholder="请填写详细地址"
        />
      </van-cell-group>
    </van-form>
    <!-- 体征信息 -->
    <div class="box">
      <div class="u-demo-block__title">体征信息</div>
      <div class="info">
        <div class="flex">
          <div class="left">身高</div>
          <input type="number" v-model="crmPatientMi.height" placeholder="填写身高"/>
          <div class="btn">cm</div>
        </div>
        <div class="flex">
          <div class="left">体重</div>
          <input type="number" v-model="crmPatientMi.weight" placeholder="填写体重"/>
          <div class="btn">kg</div>
        </div>
        <div class="flex">
          <div class="left">体温</div>
          <input type="number" v-model="crmPatientMi.temperature" placeholder="填写体温"/>
          <div class="btn">℃</div>
        </div>
        <div class="flex">
          <div class="left">心率</div>
          <input type="number" v-model="crmPatientMi.heartRate" placeholder="填写心率"/>
          <div class="btn">次</div>
        </div>
        <div class="flex">
          <div class="left">收缩压</div>
          <input type="number" v-model="crmPatientMi.bloodPressureHigh" placeholder="填写收缩压"/>
          <div class="btn">mmHg</div>
        </div>
        <div class="flex">
          <div class="left">舒张压</div>
          <input type="number" v-model="crmPatientMi.bloodPressureLow" placeholder="填写舒张压"/>
          <div class="btn">mmHg</div>
        </div>
        <div class="flex">
          <div class="left">血糖</div>
          <input type="number" v-model="crmPatientMi.bloodSugar" placeholder="填写血糖"/>
          <div class="btn">mmol/L</div>
        </div>
        <div class="flex">
          <div class="left">血氧</div>
          <input type="number" v-model="crmPatientMi.bloodOxygen" placeholder="填写血氧"/>
          <div class="btn">%</div>
        </div>
      </div>
    </div>
    <van-button style="margin-top:20px" block type="primary" @click="submitChronicDiseaseInfo">提交</van-button>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showTimePicker" round position="bottom">
      <van-date-picker
          v-model="currentDate"
          title="选择日期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="timeConfirm"
          @cancel="showTimePicker = false"
      />
    </van-popup>

    <!-- 普通滑轮选择器 -->
    <van-popup v-model:show="showCommonPicker" round position="bottom">
      <van-picker :columns-field-names="commonPickerField" :columns="commonPickerSelections"
                  @cancel="showCommonPicker = false" @confirm="handleSelectCommonPicker"/>
    </van-popup>

    <van-popup v-model:show="showAddressPicker" position="bottom">
      <van-area :area-list="allArea" v-model="crmPatientMi.districtCode"
                @confirm="onConfirmArea" @cancel="showAddressPicker = false"/>
    </van-popup>

    <van-dialog v-model:show="showPickCardDialog" title="请选择就诊人" @confirm="handleConfirmCard">
      <div style="margin: 20px 0 20px 20px">
        <van-radio-group v-model="crmPatientMi.patientId">
          <van-radio v-for="card in defaultCards" :name="card.patientId" style="margin-bottom: 12px">
            {{ card.name }} / {{ card.socialNo }}
          </van-radio>
        </van-radio-group>
      </div>
    </van-dialog>

  </window-size>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {
  getCrmDictionary, selectCrmPatientMiByCode, saveCrmPatientMi
} from '@/api/chronic-disease';
import {showFailToast, showSuccessToast} from 'vant'
import allArea from '@/utils/area'
import store from "@/store"
import router from "@/router";
import {getDate} from "@/utils/date";

const loginFormRef = ref()

const commonPickerField = {
  text: 'name',
  value: 'label',
}

const showAddressPicker = ref(false)
const onConfirmArea = (values) => {
  crmPatientMi.value.provinceCode = values.selectedValues[0]
  crmPatientMi.value.cityCode = values.selectedValues[1]
  crmPatientMi.value.areaCode = values.selectedValues[2]
  crmPatientMi.value.districtLabel = values.selectedOptions.filter((item) => !!item)
      .map((item) => item.text).join('/')
  showAddressPicker.value = false
}

const crmPatientMi = ref({})

const socialNoPattern = (val) => /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}(\d|X)$/.test(val)

function submitChronicDiseaseInfo() {
  if (!validForm()) {
    return
  }
  if (!crmPatientMi.value.lastDate) {
    crmPatientMi.value.lastDate = null;
  }
  saveCrmPatientMi(crmPatientMi.value).then(() => {
    showSuccessToast('提交成功')
  });
}

function validForm() {
  if (!crmPatientMi.value.pName) {
    showFailToast('请填写姓名');
    return false;
  }
  if (!crmPatientMi.value.sexLabel) {
    showFailToast('请选择性别');
    return false;
  }
  if (!crmPatientMi.value.age) {
    showFailToast('请填写年龄');
    return false;
  }
  if (!crmPatientMi.value.socialNo) {
    showFailToast('请填写身份证号');
    return false;
  }
  if (!crmPatientMi.value.relTel) {
    showFailToast('请填写本人手机号');
    return false;
  }
  if (!crmPatientMi.value.typeLabel) {
    showFailToast('请选择患者来源');
    return false;
  }
  if (!crmPatientMi.value.chronicDiseaseTypeLabel) {
    showFailToast('请选择慢病类型');
    return false;
  }
  return true
}

const showTimePicker = ref(false)

function timeConfirm({selectedValues}) {
  showTimePicker.value = false
  crmPatientMi.value.lastDate =
      `${selectedValues[0]}-${selectedValues[1]}-${selectedValues[2]}`
}

const showCommonPicker = ref(false)
const commonPickerSelections = ref([])
const currentCommonPickerKey = ref(null)

function clickCommonPicker(e) {
  currentCommonPickerKey.value = e
  if (e === 'sex') {
    commonPickerSelections.value = dictData.value.getSexCode
  } else if (e === 'certificateType') {
    commonPickerSelections.value = dictData.value.getPsnCertType
  } else if (e === 'chronicDiseaseType') {
    commonPickerSelections.value = dictData.value.getCrmClass
  } else if (e === 'relCode') {
    commonPickerSelections.value = dictData.value.getRelations
  } else if (e === 'pType') {
    commonPickerSelections.value = dictData.value.getAdmissWay
  }
  showCommonPicker.value = true;
}

function handleSelectCommonPicker(e) {
  showCommonPicker.value = false
  if (currentCommonPickerKey.value === 'sex') {
    crmPatientMi.value.sex = e.selectedOptions[0].code
    crmPatientMi.value.sexLabel = e.selectedOptions[0].name
  } else if (currentCommonPickerKey.value === "source") {
    crmPatientMi.value.source = e.selectedOptions[0].name
  } else if (currentCommonPickerKey.value === "chronicDiseaseType") {
    crmPatientMi.value.chronicDiseaseType = e.selectedOptions[0].code
    crmPatientMi.value.chronicDiseaseTypeLabel = e.selectedOptions[0].name
  } else if (currentCommonPickerKey.value === "relCode") {
    crmPatientMi.value.relCode = e.selectedOptions[0].code
    crmPatientMi.value.relLabel = e.selectedOptions[0].name
  } else if (currentCommonPickerKey.value === "pType") {
    crmPatientMi.value.pType = e.selectedOptions[0].code
    crmPatientMi.value.typeLabel = e.selectedOptions[0].name
  }
}

const toMyCards = () => {
  router.push('/myPatientIdCards')
}

const fetchCrmPatientInfo = (card) => {
  selectCrmPatientMiByCode(card.patientId).then(res => {
    crmPatientMi.value = res
    if (res.districtCode) {
      crmPatientMi.value.districtLabel = getFullRegionNameByDistrict(res.districtCode)
    }
  })
}

const getFullRegionNameByDistrict = (districtCode) => {
  let districtName = allArea.county_list[districtCode]
  if (!districtName) {
    return null
  }
  let cityCode = districtCode.substring(0, 4) + '00';
  let cityName = allArea.city_list[cityCode]
  let provinceCode = cityCode.substring(0, 2) + '0000'
  let provinceName = allArea.province_list[provinceCode]
  return provinceName + '/' + cityName + '/' + districtName
}

const defaultCards = ref([])
const showPickCardDialog = ref(false)

const handleConfirmCard = () => {
  for (let i = 0; i < defaultCards.value.length; i++) {
    const tempCard = defaultCards.value[i]
    if (tempCard.patientId === crmPatientMi.value.patientId) {
      fetchCrmPatientInfo(tempCard)
      return
    }
  }
}

const minDate = ref(new Date(2020, 1, 23))
const maxDate = ref(new Date())
const currentDate = ref(getDate().split('-'))

const analyzeDefaultCard = () => {
  const allCards = store.state.patientCards
  allCards.forEach(card => {
    if (card.isDefault === 1) {
      defaultCards.value.push(card)
    }
  })
  if (defaultCards.value.length === 1) {
    fetchCrmPatientInfo(defaultCards.value[0]);
  }
  store.commit('SET_LOADING', false)
  if (defaultCards.value.length > 1) {
    showPickCardDialog.value = true
  }
}

const dictData = ref({})
onMounted(() => {
  getCrmDictionary().then((res) => {
    dictData.value = res
    if (localStorage.getItem('token')) {
      store.commit('SET_LOADING', true);
      setTimeout(() => {
        analyzeDefaultCard()
      }, 700)
    }
  });
})
</script>

<style scoped>
:deep label {
  color: #000 !important;
}

.tip-box {
  color: #6e6e6e;
  font-size: 12px;
  margin: 8px 0 8px 18px;
}

.tip-link {
  color: dodgerblue;
  text-decoration: underline;
}

.u-demo-block__title {
  font-size: 16px;
  color: #95959b;
  margin: 15px 0 0 12px;
}

.box {
  padding: 5px;
  font-size: 12px;
  box-sizing: border-box;
}

.info {
  width: 100%;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 20rpx;
}

.flex {
  display: flex;
  height: 30rpx;
  width: 50%;
  align-items: center;
  margin-top: 15px;
}

.left {
  width: 50px;
  text-align: center;
}

input {
  height: 30px;
  line-height: 30px;
  border-radius: 4px;
  width: 70px;
  border: 1px solid #e5e8ed;
  padding: 0 5px;
  box-sizing: border-box;
  margin-left: 5px;
}

.btn {
  background-color: #f5f7fa;
  text-align: center;
  width: 50px;
  border: 1px solid #e5e8ed;
  height: 28px;
  line-height: 28px;
}
</style>
