<template>
  <view class="">
    <uni-section type="line" title="患者基本信息" titleFontSize="16px"> </uni-section>
    <uni-forms :modelValue="baseInfo" :label-width="160" class="white uni-radius-lg uni-pa-10">
      <uni-forms-item label="扫描身份证" name="" @click="onScan">
        <view class="flex full-height justify-end">
          <uni-icons type="scan" color="#70798C" size="24" />
        </view>
      </uni-forms-item>

      <uni-forms-item label="姓名" name="patientName">
        <uni-easyinput type="text" v-model="baseInfo.patientName" placeholder="请输入姓名" @change="onBaseChange('patientName', $event)" />
      </uni-forms-item>

      <uni-forms-item name="patientGender" label="性别">
        <uni-data-checkbox v-model="baseInfo.patientGender" :localdata="GENDER_LIST"
                           @change="onBaseChange('patientGender', $event.detail.value)" />
      </uni-forms-item>

      <uni-forms-item label="民族" name="patientNation">
        <uni-data-select :localdata="nationList" v-model="baseInfo.patientNation" :clear="false"
                         @change="onBaseChange('patientNation', $event)" />
      </uni-forms-item>

      <uni-forms-item label="身份证号" name="patientIdCardNo">
        <uni-easyinput type="idcard" v-model="baseInfo.patientIdCardNo" placeholder="请输入身份证号"
                       @change="onBaseChange('patientIdCardNo', $event)" />
      </uni-forms-item>

      <template v-for="(item, key) in codeForm" :key="key">
        <uni-forms-item :name="key" :label="CODE_DICT[key].text" v-if="computeShow(key)">
          <CodeFormItem :code="key" :value="item" :show="computeShow(key)" @on-change="onChange(key, $event)" />
        </uni-forms-item>
      </template>
    </uni-forms>

    <uni-section type="line" title="疑似诊断" titleFontSize="16px"> </uni-section>
    <uni-data-checkbox mode="list" v-model="baseInfo.firstAidZlType" :localdata="FIRST_AID_ZL_TYPE" class="white uni-radius-lg uni-pa-6"
                       @change="onBaseChange('firstAidZlType', $event.detail.value)">
    </uni-data-checkbox>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, inject } from 'vue';
import type { Ref } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { GENDER_LIST, FIRST_AID_ZL_TYPE } from '@/config/service'
import { CODE_DICT } from '@/config/code';
import { useServiceStore } from '@/store/modules/service';

const firstAidId = inject<Ref<string>>('firstAidId')
const userStore = useUserStore()
const serviceStore = useServiceStore()

const baseInfo = reactive({
  patientName: '张三',
  patientGender: 0,
  patientNation: '汉族',
  patientIdCardNo: '142222188901120112',
  firstAidZlType: 0
})

const codeForm = reactive({
  'JBXX-SFXHCZ': '已知',
  'JBXX-FBSJ': '',
  'JBXX-ZHZC-TIME': '',
  'JBXX-SFYNCZ': '是',
  'JBXX-DDJZ-TIME': '',
  'JBXX-TZCZYS-TIME': '',
  'JBXX-CZYSDC-TIME': '',
  'JBXX-LYFS': ''
})

const nationList = ref([])

const token = computed(() => userStore.token)
const currentPatient = computed(() => serviceStore.currentPatient)

// 提交创建急救
async function onSubmit() {
  const param = { ...baseInfo, }
  try {
    const { firstAidId, firstAidStatus } = await uni.$u.api.createAid(param)
    uni.$u.toast('创建成功')
    uni.$u.openPage('detail2', false, `firstAidId=${firstAidId}&firstAidStatus=${firstAidStatus}`)
  } catch (error) {
    uni.$u.alertError(error)
  }
}

// 扫描身份证
function onScan() {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success(res) {
      upload(res.tempFilePaths[0])
    }
  });
}

// 上传
function upload(tempPath: string) {
  const host = uni.getStorageSync(uni.$u.LOCAL_KEY.HOST)
  if (!host) {
    uni.showModal({ title: '提示', content: '请先配置服务器地址' })
    return
  }
  uni.uploadFile({
    url: `${host}/sys/ocr/idcardInfo`, //仅为示例，非真实的接口地址
    filePath: tempPath,
    name: 'file',
    header: { Authorization: `Bearer ${token.value}` },
    success: (uploadFileRes) => {
      if (!uploadFileRes?.data) {
        uni.$u.toast('请求失败')
        return
      }
      const { msg, code, data } = JSON.parse(uploadFileRes.data) as any

      if (code === 200) {
        const { name, sex, idCardNo, nation } = data
        baseInfo.patientName = name || ''
        baseInfo.patientGender = sex || ''
        baseInfo.patientNation = nation || ''
        baseInfo.patientIdCardNo = idCardNo || ''
        // handleScan(url)
      } else if (code === 401) {
        uni.$u.api.login().then(upload(tempPath))
      } else {
        uni.$u.toast(msg)
      }
    }
  });
}

/**
 * 基础信息更新
 * @param {string} type 字段名
 * @param {string} event 值信息
 */
async function onBaseChange(type: string, event: string) {
  console.log(firstAidId?.value);
  if (!firstAidId?.value) {
    uni.$u.alertError('缺少急救id参数')
    return
  }

  const param = { [type]: event, firstAidId: firstAidId?.value }
  try {
    await uni.$u.api.updateAidBase(param)
    uni.$u.toast('更新成功')
  } catch (error) {
    uni.$u.alertError(error)
  }
}

// code form item change
async function onChange(code: string, value: string) {
  codeForm[code] = value
  try {
    if (!firstAidId?.value) {
      uni.$u.alertError('缺少急救id参数')
      return
    }
    const param = { codeAndAnswerList: [{ questionCode: code, answer: [value], time: '' }], firstAidId: firstAidId?.value, sourceId: '', sourceType: '' }
    await uni.$u.api.updateAidCode(param)
    uni.$u.toast('更新成功')
  } catch (error) {
    uni.$u.alertError(error)
  }
}

// 计算code form 前置条件的显示
function computeShow(code: string) {
  const { showType } = CODE_DICT[code]
  if (!showType) return true
  return (showType.type === 'value' && codeForm[showType.code] === showType.value)
}

// 查民族列表
async function getNationList() {
  try {
    const data = await uni.$u.api.getNationList()
    nationList.value = data.map((item: string) => ({ value: item, text: item }))
  } catch (error) {
    uni.$u.alertError(error)
  }
}

function init() {
  // 初始获取民族
  getNationList()

  // 同步store里的急救信息
  if (!currentPatient.value) return
  for (const key in baseInfo) {
    baseInfo[key] = currentPatient.value[key]
  }
  // 同步code信息
  const { recordValDict } = currentPatient.value
  if (!recordValDict) return

  for (const key in codeForm) {
    if (!recordValDict[key]) continue
    codeForm[key] = recordValDict[key][0]?.answer[0] || ''
  }
}


init()
</script>
