<template>
  <page-layer>
    <template #header>
      <el-date-picker
          v-model="datePeriod"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="healthCardShortcuts"
          style="width: 200px"
      ></el-date-picker>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" icon="Camera" @click="scanBarCode">扫描健康证条码</el-button>
      <el-button type="primary" icon="Edit" @click="fixTjNo">修正体检号</el-button>
      <el-button type="primary" icon="Upload" @click="uploadSelected(null)">推送选中检查</el-button>
      <el-divider direction="vertical"></el-divider>
      <el-checkbox v-model="autoPush">在检验结果完整时自动推送</el-checkbox>
    </template>
    <template #main>
      <el-container>
        <el-aside width="400px">
          <el-table ref="indexTable" :data="inspectionsIndex" stripe :height="tableHeight" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="ordr_CREATE_DATE" label="报告时间" width="130"></el-table-column>
            <el-table-column prop="aply_CTNT" label="检验名称"></el-table-column>
          </el-table>
        </el-aside>
        <el-main>
          <el-card class="box-card">
            <template #header>
              <div class="card-header">条码信息</div>
            </template>
            <div class="card-info-line">条码：{{ customerInfo.barCode }}</div>
            <div class="card-info-line">姓名：{{ customerInfo.name }}</div>
            <div class="card-info-line">性别：{{ customerInfo.sex }}</div>
            <div class="card-info-line">年龄：{{ customerInfo.age }}</div>
            <div class="card-info-line">体检号：{{ tjNo }}</div>
            <div class="card-info-line">身份证：{{ customerInfo.idCard }}</div>
          </el-card>
          <el-divider></el-divider>
          <div class="push-result">大便培养推送结果：<span v-html="makeColoredRes(pushResult.JK01)"></span></div>
          <div class="push-result">甲肝戊肝推送结果：<span v-html="makeColoredRes(pushResult.JK02)"></span></div>
          <div class="push-result">核酸检测推送结果：<span v-html="makeColoredRes(pushResult.JK03)"></span></div>
        </el-main>
      </el-container>
    </template>
  </page-layer>
</template>

<script>
import { onMounted, ref } from 'vue'
import { healthCardShortcuts } from '@/data/shortcuts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getIndexByBarCode, getIndexByTjNo, pushSelectedResult } from '@/api/inspections'
import store from '@/store'
import { formatDate } from '@/utils/date'
import PageLayer from "@/layout/PageLayer";
export default {
  name: 'UploadToHealthCard',
  components: {PageLayer},
  setup() {
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 45
    const datePeriod = ref([])
    const customerInfo = ref({})
    const tjNo = ref('')
    const indexTable = ref(null)
    const inspectionsIndex = ref([])
    const multipleSelection = ref([])
    const pushResult = ref({})
    const autoPush = ref(true)

    const makeParam = (value) => {
      if (!datePeriod.value) {
        ElMessage({
          message: '请选择日期范围',
          type: 'warning',
          duration: 2000,
          showClose: true,
        })
        return
      }
      return {
        start: formatDate(datePeriod.value[0]),
        end: formatDate(datePeriod.value[1]),
        content: value,
      }
    }

    const scanBarCode = () => {
      ElMessageBox.prompt('请扫描或输入健康证条码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(({ value }) => {
          pushResult.value = {}
          getIndexByBarCode(makeParam(value)).then((res) => {
            tjNo.value = res.tjNo
            customerInfo.value = res.customerInfo
            inspectionsIndex.value = res.inspectionsIndex
            if (!res.inspectionsIndex || res.inspectionsIndex.length === 0) {
              ElMessageBox.confirm('没有找到【姓名：' + customerInfo.value.name + '，体检号：' + res.tjNo + '】的体检结果，请尝试修正体检号。', '提示', {
                type: 'warning',
                confirmButtonText: '修正体检号',
                cancelButtonText: '取消',
              })
                .then(() => {
                  fixTjNo()
                })
                .catch(() => {})
            } else {
              if (autoPush.value && isInspectionsCompleted(inspectionsIndex.value)) {
                setTimeout(() => {
                  toggleSelection(inspectionsIndex.value)
                }, 100)
              }
            }
          })
        })
        .catch(() => {})
    }

    const fixTjNo = () => {
      if (!customerInfo.value.name) {
        ElMessage({
          message: '请先扫描健康证条码。',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }
      ElMessageBox.prompt('请扫描或输入【' + customerInfo.value.name + '】的体检号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(({ value }) => {
          getIndexByTjNo(makeParam(value)).then((res) => {
            if (!res || res.length === 0) {
              ElMessage({
                message: '没有找到体检号【' + value + '】对应的检查，请确认日期范围是否正确。',
                type: 'warning',
                duration: 2500,
                showClose: true,
              })
            } else {
              inspectionsIndex.value = res
              if (autoPush.value && isInspectionsCompleted(inspectionsIndex.value)) {
                setTimeout(() => {
                  toggleSelection(inspectionsIndex.value)
                }, 100)
              }
            }
          })
        })
        .catch(() => {})
    }

    const isInspectionsCompleted = (val) => {
      if (!val || val.length < 2) {
        return false
      }
      let jk01 = false
      let jk02 = false
      let jk03 = false
      val.forEach((item) => {
        if (item.aply_CTNT.indexOf('大便培养') !== -1 || item.aply_CTNT.indexOf('大便体检') !== -1) {
          jk01 = true
        }
        if (item.aply_CTNT.indexOf('甲肝抗体') !== -1 && item.aply_CTNT.indexOf('戊肝抗体') !== -1) {
          jk02 = true
        }
        if (item.aply_CTNT.indexOf('核酸') !== -1) {
          jk03 = true
        }
      })
      return jk01 && jk02
    }

    const toggleSelection = (rows) => {
      for (let i = 0; i < rows.length; i++) {
        indexTable.value.toggleRowSelection(rows[i])
      }
      uploadSelected(rows)
    }

    const handleSelectionChange = (val) => {
      multipleSelection.value = val
    }

    const uploadSelected = (rows) => {
      const param = {
        customerInfo: customerInfo.value,
        inspectionsIndex: rows ? rows : multipleSelection.value,
      }
      pushSelectedResult(param).then((res) => {
        pushResult.value = res
        if (res.JK01 === '推送成功' && res.JK02 === '推送成功') {
          ElMessage({
            message: '推送成功。',
            type: 'success',
            duration: 2500,
            showClose: true,
          })
          scanBarCode()
        } else {
          ElMessage({
            message: '推送失败。',
            type: 'error',
            duration: 2500,
            showClose: true,
          })
        }
      })
    }

    onMounted(() => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      datePeriod.value = [start, end]
    })
    return {
      tableHeight,
      datePeriod,
      healthCardShortcuts,
      scanBarCode,
      customerInfo,
      indexTable,
      inspectionsIndex,
      handleSelectionChange,
      multipleSelection,
      uploadSelected,
      pushResult,
      makeColoredRes,
      autoPush,
      tjNo,
      fixTjNo,
    }
  },
}

function makeColoredRes(val) {
  if (!val) {
    return ''
  }
  if (val.indexOf('成功') !== -1) {
    return '<span style="color:green">' + val + '</span>'
  }
  return '<span style="color:red">' + val + '</span>'
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.box-card {
  width: 480px;
}
.card-info-line {
  height: 30px;
  line-height: 30px;
}
.push-result {
  width: 460px;
  height: 50px;
  line-height: 50px;
  background: white;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border-radius: 4px;
  border: 1px solid #ebeef5;
  color: #303133;
  margin-bottom: 10px;
  padding-left: 20px;
}
</style>
