<template>
  <div class="layout_container surgery-arrangement">
    <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>
      <el-button
          icon="PieChart"
          type="success"
          @click="showSurgeryStatistics"
        >
        统计
      </el-button>
      <el-select
          v-model="displayRoom"
          style="width: 120px;
          margin-left: 12px"
          @change="handleChangeDisplay"
      >
        <el-option value="ALL" label="查看全部" />
        <el-option value="NORMAL" label="只看普通手术间" />
        <el-option value="OTHER" label="只看其他手术间" />
      </el-select>
    </header>
    <div class="layout_main layout_el-table">
      <div>
        <el-tag
            effect="dark"
            size="small"
            type="danger"
          >
          急诊:{{ emergencyCount }}条
        </el-tag>
        <el-tag
            effect="dark"
            size="small"
          >
          普通:{{ cptSrgLst.length - emergencyCount }}条
        </el-tag>
      </div>
      <el-table
        :data="
          cptSrgLst.slice(
            (currentPage - 1) * pageSize,
            currentPage * pageSize
          )
        "
        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' : 'primary'"
              effect="dark"
            >
              {{ 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=" "
              class="el-select_no-suffix"
            >
              <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="deptName"
          width="78"
        ></el-table-column>
        <el-table-column label="台次" prop="sstc" width="40">
          <template #default="{ row }">
            <div v-if="row.status === 'd'">{{ row.sstc }}</div>
            <el-select
                v-else
                v-model="row.sstc"
                @focus="handleSelectionFocus(row, 'sstc')"
                @change="
                sstc => handleSelectionChange(row.recordId, 'sstc', sstc)
              "
                placeholder=" "
                clearable
                class="el-select_no-suffix"
            >
              <el-option value="" label="清空"></el-option>
              <el-option v-for="n in 12" :value="n" :label="n"></el-option>
            </el-select>
          </template>
        </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="姓名" width="50">
          <template #default="scope">
            <div style="height: 32px; line-height: 32px">
              {{ scope.row.patientName }}
            </div>
          </template>
        </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="60">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">
              {{ scope.row.doctorMzYsName }}
            </div>
            <el-select
              v-else
              v-model="scope.row.doctorMzYs"
              filterable
              @focus="handleSelectionFocus(scope.row, 'doctorMzYs')"
              @change="
                doctorMzYs =>
                  handleSelectionChange(
                    scope.row.recordId,
                    'doctor_mz_ys',
                    doctorMzYs
                  )
              "
              placeholder=" "
              class="el-select_no-suffix"
            >
              <el-option
                v-for="item in aneStaffs"
                :value="item.code"
                :label="item.name"
                :key="'doctor_mz_ys-' + item.code"
              ></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.doctorZdName }}
            </div>
            <el-input
              v-else
              v-model="scope.row.doctorZdName"
              @click="beforeSearch(scope.row, 'doctor_zd')"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column label="一助" width="55">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">
              {{ scope.row.doctor1Name }}
            </div>
            <el-input
                v-else
                v-model="scope.row.doctor1Name"
                @click="beforeSearch(scope.row, 'doctor_1')"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="二助" width="55">
          <template #default="scope">
            <div v-if="scope.row.status === 'd'">
              {{ scope.row.doctor2Name }}
            </div>
            <el-input
                v-else
                v-model="scope.row.doctor2Name"
                @click="beforeSearch(scope.row, 'doctor_2')"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column label="器械护士" width="60">
          <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=" "
              class="el-select_no-suffix"
            >
              <el-option
                v-for="item in surStaffs"
                :value="item.code"
                :label="item.name"
                :key="'nurse_qx-' + item.code"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="巡回护士" width="60">
          <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=" "
              class="el-select_no-suffix"
            >
              <el-option
                v-for="item in surStaffs"
                :value="item.code"
                :label="item.name"
                :key="'nurse_xh-' + item.code"
              ></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="50">
          <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=" "
              @focus="handleSelectionFocus(scope.row, 'urgentClinicFlag')"
              @change="
                urgentClinicFlag =>
                  handleSelectionChange(
                    scope.row.recordId,
                    'urgent_clinic_flag',
                    urgentClinicFlag
                  )
              "
              class="el-select_no-suffix"
            >
              <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="50">
          <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=" "
              class="el-select_no-suffix"
            >
              <el-option label="正常" value="0"></el-option>
              <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="70">
          <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=" "
              class="el-select_no-suffix"
            >
              <el-option label="一级手术" value="1"></el-option>
              <el-option label="二级手术" value="2"></el-option>
              <el-option label="三级手术" value="3"></el-option>
              <el-option label="四级手术" value="4"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="体外" width="40">
          <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=" "
              class="el-select_no-suffix"
            >
              <el-option label="否" value="0"></el-option>
              <el-option label="是" value="1"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="术前访视">
          <template #default="scope">
            <div
              v-if="scope.row.status === 'd'"
              :title="scope.row.preoperativeVisit"
            >
              {{ scope.row.preoperativeVisit }}
            </div>
            <el-input
              v-else
              v-model="scope.row.preoperativeVisit"
              readonly
              @click="inputContent(scope.row, 'preoperativeVisit')"
              :title="scope.row.preoperativeVisit"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="术前准备">
          <template #default="scope">
            <div
              v-if="scope.row.status === 'd'"
              :title="scope.row.preoperativePreparation"
            >
              {{ scope.row.preoperativePreparation }}
            </div>
            <el-input
              v-else
              v-model="scope.row.preoperativePreparation"
              readonly
              @click="inputContent(scope.row, 'preoperativePreparation')"
              :title="scope.row.preoperativePreparation"
            ></el-input>
          </template>
        </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="inputContent(scope.row, 'remark')"
              :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="100">
          <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="cptSrgLst.length"
        layout="total,prev, pager, next"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
  <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.deptName }} - {{ 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>

  <el-dialog v-model="surgeryStatisticsVisible" title="手术统计" width="70%">
    <div style="display: flex; align-items: center">
      <div style="width: 220px">
        <el-date-picker
          v-model="statisticsDateRange"
          :shortcuts="shortcuts"
          end-placeholder="结束日期"
          range-separator="至"
          start-placeholder="开始日期"
          style="width: 200px"
          :clearable="false"
          type="daterange"
        />
      </div>
      <el-select
        v-model="statisticsRequest.statisticsLabel"
        style="margin-left: 12px; width: 100px"
      >
        <el-option label="按科室" value="BY_DEPARTMENT"></el-option>
        <el-option label="按手术" value="BY_SURGERY"></el-option>
        <el-option label="按级别" value="BY_LEVEL"></el-option>
      </el-select>
      <el-divider direction="vertical"></el-divider>
      <el-button icon="Search" @click="executeQueryStatistics">查询</el-button>
    </div>

    <div style="height: 500px" class="surgery-arrangement">
      <div
        style="
          height: 460px;
          margin-top: 20px;
          padding: 8px 0;
          overflow-y: scroll;
          background-color: #e0e0e0;
        "
      >
        <div v-for="(val, key) in surgeryStatistics.surgeryMap">
          <div
            style="
              display: flex;
              width: 330px;
              padding-left: 12px;
              line-height: 32px;
              border-bottom: 1px solid white;
            "
          >
            <div style="width: 32px">
              <div class="show-detail-icon" @click="showStatisticsDetail(key)">
                >
              </div>
            </div>
            <div style="width: 260px; padding-left: 8px; text-align: left">
              {{ key }}
            </div>
            <div style="width: 40px; text-align: center">
              <span style="font-weight: bold; color: black">{{
                val.length
              }}</span
              >台
            </div>
          </div>

          <div
            v-if="currentStatistics.key === key"
            style="background-color: white; padding: 0 12px"
          >
            <el-table :data="currentStatistics.list">
              <el-table-column prop="deptName" label="手术科室" />
              <el-table-column prop="recordId" label="手术单号" />
              <el-table-column prop="patientName" label="患者姓名" />
              <el-table-column prop="inpatientNo" label="住院号" />
              <el-table-column prop="applyDocName" label="申请医生" />
              <el-table-column prop="applyDate" label="申请时间" />
              <el-table-column prop="opDatetime" label="手术时间" />
              <el-table-column prop="opCode" label="手术编码" />
              <el-table-column prop="opName" label="手术名称" />
              <el-table-column prop="opScaleName" label="手术级别" />
              <el-table-column prop="urgentClinicName" label="手术分类" />
              <el-table-column prop="statusName" label="手术状态" />
              <el-table-column prop="doctorZdName" label="主刀医生" />
              <el-table-column prop="doctor1Name" label="一助" />
              <el-table-column prop="doctor2Name" label="二助" />
              <el-table-column prop="doctorMzName" label="麻醉医生" />
              <el-table-column prop="hocusName" label="麻醉方式" />
              <el-table-column prop="nurseXhName" label="巡回护士" />
              <el-table-column prop="nurseQxName" label="器械护士" />
            </el-table>
          </div>
        </div>
      </div>
      <div
        style="margin-top: 15px; font-weight: bold"
        v-show="surgeryStatistics.total"
      >
        总计：{{ surgeryStatistics.total }}台
      </div>
    </div>
  </el-dialog>
</template>

<script name="SurgeryArrangement" setup>
import {
  getDicList,
  notifyDoctor,
  queryStatistics,
  selectSurgeryArrangements,
  updateArrangement,
  updateSurgeryStatus,
} from "@/api/surgical-management/surgery-arrangement";
import {shortcuts} from "@/data/shortcuts.js";
import {formatDate, formatDatetime, getDateRangeFormatDate,} from "@/utils/date";
import {listIsBlank, stringNotBlank} from "@/utils/blank-utils";
import {ElMessage, ElMessageBox} from "element-plus";
import Search from "@/components/search/Index.vue";
import router from "@/router";
import {getLodop, initLodop} from "@/utils/c-lodop";
import {xcMessage} from "@/utils/xiaochan-element-plus";

const currentPage = ref(1);
const pageSize = ref(30);
const emergencyCount = ref(0);

const wardList = ref([]);
const allRooms = ref([]);
const surStaffs = ref([]);
const aneStaffs = ref([]);
let statusList = reactive([
  { code: "0", name: "全部" },
  { code: "1", name: "申请" },
  { code: "2", name: "安排" },
  { code: "3", name: "确认" },
  { code: "d", name: "取消" },
]);
const dateRange = ref([shortcuts[0].value[0], shortcuts[0].value[1]]);

let queryParam = reactive({
  ward: "",
  patNo: "",
  status: "0",
  startTime: "",
  endTime: "",
  jzFlag: false,
});

const surgeryList = ref([]);
const cptSrgLst = ref([])
const displayRoom = ref('ALL')

function handleChangeDisplay(val) {
  if (val === "ALL") {
    cptSrgLst.value = surgeryList.value;
  } else if (val === "NORMAL") {
    cptSrgLst.value = surgeryList.value.filter(item => {
      return !item.roomCode || (parseInt(item.roomCode) < 15)
    })
  } else {
    cptSrgLst.value = surgeryList.value.filter(item => {
      return item.roomCode && (parseInt(item.roomCode) >= 15)
    })
  }
  calEmergencyCount(cptSrgLst.value)
}

function calEmergencyCount(list) {
  emergencyCount.value = 0
  list.forEach(item => {
    if (stringNotBlank(item.urgentClinicFlag)) {
      if (item.urgentClinicFlag === "1") {
        emergencyCount.value++;
      }
    }
  });
}

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

const clickQuery = () => {
  if (listIsBlank(dateRange.value)) {
    ElMessage.error("请先输入日期");
    return;
  }
  let dateS = getDateRangeFormatDate(dateRange.value);
  queryParam.startTime = dateS.startTime;
  queryParam.endTime = dateS.endTime;
  selectSurgeryArrangements(queryParam).then(res => {
    surgeryList.value = res;
    handleChangeDisplay(displayRoom.value);
  }).catch(() => {
    surgeryList.value = []
  });
};

const handleCurrentChange = val => {
  currentPage.value = 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;
      if (targetVal === 1) {
        ElMessageBox.confirm("是否向手术医生发送通知？",'提示', {
            type: "warning",
        }).then(() => {
          notifyDoctor(row).then(res2 => {
            xcMessage.success(res2)
          });
        });
      }
    }
  );
};

const showSearch = ref(false);
const titleOfSearch = ref("");
const currentRow = ref({});
const currentKey = ref("");
const beforeSearch = (row, col) => {
  currentRow.value = row;
  currentKey.value = col;
  titleOfSearch.value = "手术医生";
  showSearch.value = true;
};
const handleClickSearchResult = item => {
  showSearch.value = false;
  handleArrangementChange(
    currentRow.value.recordId,
    currentKey.value,
    item.code
  ).then(() => {
    switch (currentKey.value) {
      case 'doctor_zd':
        currentRow.value.doctorZd = item.code;
        currentRow.value.doctorZdName = item.name;
        break;
      case 'doctor_1':
        currentRow.value.doctor1 = item.code;
        currentRow.value.doctor1Name = item.name;
        break;
      case 'doctor_2':
        currentRow.value.doctor2 = item.code;
        currentRow.value.doctor2Name = item.name;
        break;
    }
  });
};

const oldSelection = reactive({
  column: "",
  value: "",
});
const handleSelectionFocus = (row, column) => {
  currentRow.value = row;
  oldSelection.column = column;
  oldSelection.value = row[column];
};

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

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 filterPromptMessage = key => {
  switch (key) {
    case "remark":
      return { title: "请输入备注", column: "remark" };
    case "preoperativeVisit":
      return { title: "请输入术前访视", column: "preoperative_visit" };
    case "preoperativePreparation":
      return {
        title: "请输入术前准备完善情况",
        column: "preoperative_preparation",
      };
  }
};

const inputContent = (row, key) => {
  let message = filterPromptMessage(key);
  ElMessageBox.prompt(message.title, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValue: row[key],
  })
    .then(({ value }) => {
      let inputVal = value ? value : "";
      handleArrangementChange(row.recordId, message.column, inputVal).then(
        () => {
          row[key] = inputVal;
        }
      );
    })
    .catch(() => {});
};

const handleArrangementChange = (orderId, column, value) => {
  return new Promise((resolve, reject) => {
    updateArrangement(orderId, column, 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 "4":
      return "四级手术";
    case "3":
      return "三级手术";
    case "2":
      return "二级手术";
    case "1":
      return "一级手术";
    default:
      return "";
  }
};

const nowdate = ref("");
const nowdatetime = ref("");
const clickPrint = () => {
  nowdate.value = formatDate(new Date());
  nowdatetime.value = formatDatetime(new Date());
  let 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();
};

const statisticsRequest = reactive({
  startDate: null,
  endDate: null,
  statisticsLabel: "BY_DEPARTMENT",
});
const statisticsDateRange = ref([]);
const surgeryStatisticsVisible = ref(false);
const surgeryStatistics = ref([]);

function showSurgeryStatistics() {
  statisticsDateRange.value = [shortcuts[0].value[0], shortcuts[0].value[1]];
  surgeryStatisticsVisible.value = true;
}

function executeQueryStatistics() {
  let temp = getDateRangeFormatDate(statisticsDateRange.value);
  statisticsRequest.startDate = temp.startTime;
  statisticsRequest.endDate = temp.endTime;
  queryStatistics(statisticsRequest).then(res => {
    surgeryStatistics.value = res;
  });
}

const currentStatistics = reactive({
  key: "",
  list: [],
});

function showStatisticsDetail(key) {
  if (key === currentStatistics.key) {
    currentStatistics.key = "";
    currentStatistics.list = [];
    return;
  }
  currentStatistics.key = key;
  currentStatistics.list = surgeryStatistics.value.surgeryMap[key];
}

onMounted(() => {
  initLodop();
  nowdate.value = formatDate(new Date());
  nowdatetime.value = formatDatetime(new Date());
  getDicList().then(res => {
    wardList.value = res.allWards;
    allRooms.value = res.allRooms;
    surStaffs.value = res.surStaffs;
    aneStaffs.value = res.aneStaffs;
  });
  clickQuery();
});
</script>

<style lang="scss">
.surgery-arrangement {
  .el-input__inner {
    color: black !important;
  }

  .el-input--small {
    .el-input__wrapper {
      padding: 1px 4px;
      background-color: transparent;
    }
  }

  .el-table {
    .el-input__suffix {
      display: none;
    }

    .cell {
      line-height: 16px;
      padding-left: 2px;
      padding-right: 2px;
    }

    .cell-border {
      border: 1px solid #555;
      color: black;
      padding: 0;
    }

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

        .el-button {
          margin-left: 2px;

          span {
            margin-left: 0;
          }
        }
      }
    }

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

    .canceled-row * {
      color: red;
    }
  }

  .el-tag {
    .el-tag__content {
      color: white;
    }
  }

  .show-detail-icon {
    width: 24px;
    height: 24px;
    margin-top: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    background-color: white;
    color: #737373;

    &:hover {
      cursor: pointer;
      scale: 1.12;
      background-color: #5b5d5d;
      color: white;
    }
  }
}
</style>
