<template>
  <div style="width: 100%;">
    <el-date-picker
        v-model="dateRange"
        :shortcuts="shortcuts"
        end-placeholder="结束日期"
        placeholder="选择日期"
        range-separator="至"
        size="small"
        start-placeholder="开始日期"
        style="width: 220px"
        type="daterange"/>
    医嘱名称：
    <el-select v-model="orderName" :remote-method="remoteMethodChargeCode" clearable filterable remote
               style="width: 120px">
      <el-option v-for="item in yiZhuMingZiData" :key="item.code" :label="item.name" :value="item.code">
        <span>{{ item.name }}</span>
      </el-option>
    </el-select>
    医嘱号:
    <el-input v-model="actOrderNo"
              style="width: 120px"
              onkeyup="this.value=this.value.replace(/[^\d]/g,'') "/>
    频率：
    <el-select v-model="pinLv" :disabled="zhuangTai === 8 || zhuangTai === 9" clearable filterable size="small"
               style="width: 120px">
      <el-option v-for="item in huanZhePinLvData" :key="item.code" :label="item.name" :value="item.code">
        <span>{{ item.name }}</span>
      </el-option>
    </el-select>
    状态：
    <el-select v-model="zhuangTai" filterable size="small" style="width: 120px" @change="zhuangTaiXuanZhe">
      <el-option v-for="item in zhuangTaiList" :key="item.code" :label="item.name" :value="item.code">
        <span>{{ item.code }}</span>
        <el-divider direction="vertical"/>
        <span>{{ item.name }}</span>
      </el-option>
    </el-select>
    <el-divider direction="vertical"/>
    <el-button icon="Search" type="primary" @click="chaXunYiZhuClick(0)">查询</el-button>
    <el-divider style="margin: 2px 0"></el-divider>
    <el-tag effect="dark" type="info">录入</el-tag>
    <el-tag effect="dark" type="success">确认</el-tag>
    <el-tag effect="dark">执行</el-tag>
    <el-tag effect="dark" type="danger">停止</el-tag>
    <el-divider direction="vertical"></el-divider>
    <el-button icon="Plus" type="primary" @click="addYiZhuClick"> 添加</el-button>
    <el-button type="warning" :disabled="xuanZhongDeShuJu.length === 0" @click="clickBatchStop">批量停止</el-button>
    <el-divider direction="vertical"></el-divider>
    <el-button :disabled="xuanZhongDeShuJu.length === 0" type="success" @click="dianJiFuZhuXuanZhongYiZhu">复制选中医嘱
    </el-button>
    <el-button type="warning" :disabled="stringIsBlank(huanZheXinXi.inpatientNo)"
               @click="clickToModifyTheDoctorSOrderTime"> 修改医嘱时间
    </el-button>
    <el-button type="warning" :disabled="stringIsBlank(huanZheXinXi.inpatientNo)" @click="jumpToMedicalRecord"> 病案首页
    </el-button>
    <el-button type="primary" @click="openElectronicMedicalRecord"> 电子病历</el-button>

    <xc-table :data="yiZhuPage"
              row-key="id"
              @currentChange="handleCurrentChange"
              @sizeChange="handleSizeChange"
              :height="230"
              @rowContextmenu="clickToViewTheDoctorSOrderFee"
              @selectionChange="huoQuXuanZhongDeShuJu"
              ref="tableRef">
      <el-table-column fixed="left" type="selection"></el-table-column>
      <el-table-column fixed="left" label="医嘱号" prop="actOrderNo"
                       width="120" show-overflow-tooltip>
        <template #default="scope">
          <el-tag :type="getYiZhuFlag(scope.row.statusFlag)" effect="dark">
            {{ scope.row.actOrderNo }}
          </el-tag>
          <span v-html="getFeeInfor(scope.row.actOrderNo)">
                        </span>
        </template>
      </el-table-column>
      <el-table-column fixed="left" width="20">
        <template #default="scope">
          {{ scope.row.orderGroup }}
        </template>
      </el-table-column>
      <el-table-column fixed="left" label="医嘱名称" show-overflow-tooltip width="135">
        <template #default="scope">
          {{ scope.row.orderName }}
        </template>
      </el-table-column>
      <el-table-column label="剂量" prop="doseUnitName">
        <template #default="scope">
          <span>{{ scope.row.dose }} {{ scope.row.doseUnitName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="频率" prop="frequCodeName"></el-table-column>
      <el-table-column label="给药方式" prop="supplyCodeName" show-overflow-tooltip></el-table-column>
      <el-table-column label="医嘱时间" prop="orderTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="开始时间" prop="startTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="录入人" prop="physicianName"></el-table-column>
      <el-table-column label="确认时间" prop="confirmTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="确认人" prop="signerName"></el-table-column>
      <el-table-column label="结束时间" prop="endTime" show-overflow-tooltip></el-table-column>
      <el-table-column label="停止人" prop="modifierName" show-overflow-tooltip></el-table-column>
      <el-table-column label="紧急" prop="emergencyFlag">
        <template #default="scope">
          <span v-if="scope.row.emergencyFlag === '1'">是</span>
        </template>
      </el-table-column>
      <el-table-column label="医保自费" prop="ybSelfFlag">
        <template #default="scope">
          <span v-if="scope.row.ybSelfFlag === '1'">是</span>
        </template>
      </el-table-column>
      <el-table-column label="医生" prop="physicianName"></el-table-column>
      <el-table-column label="费用标志" prop="selfBuyName"></el-table-column>
      <el-table-column label="执行科室" prop="execUnitName"></el-table-column>
      <el-table-column label="领量" prop="drugQuanName">
        <template #default="scope">
          <span>{{ scope.row.drugQuan }} {{ scope.row.drugQuanName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类别" prop="drugFlagName">
        <template #default="scope">
          <span>{{ scope.row.drugFlag }} {{ scope.row.drugFlagName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="药房" prop="groupNoName"></el-table-column>
      <el-table-column label="序号" prop="serialName"></el-table-column>
      <el-table-column fixed="right" width="220">
        <template #header>
          <el-button size="small" @click="clearSelection" type="warning">清空选择</el-button>
        </template>
        <template #default="scope">
          <el-button text :disabled="scope.row.statusFlag === '5'"
                     @click.stop="dianJiYiZhuChaoZuo(scope.row, 1,'无')">
            <span v-if="scope.row.emergencyFlag === '1'">取消</span>
            <span v-else>紧急</span>
          </el-button>
          <el-button text @click.stop="dianJiYiZhuChaoZuo(scope.row, 2, '撤销医嘱')" type="warning"> 撤销</el-button>
          <el-button text @click.stop="dianJiYiZhuChaoZuo(scope.row, 3, '停止医嘱')" type="danger"> 停止</el-button>
        </template>
      </el-table-column>
    </xc-table>

    <el-dialog v-model="yiZhuChaoZuoDialog" :close-on-click-modal="false" :close-on-press-escape="false"
               :show-close="false" :title="yiZhuChaoZuoBiaoTi" top="25%" width="30%">
      <div v-if="chaoZuoBiaoZhi === 2">
        撤销原因：
        <el-input v-model="content" maxlength="100" rows="2" show-word-limit type="textarea"></el-input>
      </div>
      <div v-else-if="chaoZuoBiaoZhi === 3 || chaoZuoBiaoZhi === 90">
        停止时间点：
        <el-date-picker v-model="tingZhiRiQi" format="YYYY-MM-DD HH:mm:ss" type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dianJiDuiHuaKuangZhongDeGuanBi">关闭</el-button>
          <el-button type="primary" @click="zhiXingChaoZuo">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <doctor-s-order-fee :data="chargeDetails.data"
                        v-if="chargeDetails.dialog"
                        :sum="chargeDetails.sum"
                        @close="chargeDetails.dialog = false"/>
  </div>


</template>

<script name="YiZhuLuRuZhuJian" setup>
import {shortcuts} from '@/data/shortcuts'
import {
  expensesForGettingADoctorSOrder,
  huoQuYiZhuMingCheng,
  huoQuYiZhuShuJu,
  piLiangXiuGaiTingZhiShiJian,
  yiZhuChaoZuo
} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {fuZhiYiZhu, huanZhePinLvData, huanZheXinXi, youWuXuanZheHuanZhe, zkList} from '../public-js/zhu-yuan-yi-sheng'
import {getDateRangeFormatDate} from '@/utils/date'
import store from '@/store'
import {stringIsBlank} from '@/utils/blank-utils'
import {getServerDateApi, getTheTransferList} from '@/api/public-api'
import router from '@/router'
import XcTable from "@/components/xc/xc-table/XcTable.vue";
import sleep from "@/utils/sleep";
import DoctorSOrderFee from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/DoctorSOrderFee.vue";
import {BizException, ExceptionEnum} from "@/utils/BizException";

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

const user = computed(() => {
  return store.state.user.info
})

const dateRange = ref([])
// 根据医嘱的名字来进行搜索
let orderName = $ref('')
const yiZhuMingZiData = ref([])
// 获取频率
const pinLv = ref('')
// 表格
let tableRef = $ref(null)
// 状态
const zhuangTai = ref(0)
// 医嘱号
let actOrderNo = $ref('')
// 分页
const yiZhuPage = ref({
  currentPage: 1,
  pageSize: 30,
  total: 0,
  data: [],
})

const remoteMethodChargeCode = (val) => {
  if (youWuXuanZheHuanZhe()) return
  if (val.length > 1) {
    huoQuYiZhuMingCheng(huanZheXinXi.value.inpatientNo, huanZheXinXi.value.admissTimes, val).then((res) => {
      yiZhuMingZiData.value = res
    })
  }
}

// 根据医嘱的名字来进行搜索 结束
const zhuangTaiList = ref([
  {code: 0, name: '全部'},
  {code: 1, name: '录入'},
  {code: 2, name: '确认'},
  {code: 3, name: '执行'},
  {code: 5, name: '停止'},
  {code: 6, name: '可停止'},
  {code: 7, name: '可撤销'},
  {code: 8, name: '临时医嘱'},
  {code: 9, name: '长期医嘱'},
])

const zhuangTaiXuanZhe = (val) => {
  if (val >= 6) {
    orderName = ''
    pinLv.value = ''
  }
}

const chaXunYiZhuClick = (total) => {
  if (youWuXuanZheHuanZhe()) return
  const dateS = getDateRangeFormatDate(dateRange.value)
  let data = {
    currentPage: yiZhuPage.value.currentPage,
    pageSize: yiZhuPage.value.pageSize,
    total: total,
    patNo: huanZheXinXi.value.inpatientNo,
    times: huanZheXinXi.value.admissTimes,
    startTime: dateS.startTime,
    endTime: dateS.endTime,
    frequCode: pinLv.value,
    orderName: orderName,
    zhuangTai: zhuangTai.value,
    actOrderNo: actOrderNo
  }
  huoQuYiZhuShuJu(data)
      .then((res) => {
        yiZhuPage.value.total = res.total
        yiZhuPage.value.data = res.records
      })
      .catch((e) => {
        yiZhuPage.value.total = 0
        yiZhuPage.value.data = []
      })
}

const handleSizeChange = (val) => {
  yiZhuPage.value.pageSize = val
  chaXunYiZhuClick(yiZhuPage.value.total)
}

const handleCurrentChange = (val) => {
  yiZhuPage.value.currentPage = val
  chaXunYiZhuClick(yiZhuPage.value.total)
}

const clearSelection = () => {
  tableRef.clearSelection()
}

/**
 * 下面这里是添加医嘱了
 */
const addYiZhuClick = () => {
  router.push({
    name: 'xinZengShuJu',
    params: {
      passRule: true,
      name: '添加医嘱',
    },
    query: {
      path: '/inpatient/zhuYuanYiSheng/yiZhuLuRu',
    },
  })
}

/**
 * 打开电子病历
 */
const openElectronicMedicalRecord = () => {
  if (youWuXuanZheHuanZhe()) return
  router.push({
    name: 'xinZengShuJu',
    params: {
      passRule: true,
      name: '电子病历',
    },
    query: {
      path: '/inpatient/zhuYuanYiSheng/yiZhuLuRu',
    },
  })
}

const dianJiYiZhuChaoZuo = ({actOrderNo, orderName}, flag, name) => {
  chaoZuoBiaoZhi = flag
  yiZhuHao.value = actOrderNo
  if (flag === 1) {
    zhiXingChaoZuo()
  } else {
    yiZhuChaoZuoDialog = true
    if (flag === 2) {
      yiZhuChaoZuoBiaoTi = '撤销医嘱'
    } else if (flag === 3) {
      yiZhuChaoZuoBiaoTi = '停止医嘱'
    }
  }
}

const zhiXingChaoZuo = () => {
  if (chaoZuoBiaoZhi === 90) {
    let data = {
      actOrderNoList: [],
      endTime: tingZhiRiQi.value,
    }
    xuanZhongDeShuJu.value.forEach(item => {
      data.actOrderNoList.push(item.actOrderNo)
    })
    piLiangXiuGaiTingZhiShiJian(data).then((res) => {
      handleCurrentChange(yiZhuPage.value.currentPage)
      yiZhuChaoZuoDialog = false
    })
  } else {
    // 这里 是因为停止医嘱和撤销医嘱中 时间和撤销原因用的是同一个
    // 方法 所以需要使用到不同的提交内容
    let data = ''
    if (chaoZuoBiaoZhi === 2) {
      data = content
    } else if (chaoZuoBiaoZhi === 3) {
      data = tingZhiRiQi.value
    }
    yiZhuChaoZuo(yiZhuHao.value, chaoZuoBiaoZhi, data).then((res) => {
      handleCurrentChange(yiZhuPage.value.currentPage)
      yiZhuChaoZuoDialog = false
      content = ''
    })
  }
}

let yiZhuChaoZuoDialog = $ref(false)
let content = $ref('')
const tingZhiRiQi = ref('')
/**
 * 医嘱操作状态 1-设为紧急 2-撤销 3-停止  90-批量停止
 */
let chaoZuoBiaoZhi = $ref(0)
const yiZhuHao = ref(0)
let yiZhuChaoZuoBiaoTi = $ref('')

const xuanZhongDeShuJu = ref([])

const huoQuXuanZhongDeShuJu = (val) => {
  xuanZhongDeShuJu.value = val
}

// 用户切换全选和全不选 时 el-table中的全选不会选中子节点
const toggleSelection = (row, selected) => {
  if (row) {
    row.forEach((item) => {
      tableRef.value.toggleRowSelection(item, selected)
    })
  }
}


/**
 * 点击复制医嘱
 */
const dianJiFuZhuXuanZhongYiZhu = () => {
  fuZhiYiZhu.value = xuanZhongDeShuJu.value
}

/**
 * 右键点击查看医嘱产生的费用
 * @param val
 */
let doctorSOrderFee = $ref({
  data: {},
  problem: {},
  totalCost: {}
})
let chargeDetails = $ref({
  dialog: false,
  data: [],
  sum: {}
})
const clickToViewTheDoctorSOrderFee = (val) => {
  chargeDetails.data = doctorSOrderFee.data[val.actOrderNoStr]
  chargeDetails.sum = doctorSOrderFee.totalCost[val.actOrderNoStr]
  chargeDetails.dialog = true
}
const getFeeInfor = (actOrderNo) => {
  try {
    let problem = doctorSOrderFee.problem[actOrderNo]
    if (typeof problem === 'undefined') {
      problem = ''
    } else {
      problem = '有' + problem
    }
    return `<br>金额:${doctorSOrderFee.totalCost[actOrderNo].sum} 元,
    ${doctorSOrderFee.totalCost[actOrderNo].amount}条,
    <br/>${problem}`
  } catch (e) {
    return ""
  }
}

onMounted(async () => {
  await sleep(200)
  // addYiZhuClick()
  zkList.value = await getTheTransferList()
})


watch(
    () => huanZheXinXi.value,
    () => {
      expensesForGettingADoctorSOrder(huanZheXinXi.value.inpatientNo, huanZheXinXi.value.admissTimes).then((res) => {
        doctorSOrderFee = res
      })

      getServerDateApi().then((res) => {
        chaXunYiZhuClick(0)
      })
    }
)

function getYiZhuFlag(val) {
  if (stringIsBlank(val)) {
    return 'warning'
  }
  switch (val) {
    case '1':
      return 'info'
    case '2':
      return 'success'
    case '3':
      return ''
    case '4':
      return ''
    case '5':
      return 'danger'
    default:
      return 'warning'
  }
}

/**
 * 点击批量停止
 */
const clickBatchStop = () => {
  yiZhuChaoZuoDialog = true
  chaoZuoBiaoZhi = 90
  yiZhuChaoZuoBiaoTi = '批量停止'
}

const dianJiDuiHuaKuangZhongDeGuanBi = () => {
  yiZhuChaoZuoDialog = false
  content = ''
}

// 点击修改医嘱时间
const clickToModifyTheDoctorSOrderTime = () => {
  router.push({
    name: 'yzActOrderModify',
    query: {
      patNo: huanZheXinXi.value.inpatientNo,
    },
  })
}

const jumpToMedicalRecord = () => {
  router.push({
    name: 'fillCaseFrontSheet',
    query: {
      patNo: huanZheXinXi.value.inpatientNo,
      deptCode: huanZheXinXi.value.smallDept,
    },
  })
}
</script>

<style scoped lang="scss">


:deep(.el-table .children-row) {
  background: rgba(145, 247, 145, 0.93);
}

:deep(.el-table) {
  --el-table-row-hover-background-color: #85dbfd7a;
}

:deep(.el-dropdown-menu__item) {
  font-size: 14px !important;
  height: 26px;
  line-height: 26px;
  font-weight: bold;
}
</style>
