<template>
  <page-layer>
    <template #header>
      <el-date-picker
          v-model="dateRange"
          :shortcuts="shortcuts"
          end-placeholder="结束日期"
          range-separator="至"
          start-placeholder="开始日期"
          style="width: 220px"
          type="daterange"
      />
      &nbsp;&nbsp;病房：
      <el-select v-model="queryParam.ward" clearable filterable style="width: 120px">
        <el-option v-for="item in wardList" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      &nbsp;&nbsp;住院号：
      <el-input v-model="queryParam.patNo" clearable style="width: 100px"></el-input>
      &nbsp;&nbsp;状态：
      <el-select v-model="queryParam.status" style="width: 80px">
        <el-option v-for="item in statusList" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>

      <el-divider direction="vertical" />
      <el-checkbox v-model="queryParam.jzFlag">急诊</el-checkbox>
      <el-divider direction="vertical" />
      <el-button icon="Search" type="primary" @click="clickQuery">查询</el-button>
    </template>
    <template #main>
      <el-tag effect="dark" size="small" type="danger">急诊:{{ emergencyCount }}条</el-tag>
      <el-tag effect="dark" size="small">普通:{{ surgeryList.length - emergencyCount }}条</el-tag>
      <el-table :data="surgeryList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                :height="window.h - 60" border :row-class-name="differChargedRows"
                header-cell-class-name="cell-border" cell-class-name="cell-border">
        <el-table-column label="手术编号" prop="recordId" width="60">
          <template #default="scope">
            <el-tag :type="scope.row.urgentClinicFlag === '1' ? 'danger' : ''" effect="dark" @click="clickToModifyTime(scope.row)">
              {{ scope.row.recordId }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="日期" prop="opDatetime"></el-table-column>
        <el-table-column label="送出时间" prop="applyDate"></el-table-column>
        <el-table-column label="手术间" prop="roomName" width="80">
          <template #default="scope">
            <el-select v-model="scope.row.roomCode" @focus="handleSelectionFocus(scope.row, 'roomCode')"
                       @change="(roomCode) => handleSelectionChange(scope.row.recordId, 'room_code', roomCode)">
              <el-option v-for="item in allRooms" :value="item.code" :label="item.name" :disabled="item.statusFlag === 2"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="病房" prop="wardName"></el-table-column>
        <el-table-column label="床号" prop="bedNo" width="45"></el-table-column>
        <el-table-column label="住院号" prop="inpatientNo" width="60"></el-table-column>
        <el-table-column label="姓名" prop="patientName" width="60"></el-table-column>
        <el-table-column label="年龄" prop="age" width="45"></el-table-column>
        <el-table-column label="性别" prop="sex" width="45"></el-table-column>
        <el-table-column label="手术名称" prop="opName"></el-table-column>
        <el-table-column label="麻醉方式" prop="hocusName" width="60"></el-table-column>
        <el-table-column label="麻醉医生" prop="doctorMzYsName" width="60"></el-table-column>
        <el-table-column label="手术医生" width="60">
          <template #default="scope">
            <div style="width: 100%; min-height: 30px;" @click="beforeSearch(scope.row)">{{ scope.row.doctorZdName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="器械护士" width="60">
          <template #default="scope">
            <el-select v-model="scope.row.nurseQx" filterable @focus="handleSelectionFocus(scope.row, 'nurseQx')"
                       @change="(nurseQx) => handleSelectionChange(scope.row.recordId, 'nurse_qx', nurseQx)">
              <el-option v-for="item in allStaffs" :value="item.code" :label="item.name"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="巡回护士" width="60">
          <template #default="scope">
            <el-select v-model="scope.row.nurseXh" filterable @focus="handleSelectionFocus(scope.row, 'nurseXh')"
                       @change="(nurseXh) => handleSelectionChange(scope.row.recordId, 'nurse_xh', nurseXh)">
              <el-option v-for="item in allStaffs" :value="item.code" :label="item.name"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="申请医生" prop="applyDocName" width="60"></el-table-column>
        <el-table-column label="诊断" prop="diagBeforeOp"></el-table-column>
        <el-table-column label="分类" width="70">
          <template #default="scope">
            <el-select v-model="scope.row.urgentClinicFlag">
              <el-option label="普通" value="0"></el-option>
              <el-option label="急诊" value="1"></el-option>
              <el-option label="择期" value="2"></el-option>
              <el-option label="限期" value="3"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="手术班次" width="70">
          <template #default="scope">
            <el-select v-model="scope.row.ssbc">
              <el-option label="正常" value="1"></el-option>
              <el-option label="加班" value="2"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="级别" width="95">
          <template #default="scope">
            <el-select v-model="scope.row.opScale">
              <el-option label="一级手术" value="4"></el-option>
              <el-option label="二级手术" value="3"></el-option>
              <el-option label="三级手术" value="2"></el-option>
              <el-option label="四级手术" value="1"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="体外标志">
          <template #default="scope">
            <el-select v-model="scope.row.twFlag" @focus="handleSelectionFocus(scope.row, 'twFlag')"
                       @change="(twFlag) => handleSelectionChange(scope.row.recordId, 'tw_flag', twFlag)">
              <el-option label="否" value="0"></el-option>
              <el-option label="是" value="1"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="手术台次" prop="sstc"></el-table-column>
        <el-table-column label="备注" prop="remark"></el-table-column>
        <el-table-column label="手术开始时间" prop="opStartDate"></el-table-column>
        <el-table-column label="手术结束时间" prop="opEndDate"></el-table-column>
        <el-table-column label="麻醉开始时间" prop="anstStartDate"></el-table-column>
        <el-table-column label="麻醉结束时间" prop="anstEndDate"></el-table-column>
        <el-table-column fixed="right" label="操作" width="110">
          <template #default="scope">
            <el-button link type="danger" icon="Delete" @click.prevent="beforeCancelSurgery(scope.row)">取消</el-button>
            <el-button link type="primary" icon="Document" @click.prevent="doctorAdvise(scope.row)" style="margin-left: 0">医嘱</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="surgeryList.length"
          layout="total,prev, pager, next"
          @current-change="handleCurrentChange"
      ></el-pagination>
    </template>
  </page-layer>
  <search v-if="showSearch" :title="titleOfSearch" target="physician" show-emp-dept @close="showSearch = false" @click-item="handleClickSearchResult"></search>
</template>

<script name="SurgeryArrangement" setup>
import {
  getDicList,
  huoQuShouShuAnPaiXinXi,
  cancelSurgery,
  updateArrangement
} from '@/api/surgical-management/surgery-arrangement'
import { shortcuts } from '@/data/shortcuts.js'
import { getDateRangeFormatDate, getDateRangeFormatDateTime } from '@/utils/date'
import { listIsBlank, stringIsBlank, stringNotBlank } from '@/utils/blank-utils'
import store from '@/store'
import {ElMessage, ElMessageBox} from 'element-plus'
import PageLayer from '@/layout/PageLayer.vue'
import Search from '@/components/search/Index.vue'
import router from '@/router'

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

let currentPage = $ref(1)
let pageSize = $ref(30)
let emergencyCount = $ref(0)

let wardList = $ref([])
let allRooms = $ref([])
let allStaffs = $ref([])
let statusList = $ref([
  { code: '0', name: '全部'},
  { code: '1', name: '申请' },
  { code: '2', name: '安排' },
  { code: '3', name: '确认' },
  { code: 'd', name: '取消' },
])
let dateRange = $ref([shortcuts[0].value[0], shortcuts[0].value[1]])
let queryParam = $ref({
  ward: '',
  patNo: '',
  status: '0',
  startTime: '',
  endTime: '',
  jzFlag: false,
})

let surgeryList = $ref([])

const clickQuery = () => {
  if (listIsBlank(dateRange)) {
    ElMessage.error('请先输入日期')
    return
  }
  let dateS = getDateRangeFormatDate(dateRange)
  queryParam.startTime = dateS.startTime
  queryParam.endTime = dateS.endTime
  huoQuShouShuAnPaiXinXi(queryParam).then((res) => {
    surgeryList = res
    emergencyCount = 0
    surgeryList.forEach((item) => {
      if (stringNotBlank(item.urgentClinicFlag)) {
        if (item.urgentClinicFlag === '1') {
          emergencyCount++
        }
      }
    })
  })
}

const handleCurrentChange = (val) => {
  currentPage = val
}

const differChargedRows = ({ row }) => {
  if (row.chargeSum && row.chargeSum > 0) {
    return 'charged-row'
  }
}

const beforeCancelSurgery = (row) => {
  if (row.status === '3') {
    ElMessage({
      message: '已完成的手术不可取消。',
      type: 'error',
      duration: 2500,
      showClose: true
    })
    return
  }
  ElMessageBox.confirm("是否确认取消该手术？", "提示", {
    type: 'warning'
  }).then(() => {
    cancelSurgery(row.recordId).then(res => {
      ElMessage({
        message: res,
        type: 'success',
        duration: 2500,
        showClose: true
      })
    })
  })
}

let showSearch = $ref(false)
let titleOfSearch = $ref('')
let currentRow = $ref({})
let currentKey = $ref('')
const beforeSearch = (row) => {
  currentRow = row
  currentKey = 'doctor_zd'
  titleOfSearch = '手术医生';
  showSearch = true
}
const handleClickSearchResult = (item) => {
  showSearch = false
  handleArrangementChange(currentRow.recordId, currentKey, item.code).then(() => {
    currentRow.doctorZd = item.code
    currentRow.doctorZdName = item.name
  })
}

const oldSelection = reactive({
  key: '',
  val: ''
})
const handleSelectionFocus = (row, key) => {
  currentRow = row
  oldSelection.key = key
  oldSelection.val = row[key]
}

const handleSelectionChange = (orderId, key, value) => {
  handleArrangementChange(orderId, key, value).then(() => {
  }).catch(() => {
    currentRow[oldSelection.key] = oldSelection.val
  })
}

const handleArrangementChange = (orderId, key, value) => {
  return new Promise((resolve, reject) => {
    updateArrangement(orderId, key, value).then(() => {
      resolve()
    }).catch(() => {
      reject()
    })
  })
}

const doctorAdvise = (row) => {
  router.push({
    name: 'yiZhuLuRu',
    params: {
      inpatientNo: row.inpatientNo,
      admissTimes: row.admissTimes
    }
  })
}

onMounted(() => {
  getDicList().then((res) => {
    wardList = res.allWards
    allRooms = res.allRooms
    allStaffs = res.allStaffs
  })
  clickQuery()
})
</script>

<style scoped>
:deep(.el-table tbody tr:hover>td) {
  background-color: unset !important;
}

:deep(.el-table .el-table-fixed-column--right .cell) {
  width: 100%;
  background: white;
  position: absolute;
  top: 0;
  bottom: 0;
  display: flex;
  align-items: center;
}

:deep(.el-table .charged-row) {
  background: rgba(142, 252, 142, 0.8);
}

:deep(.el-table .cell-border) {
  border: 1px solid #555;
  color: black;
  padding: 0;
}

:deep(.el-input__inner) {
  color: black !important;
}

:deep(.el-input--small .el-input__wrapper) {
  padding: 1px 4px;
}

:deep(.el-table .el-input__suffix) {
  display: none;
}
</style>
