<template>
  <el-container style="width: 1400px;">
    <el-header style="height: 30px">
      名称：
      <el-autocomplete v-model="orderName" :fetch-suggestions="querySearchAsync" clearable style="width: 120px"
                       @keyup.enter="dianJiChaXunHuanZheJianCha(0)"></el-autocomplete>

      <el-date-picker
          v-model="dateRange"
          :shortcuts="shortcuts"
          end-placeholder="申请结束"
          placeholder="选择日期"
          range-separator="至"
          size="small"
          start-placeholder="申请开始"
          style="width: 220px"
          type="daterange"/>
      <el-button icon="Search" type="primary" @click="dianJiChaXunHuanZheJianCha(0)">查询</el-button>
      <el-divider direction="vertical"></el-divider>
      <el-button icon="Check" type="success" @click="saveData">保存</el-button>
      <el-button icon="Check" type="primary" @click="saveTemplate"
                 :disabled="addCheckList.length ===0">存为模板
      </el-button>
      搜索：
      <xc-combo-grid :query-data-func="getJcItem" @rowClick="searchAdd">
        <el-table-column label="编码" prop="code"/>
        <el-table-column width="240" label="名称" prop="name"/>
        <el-table-column label="执行科室" prop="execUnitName"/>
      </xc-combo-grid>
    </el-header>
    <el-container>
      <el-aside style="width: 450px">
        <el-tabs v-model="asideTabs">
          <el-tab-pane :name="0" label="新申请">
            <new-application/>
          </el-tab-pane>
          <el-tab-pane :name="1" label="历史记录">
            <check-application-history :data="jianChaShuJu"
                                       :returnData="dianJiaJianChaXiangQing"
                                       :current-change="handleCurrentChange"/>
          </el-tab-pane>
        </el-tabs>
      </el-aside>
      <el-main>
        <el-tabs v-model="mainTabs">
          <el-tab-pane :name="0" label="检查申请单">
            <div :style="{height:windowSize.h / 1.4 + 'px' }" style="overflow: auto">
              <print-check-v2 ref="daYingJianChaRef"/>
            </div>
          </el-tab-pane>
          <el-tab-pane :name="1" label="检查结果">
            <jian-cha-jie-guo ref="jianChaJieGuoRef" :pat-info="huanZheXinXi"/>
          </el-tab-pane>
          <el-tab-pane :name="3" label="编辑数据">
            <xc-table :local-data="addCheckList"
                      :default-expand-all="false"
                      :height="350">
              <el-table-column label="操作" width="90" fixed="left">
                <template #default="scope">
                  <el-button-group>
                    <el-button type="primary" icon="Edit" title="编辑" @click="openTheEditPopUpWindow(scope.$index)"/>
                    <el-button type="danger" icon="Delete" title="删除" @click="deleteRequest(scope.$index)"/>
                  </el-button-group>
                </template>
              </el-table-column>
              <el-table-column label="编码" prop="orderCode" width="60"></el-table-column>
              <el-table-column label="名称" prop="orderName" width="220" show-overflow-tooltip></el-table-column>
              <el-table-column label="诊断" prop="diagText" width="120" show-overflow-tooltip></el-table-column>
              <el-table-column label="病室摘要" prop="reqComment" show-overflow-tooltip></el-table-column>
              <el-table-column label="体征信息" prop="reqTzComment" show-overflow-tooltip></el-table-column>
              <el-table-column label="相关辅检结果" prop="reqOtherResult" show-overflow-tooltip></el-table-column>
              <el-table-column label="检查时间" prop="startTime" width="130"/>
              <el-table-column label="执行科室" prop="execDeptName" width="110"></el-table-column>
              <el-table-column label="急诊" width="40">
                <template #default="{row}">
                    <span v-if="row.jzFlag === 1">
                      √
                    </span>
                </template>
              </el-table-column>
              <el-table-column label="自费" width="40">
                <template #default="{row}">
                    <span v-if="row.ybSelfFlag === 1">
                      √
                    </span>
                </template>
              </el-table-column>
            </xc-table>
          </el-tab-pane>
        </el-tabs>
        <xc-dialog-v2 v-model="editor.dialog" title="检查编辑">
          <inspection-requisition :data="editor.data"
                                  :diagnosis="diagnosis"
                                  :search-diagnostics="searchDiagnostics"/>

          <template #footer>
            {{ (editor.index + 1) + '/' + addCheckList.length }}
            <el-button-group>
              <el-button @click="openTheEditPopUpWindow(editor.index-1)" :disabled="editor.index === 0">上一个
              </el-button>
              <el-button @click="openTheEditPopUpWindow(editor.index+1)"
                         :disabled="editor.index === addCheckList.length - 1">下一个
              </el-button>
            </el-button-group>
            <el-button type="primary" @click="editor.dialog = false">确认</el-button>
          </template>
        </xc-dialog-v2>
      </el-main>
      <save-template-inspection ref="saveTemplateRef"/>
    </el-container>
  </el-container>
</template>

<script setup name="JianChaShenQing">
import {
  addJcCheck,
  addCheckList, cuoWuXinXi,
  huanZheXinXi,
  youWuXuanZheHuanZhe
} from '@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng'
import {computed, ref, watch} from 'vue'
import {
  baoCunJianYanJianCha,
  diagnosisInOurHospital, getJcItem,
  huoQuJianChaShenQing,
  huoQuJianYanJianChaMing,
  huoQuShengQingXiangQing,
  queryCheckTextResults,
} from '@/api/zhu-yuan-yi-sheng/jian-yan-jian-cha-shen-qing'
import store from '@/store'
import {getDateRangeFormatDate} from '@/utils/date'
import {shortcuts} from '@/data/shortcuts'
import {ElMessageBox} from 'element-plus'
import CheckApplicationHistory from "@/components/zhu-yuan-yi-sheng/jian-cha-shen-qing/aside/CheckApplicationHistory";
import NewApplication from "@/components/zhu-yuan-yi-sheng/jian-cha-shen-qing/aside/NewApplication";
import InspectionRequisition
  from "@/views/hospitalization/zhu-yuan-yi-sheng/jian-cha-jian-yan-shen-qing/InspectionRequisition";
import SaveTemplateInspection
  from "@/views/hospitalization/zhu-yuan-yi-sheng/jian-cha-jian-yan-shen-qing/SaveTemplateInspection";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import {yaoPinXiangMuPiPeiYiBao} from "@/api/public-api";
import {stringNotBlank} from "@/utils/blank-utils";
import JianChaJieGuo from "@/components/zhu-yuan-yi-sheng/jian-cha-shen-qing/da-ying/JianChaJieGuo.vue";
import XcTable from "@/components/xiao-chan/xc-table/XcTable.vue";
import XcDialogV2 from "@/components/xiao-chan/dialog/XcDialogV2.vue";
import XcComboGrid from "@/components/xiao-chan/combo-grid/XcComboGrid.vue";
import PrintCheckV2 from "@/components/zhu-yuan-yi-sheng/jian-cha-shen-qing/da-ying/PrintCheckV2.vue";


const windowSize = computed(() => {
  return store.state.app.windowSize
})


const orderName = ref('')
const dateRange = ref(null)
const jianChaShuJu = ref({
  currentPage: 1,
  total: 0,
  pageSize: 20,
  data: [],
})
const asideTabs = ref(0)
const mainTabs = ref(3)

const daYingJianChaRef = ref()
// 检查结果
const jianChaJieGuoRef = ref()

/**
 * 点击查询患者检查
 * @param total
 */
const dianJiChaXunHuanZheJianCha = (total) => {
  let dateS = getDateRangeFormatDate(dateRange.value)
  let param = {
    patNo: huanZheXinXi.value.inpatientNo,
    times: huanZheXinXi.value.admissTimes,
    orderName: orderName.value,
    total: total,
    currentPage: jianChaShuJu.value.currentPage,
    pageSize: jianChaShuJu.value.pageSize,
    startTime: dateS.startTime,
    endTime: dateS.endTime,
  }
  huoQuJianChaShenQing(param).then((res) => {
    if (total === 0) {
      jianChaShuJu.value.total = res.total
    }
    asideTabs.value = 1
    jianChaShuJu.value.data = res.records
  })
}

/**
 * 检查申请单分页
 * @param val
 */
const handleCurrentChange = (val) => {
  jianChaShuJu.value.currentPage = val
  dianJiChaXunHuanZheJianCha(jianChaShuJu.value.total)
}

/**
 * 点击查看检查申请单详情
 * @param row 行数据
 */
const dianJiaJianChaXiangQing = (row) => {
  huoQuShengQingXiangQing(row.reqNo).then((res) => {
    daYingJianChaRef.value.fillData(res)
    mainTabs.value = 0
  })

  queryCheckTextResults(row.inpatientNo, row.reqNo).then((res) => {
    res.row = row
    jianChaJieGuoRef.value.fillData(res).then(() => {
      mainTabs.value = 1
    })
  }).catch((e) => {
    jianChaJieGuoRef.value.fillData({
      record: {}, row: {}
    })
  })


}


// 搜索临床诊断
const diagnosis = ref([])
const searchDiagnostics = (val) => {
  diagnosisInOurHospital(val).then((res) => {
    diagnosis.value = res
  })
}

// 保存模板
const saveTemplateRef = ref()
const saveTemplate = () => {
  saveTemplateRef.value.openOrClose()
}

// 保存数据
const saveData = () => {
  if (youWuXuanZheHuanZhe()) return
  if (addCheckList.value.length === 0) {
    BizException(ExceptionEnum.LOGICAL_ERROR, '请先选择数据')
  }
  let listCode = []
  addCheckList.value.forEach((item) => {
    listCode.push(item.orderCode + '-00')
  })
  yaoPinXiangMuPiPeiYiBao(listCode).then((res) => {
    if (stringNotBlank(res)) {
      cuoWuXinXi.value = res
      ElMessageBox.confirm(res, '提示', {
        type: 'warning',
        dangerouslyUseHTMLString: true,
      })
          .then(() => {
            baoCunShuJu()
          })
          .catch(() => {
          })
    } else {
      baoCunShuJu()
    }
  })
}

function baoCunShuJu() {
  ElMessageBox.confirm('确定要保存这些数据吗？', '提示', {
    type: 'warning',
  }).then(() => {
    let data = huanZheXinXi.value
    data.list = addCheckList.value
    data.reqType = 3
    baoCunJianYanJianCha(data)
        .then((res) => {
          addCheckList.value = []
          dianJiChaXunHuanZheJianCha(0)
          mainTabs.value = 0
          asideTabs.value = 1
        })
  }).catch(() => {
  })
}

// 查询患者的检查项目名称
const querySearchAsync = (val, cb) => {
  if (youWuXuanZheHuanZhe()) return
  huoQuJianYanJianChaMing(val, huanZheXinXi.value.inpatientNo, huanZheXinXi.value.admissTimes, huanZheXinXi.value.bedNo, '3').then((res) => {
    cb(res)
  })
}

// 编辑器弹窗
const editor = ref({
  dialog: false,
  data: {},
  index: -1
})
const openTheEditPopUpWindow = (index) => {
  editor.value.index = index
  editor.value.dialog = true
  editor.value.data = addCheckList.value[index]
}
const deleteRequest = (index) => {
  addCheckList.value.splice(index, 1)
}

const searchAdd = (data) => {
  let temp = {
    execDept: data.execUnit,
    execDeptName: data.execUnitName,
    orderCode: data.code,
    orderName: data.name,
  }
  addJcCheck(temp)
}

onActivated(() => {
  dianJiChaXunHuanZheJianCha(0)
})


watch(
    () => huanZheXinXi.value,
    () => {
      dianJiChaXunHuanZheJianCha(0)
    }
)

</script>

<style scoped>
:deep(.el-table .success-row) {
  background: rgba(71, 123, 220, 0.69);
}
</style>
