<template>
  <el-container>
    <el-header>
      <el-date-picker
          v-model="dateRange"
          :shortcuts="shortcuts"
          end-placeholder="结束日期"
          placeholder="选择日期"
          range-separator="至"
          size="small"
          start-placeholder="开始日期"
          style="width: 220px"
          type="daterange"
      >
      </el-date-picker>
      医嘱名称：
      <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-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"></el-divider>
          <span>{{ item.name }}</span>
        </el-option>
      </el-select>
      <el-divider direction="vertical"></el-divider>
      <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-header>
    <el-main>
      <el-table
          ref="tableRef"
          :data="yiZhuPage.data"
          :height="windowSize.h / 1.5"
          :row-class-name="differChildrenRows"
          border
          class="eltable"
          highlight-current-row
          row-key="actOrderNo"
          @selection-change="huoQuXuanZhongDeShuJu"
          @select-all="quanXuanYiZhu"
          @row-click="clickOnTheForm"
      >
        <el-table-column fixed="left" type="index"></el-table-column>
        <el-table-column fixed="left" type="selection"></el-table-column>
        <el-table-column fixed="left" label="医嘱号" prop="actOrderNo" width="120">
          <template #default="scope">
            <el-tag :type="getYiZhuFlag(scope.row.statusFlag)" effect="dark">{{ scope.row.actOrderNo }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="left" label="医嘱名称" prop="orderName" show-overflow-tooltip width="135"></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" label="操作" width="150">
          <template #default="scope">
            <el-dropdown :hide-on-click="false" size="small" split-button type="primary">
              操作
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :disabled="scope.row.statusFlag === '5'"
                                    @click="dianJiYiZhuChaoZuo(scope.row, 1,'无')">
                    <span v-if="scope.row.emergencyFlag === '1'">取消紧急</span>
                    <span v-else>设为紧急</span>
                  </el-dropdown-item>
                  <el-dropdown-item @click="dianJiYiZhuChaoZuo(scope.row, 2, '撤销医嘱')"> 撤销医嘱</el-dropdown-item>
                  <el-dropdown-item @click="dianJiYiZhuChaoZuo(scope.row, 3, '停止医嘱')"> 停止医嘱</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :current-page="yiZhuPage.currentPage"
          :page-size="yiZhuPage.pageSize"
          :page-sizes="[10, 20, 30, 40, 50]"
          :total="yiZhuPage.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      >
      </el-pagination>
    </el-main>
    <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>
  </el-container>
</template>

<script name="YiZhuLuRuZhuJian" setup>
import {shortcuts} from '@/data/shortcuts'
import {
  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, getFormatDatetime} from '@/utils/date'
import store from '@/store'
import {stringIsBlank, stringNotBlank} from '@/utils/blank-utils'
import {getServerDateApi, getTheTransferList} from '@/api/public-api'
import router from '@/router'
import Sleep from '@/utils/sleep'

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('')
// 状态
const zhuangTai = ref(0)
// 分页
const yiZhuPage = ref({
  currentPage: 1,
  pageSize: 30,
  total: 0,
  data: [],
})
const tableRef = ref(null)

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,
  }
  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 differChildrenRows = ({row}) => {
  if (row.isChildren) {
    return 'children-row'
  }
}

/**
 * 下面这里是添加医嘱了
 */
const addYiZhuClick = () => {
  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)
    })
  }
}

/**
 * 切换全选和不全选
 * @type {boolean}
 */
let quanXuanFlag = false // 默认 为全不选
const quanXuanYiZhu = (selection) => {
  quanXuanFlag = !quanXuanFlag
  selection.forEach((item) => {
    if (stringNotBlank(item.children)) {
      toggleSelection(item.children, quanXuanFlag)
    }
  })
  if (!quanXuanFlag) {
    tableRef.value.clearSelection()
  }
}

const clickOnTheForm = (row, column, event) => {
  tableRef.value.toggleRowSelection(row, !xuanZhongDeShuJu.value.includes(row))
}

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

onMounted(async () => {
  // setTimeout(() => {
  //   addYiZhuClick()
  // }, 300)
  zkList.value = await getTheTransferList()
})

onActivated(() => {
  getServerDateApi().then((res) => {
    dateRange.value[0] = getFormatDatetime(res, 'YYYY-MM-DD')
    dateRange.value[1] = getFormatDatetime(res, 'YYYY-MM-DD')
    chaXunYiZhuClick(0)
  })
})

watch(
    () => huanZheXinXi.value,
    () => {
      getServerDateApi().then((res) => {
        if (dateRange.value === null) {
          dateRange.value = []
          dateRange.value.push(getFormatDatetime(res, 'YYYY-MM-DD'))
          dateRange.value.push(getFormatDatetime(res, 'YYYY-MM-DD'))
        } else {
          dateRange.value[0] = getFormatDatetime(res, 'YYYY-MM-DD')
          dateRange.value[1] = getFormatDatetime(res, 'YYYY-MM-DD')
        }
        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>
: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>
