<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>
      <el-button icon="Printer" type="danger" @click="clickPrint">打印</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="windowSize.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="55">
          <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="日期" width="125">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">{{ scope.row.opDatetime }}</div>
            <el-input v-else v-model="scope.row.opDatetime" readonly @click="beforeChargeOpTime(scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="送出时间" prop="applyDate" width="118"></el-table-column>
        <el-table-column label="手术间" prop="roomName" width="50">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">{{ scope.row.roomName }}</div>
            <el-select v-else v-model="scope.row.roomCode" @focus="handleSelectionFocus(scope.row, 'roomCode')"
                       @change="(roomCode) => handleSelectionChange(scope.row.recordId, 'room_code', roomCode)"
                       placeholder=" ">
              <el-option v-for="item in allRooms" :value="item.code" :label="item.name"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="病房" prop="wardName" width="78"></el-table-column>
        <el-table-column label="床号" prop="bedNo" width="30"></el-table-column>
        <el-table-column label="住院号" prop="inpatientNo" width="60"></el-table-column>
        <el-table-column label="姓名" prop="patientName" width="50"></el-table-column>
        <el-table-column label="年龄" prop="age" width="33"></el-table-column>
        <el-table-column label="性别" prop="sex" width="30"></el-table-column>
        <el-table-column label="手术名称" prop="opName" width="183"></el-table-column>
        <el-table-column label="麻醉方式" prop="hocusName" width="165"></el-table-column>
        <el-table-column label="麻醉医生" prop="doctorMzYsName" width="55"></el-table-column>
        <el-table-column label="手术医生" width="55">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">{{ scope.row.doctorZdName }}</div>
            <el-input v-else v-model="scope.row.doctorZdName" @click="beforeSearch(scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="器械护士" width="55">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">{{ scope.row.nurseQxName }}</div>
            <el-select v-else v-model="scope.row.nurseQx" filterable @focus="handleSelectionFocus(scope.row, 'nurseQx')"
                       @change="(nurseQx) => handleSelectionChange(scope.row.recordId, 'nurse_qx', nurseQx)"
                       placeholder=" ">
              <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="55">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">{{ scope.row.nurseXhName }}</div>
            <el-select v-else v-model="scope.row.nurseXh" filterable @focus="handleSelectionFocus(scope.row, 'nurseXh')"
                       @change="(nurseXh) => handleSelectionChange(scope.row.recordId, 'nurse_xh', nurseXh)"
                       placeholder=" ">
              <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="55"></el-table-column>
        <el-table-column label="诊断" prop="diagBeforeOp" width="135"></el-table-column>
        <el-table-column label="分类" width="45">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">{{ filterUrgentClinicFlag(scope.row.urgentClinicFlag) }}</div>
            <el-select v-else v-model="scope.row.urgentClinicFlag" placeholder=" ">
              <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="45">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">{{ filterSsbc(scope.row.ssbc) }}</div>
            <el-select v-else v-model="scope.row.ssbc" placeholder=" ">
              <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="66">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">{{ filterOpScale(scope.row.opScale) }}</div>
            <el-select v-else v-model="scope.row.opScale" placeholder=" " >
              <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="体外" width="45">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">{{ filterTwFlag(scope.row.twFlag) }}</div>
            <el-select v-else v-model="scope.row.twFlag" @focus="handleSelectionFocus(scope.row, 'twFlag')"
                       @change="(twFlag) => handleSelectionChange(scope.row.recordId, 'tw_flag', twFlag)"
                       placeholder=" ">
            <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" width="35"></el-table-column>
        <el-table-column label="备注">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'" :title="scope.row.remark">{{ scope.row.remark }}</div>
            <el-input v-else v-model="scope.row.remark" readonly @click="inputRemark(scope.row)" :title="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="手术开始时间" prop="opStartDate" width="118"></el-table-column>
        <el-table-column label="手术结束时间" prop="opEndDate" width="118"></el-table-column>
        <el-table-column label="麻醉开始时间" prop="anstStartDate" width="118"></el-table-column>
        <el-table-column label="麻醉结束时间" prop="anstEndDate" width="118"></el-table-column>
        <el-table-column fixed="right" label="操作" width="110">
          <template #default="scope">
            <el-button v-if="scope.row.status === 'd'" link type="primary" icon="Refresh" @click.prevent="changeSurgeryStatus(scope.row, '1')">恢复</el-button>
            <span v-else>
              <el-button link :type="scope.row.arrangementExecuted === 0 ? 'info' : 'primary'"
                         :icon="scope.row.arrangementExecuted === 0 ? 'Close' : 'Check'"
                         @click.prevent="changeArrangementExecuted(scope.row)">
                {{ scope.row.arrangementExecuted === 0 ? '未接' : '已接'}}
              </el-button>
              <el-button v-if="scope.row.status !== '3' && scope.row.arrangementExecuted === 0"
                         link type="danger" icon="Delete"
                         @click.prevent="changeSurgeryStatus(scope.row, 'd')">
                取消
              </el-button>
            </span>
          </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>
  <div id="printArea" style="position: fixed; background: white; color: black; opacity: 0">
    <div style="width: 100%; margin-top: 12px; text-align: center; height: 36px; line-height: 36px; font-size: 22px; font-weight: bold">手 术 安 排 表（{{ nowdate }}）</div>
    <div style="width: 100%; padding-left: 30px; height: 32px">打印时间：{{ nowdatetime }}</div>
    <div style="padding-left: 30px">
      <div style="display: flex;align-items: center;justify-content: center;font-weight: bold;font-size:12px;height: 30px;border-bottom: 1px solid black">
        <div style="width: 170px;">手术日期</div>
        <div style="width: 90px;">手术间</div>
        <div style="width: 160px;">病房 - 床号</div>
        <div style="width: 80px;">住院号</div>
        <div style="width: 160px;">年龄 - 性别 - 姓名</div>
        <div style="width: 260px;">手术名称</div>
        <div style="width: 170px; margin-left: 16px">麻醉方式</div>
        <div style="width: 80px;">麻醉医生</div>
        <div style="width: 80px;">手术医生</div>
        <div style="width: 80px;">器械护士</div>
        <div style="width: 80px;">巡回护士</div>
      </div>
      <div style="height: 8px"></div>
      <div v-for="item in surgeryListForPrint" style="display: flex;align-items: center;justify-content: center;font-size: 12px; height: 32px; border-bottom: 1px solid black">
        <div style="width: 170px">{{ item.opDatetime }}</div>
        <div style="width: 90px;">{{ item.roomName }}</div>
        <div style="width: 160px;">{{ item.wardName }} - {{ item.bedNo }}床</div>
        <div style="width: 80px;">{{ item.inpatientNo }}</div>
        <div style="width: 160px;">{{ item.age }} - {{ item.sex }} - {{ item.patientName }}</div>
        <div style="width: 260px;">{{ item.opName }}</div>
        <div style="width: 170px; margin-left: 16px">{{ item.hocusName }}</div>
        <div style="width: 80px;">{{ item.doctorMzYsName }}</div>
        <div style="width: 80px;">{{ item.doctorZdName }}</div>
        <div style="width: 80px;">{{ item.nurseQxName }}</div>
        <div style="width: 80px;">{{ item.nurseXhName }}</div>
      </div>
    </div>
  </div>
</template>

<script name="SurgeryArrangement" setup>
import {
  getDicList,
  huoQuShouShuAnPaiXinXi,
  updateSurgeryStatus,
  updateArrangement
} from '@/api/surgical-management/surgery-arrangement'
import { shortcuts } from '@/data/shortcuts.js'
import {formatDate, formatDatetime, getDateRangeFormatDate, getDateRangeFormatDateTime, getDatetime} 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'
import { initLodop, getLodop } from '@/utils/c-lodop'
import {refundOrder} from "@/api/wxpay-refund";

const windowSize = 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([])

let surgeryListForPrint = computed(() => {
  return surgeryList.filter(item => {
    return item.status !== 'd'
  })
})

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'
  }
  if (row.status === 'd') {
    return 'canceled-row'
  }
}

const surgeryExecuted = (row) => {
  if (row.status === '3') {
    ElMessage({
      message: '已完成的手术不可取消。',
      type: 'error',
      duration: 2500,
      showClose: true
    })
    return true
  }
  return false
}

const arrangementExecuted = (row) => {
  if (row.arrangementExecuted === 1) {
    ElMessage({
      message: '已接的手术不可取消。',
      type: 'error',
      duration: 2500,
      showClose: true
    })
    return true
  }
  return false
}

const changeSurgeryStatus = (row, status) => {
  if (!surgeryExecuted(row) && !arrangementExecuted(row)) {
    currentRow.value = row;
    updateSurgeryStatus(row.recordId, status).then(() => {
      currentRow.value.status = status
    })
  }
}

const changeArrangementExecuted = (row) => {
  currentRow.value = row
  const targetVal = row.arrangementExecuted === 0 ? 1 : 0
  updateArrangement(row.recordId, 'arrangement_executed', targetVal).then(() => {
    currentRow.value.arrangementExecuted = targetVal
  })
}

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 beforeChargeOpTime = (row) => {
  ElMessageBox.prompt('请输入手术时间：', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: row.opDatetime,
    inputPattern: /^[1-9][0-9][0-9][0-9]-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]) (0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])$/,
    inputErrorMessage: '请输入正确的时间格式',
  }).then(({value}) => {
    handleArrangementChange(row.recordId, 'op_datetime', value).then(() => {
      row.opDatetime = value
    })
  }).catch(() => {})
}

const inputRemark = (row) => {
  ElMessageBox.prompt('请输入备注：', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: row.remark,
  }).then(({value}) => {
    let remark = value ? value : ''
    handleArrangementChange(row.recordId, 'remark', remark).then(() => {
      row.remark = value
    })
  }).catch(() => {})
}

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
    }
  })
}

const filterUrgentClinicFlag = (flag) => {
  switch (flag) {
    case '0':
      return '普通';
    case '1':
      return '急诊';
    case '2':
      return '择期';
    case '3':
      return '限期'
    default:
      return '';
  }
}

const filterSsbc = (ssbc) => {
  switch (ssbc) {
    case '1':
      return '正常';
    case '2':
      return '加班';
    default:
      return ''
  }
}

const filterTwFlag = (flag) => {
  switch (flag) {
    case '0':
      return '否';
    case '1':
      return '是';
    default:
      return ''
  }
}

const filterOpScale = (scale) => {
  switch (scale) {
    case '1':
      return '四级手术';
    case '2':
      return '三级手术';
    case '3':
      return '二级手术'
    case '4':
      return '一级手术';
    default:
      return '';
  }
}

const nowdate = ref('')
const nowdatetime = ref('')
const clickPrint = () => {
  nowdate.value = formatDate(new Date())
  nowdatetime.value = formatDatetime(new Date())
  LODOP = getLodop()
  let pagePrint = '<body>' + document.getElementById('printArea').innerHTML + '</body>'
  LODOP.PRINT_INIT('surgeryArrangement')
  LODOP.SET_PRINT_PAGESIZE(2, '210mm', '297mm', '')
  LODOP.SET_PRINT_MODE('RESELECT_PRINTER', true)
  LODOP.SET_PRINT_MODE('PRINT_PAGE_PERCENT', 'Full-Width')
  LODOP.ADD_PRINT_HTM('2mm', '2mm', '100%', '100%', pagePrint)
  LODOP.SET_SHOW_MODE("LANDSCAPE_DEFROTATED", 1)
  LODOP.PREVIEW()
}

onMounted(() => {
  initLodop()
  nowdate.value = formatDate(new Date())
  nowdatetime.value = formatDatetime(new Date())
  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 .canceled-row *) {
  color: red ;
}

:deep(.el-tag .el-tag__content) {
  color: white;
}

: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;
  background-color: transparent;
}

:deep(.el-table .el-input__suffix) {
  display: none;
}

:deep(.el-table .cell) {
  line-height: 16px;
  padding-left: 2px;
  padding-right: 2px;
}
</style>
