<template>
  <div style="height: 30px">
    申请时间：
    <el-date-picker
        v-model="dateRange"
        :shortcuts="shortcuts"
        end-placeholder="结束日期"
        placeholder="选择日期"
        range-separator="至"
        size="small"
        start-placeholder="开始日期"
        style="width: 280px"
        type="daterange"
    ></el-date-picker>
    <el-button icon="Search" type="primary" @click="dianJiChaXunShouShu(0)">查询</el-button>
    <el-button icon="Plus" type="success" @click="dianJiXinZhenShouShu">新增</el-button>
    <el-button icon="Check" type="success" @click="clickSave">保存手术</el-button>
    <el-button type="danger" @click="error.dialog = true">打开错误信息</el-button>
  </div>

  <div style="display: flex">
    <div>
      <el-table :data="shouShuShuJu.data"
                :height="getWindowSize.h - (yzHeaderSize + 10)"
                highlight-current-row
                @row-click="dianJiChaKanShouShu">
        <el-table-column label="申请号" prop="recordId" show-overflow-tooltip></el-table-column>
        <el-table-column label="申请号" prop="statusName" show-overflow-tooltip></el-table-column>
        <el-table-column label="项目名称" prop="opName" show-overflow-tooltip></el-table-column>
        <el-table-column label="手术时间" prop="opDatetime" show-overflow-tooltip></el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button icon="Delete" type="danger" @click.stop="dianJiShanChu(scope.row, scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :current-page="shouShuShuJu.currentPage"
          :page-size="shouShuShuJu.pageSize"
          :total="shouShuShuJu.total"
          layout="total,prev, pager, next"
          small
          @current-change="handleCurrentChange">
      </el-pagination>
    </div>
    <div>
      <el-tabs v-model="tabs" closable
               @tab-remove="removeTab">
        <el-tab-pane v-for="(item,index) in operationApplication"
                     :label="tabsName(item.opName,index)"
                     :name="index + 1">
          <bian-ji-shou-shu
              :anesthetic-mode="anestheticMode"
              :data="item"
              :item="index"/>
        </el-tab-pane>
        <el-tab-pane label="手术查看" :name="0">
          <da-ying-shou-shu-sheng-qing-dan
              ref="daYing"
              :height="getWindowSize.h - (yzHeaderSize + 70)"/>
        </el-tab-pane>
      </el-tabs>
      <surgical-error-info :data="error"/>
    </div>
  </div>

</template>

<script setup name="ShouShuShenQing">
import {computed, ref, watch} from 'vue'
import {
  huoQuShouShu,
  huoQuShouShuMingCheng,
  huoQuShouShuShenQingDaYing,
  shanChuShouShu, xinZengShouShuShenQing
} from '@/api/zhu-yuan-yi-sheng/shou-shu-shen-qing'
import {
  huanZheXinXi,
  operationApplication,
  youWuXuanZheHuanZhe, yzHeaderSize
} from '@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng'
import {shortcuts} from '@/data/shortcuts'
import store from '@/store'
import DaYingShouShuShengQingDan from '@/components/zhu-yuan-yi-sheng/shou-shu-shen-qing/DaYingShouShuShengQingDan.vue'
import {stringIsBlank, stringNotBlank} from '@/utils/blank-utils'
import {ElMessageBox} from 'element-plus'
import BianJiShouShu from "@/components/zhu-yuan-yi-sheng/shou-shu-shen-qing/BianJiShouShu";
import {getServerDateApi, maZuiFangShi} from "@/api/public-api";
import SurgicalErrorInfo from "@/components/zhu-yuan-yi-sheng/shou-shu-shen-qing/SurgicalErrorInfo";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import {getWindowSize} from "@/utils/window-size";
import {isDev} from "@/utils/public";

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

const orderName = ref('')
const dateRange = ref([])
const daYing = ref()
const tabs = ref(0)

const shouShuShuJu = ref({
  data: [],
  currentPage: 1,
  pageSize: 20,
  total: 0,
})

const error = ref({
  dialog: false,
  msg: {}
})

/**
 * 点击查询手术
 * @param val
 */
const dianJiChaXunShouShu = (val) => {
  const data = {
    patNo: huanZheXinXi.value.inpatientNo,
    times: huanZheXinXi.value.admissTimes,
    currentPage: shouShuShuJu.value.currentPage,
    pageSize: shouShuShuJu.value.pageSize,
    total: val,
  }
  huoQuShouShu(data).then((res) => {
    if (val === 0) {
      shouShuShuJu.value.total = res.total
    }
    shouShuShuJu.value.data = res.records
  })
}

/**
 * 点击分页
 * @param val
 */
const handleCurrentChange = (val) => {
  shouShuShuJu.value.currentPage = val
  dianJiChaXunShouShu(shouShuShuJu.value.total)
}

const tabsName = (val, index) => {
  if (stringIsBlank(val)) {
    return '添加手术' + index;
  }
  return val
}

const clickSave = async () => {
  if (youWuXuanZheHuanZhe()) return
  let data = huanZheXinXi.value
  data.execDept = store.state.user.info.deptCode
  data.list = operationApplication.value

  try {
    await ElMessageBox.confirm('是否要生成全排斥医嘱？', '提示', {
      type: 'warning',
      confirmButtonText: '生成排斥医嘱',
      cancelButtonText: '生成处置医嘱',
      distinguishCancelAndClose: true
    })
    data.generateRejectedOrders = true
  } catch (e) {
    if (e === 'cancel') {
      data.generateRejectedOrders = false
    } else {
      return
    }
  }

  xinZengShouShuShenQing(data).then((res) => {
    if (res !== null && res.error !== null) {
      error.value.dialog = true
      error.value.msg = res.data
    } else {
      tabs.value = 0
      operationApplication.value = []
    }
  })

}

const removeTab = (targetName) => {
  if (targetName === 0) {
    BizException(ExceptionEnum.MESSAGE_ERROR, '无法删除')
  }
  operationApplication.value.splice(targetName - 1, 1)
  tabs.value = tabs.value - 1
}

const dianJiChaKanShouShu = (row) => {
  huoQuShouShuShenQingDaYing(huanZheXinXi.value.inpatientNo, huanZheXinXi.value.admissTimes, row.recordId).then((res) => {
    daYing.value.data = res
    if (stringNotBlank(res.applyDate)) {
      res.applyDate = res.applyDate.split(' ')[0]
    }
    if (stringNotBlank(res.opDatetime)) {
      res.opDatetime = res.opDatetime.split(' ')[0]
    }
  })
  tabs.value = 0
}

const dianJiShanChu = (row, index) => {
  ElMessageBox.confirm(`您确定要删除【${row.opName}】吗？`, '提示', {})
      .then(() => {
        shanChuShouShu(row.recordId)
        shouShuShuJu.value.data.splice(index, 1)
      })
      .catch(() => {
      })
}

watch(
    () => huanZheXinXi.value,
    () => {
      dianJiChaXunShouShu(0)
    },
    {immediate: true}
)

const dianJiXinZhenShouShu = async () => {
  operationApplication.value.push({
    inpatientNo: huanZheXinXi.value.inpatientNo,
    admissTimes: huanZheXinXi.value.admissTimes,
    opCode: '',
    opName: '添加手术' + operationApplication.value.length,
    applyDate: await getServerDateApi(),
    opDatetime: '',
    urgentClinicFlag: '',
    ssbc: '',
    diagBeforeCode: '',
    ybSelfFlag: '',
    partCode: '',
    opScale: '',
    hocusCode: '',
    doctorZd: '',
    doctor1: '',
    doctor2: '',
    doctor3: '',
    doctorMz: '',
    nurseQx: '',
    nurseXh: '',
    remark: '',
  })
  tabs.value = operationApplication.value.length
}

// 麻醉方式
const anestheticMode = ref()

onMounted(() => {
  maZuiFangShi().then(res => {
    anestheticMode.value = res
  })
  if (isDev) {
    dianJiXinZhenShouShu()
  }
})

</script>

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