<template>
  <el-dialog draggable v-model="dialog" destroy-on-close title="模板" width="90%" @close="emit('close')">
    <el-container>
      <el-aside style="width: 350px">
        <el-radio-group v-model="muBanLeiXing" size="small" @change="dianJiChaXun">
          <el-radio-button :label="0">全部</el-radio-button>
          <el-radio-button :label="1">全院</el-radio-button>
          <el-radio-button :label="2">本科室</el-radio-button>
          <el-radio-button :label="3">个人</el-radio-button>
          <el-radio-button :label="4">收藏</el-radio-button>
        </el-radio-group>
        <el-input v-model="code" clearable style="width: 120px" @keyup.enter="dianJiChaXun"></el-input>
        <el-button @click="dianJiChaXun">查询</el-button>
        <el-table :data="fuJiMuBanShuJu.data" :height="windowSize.h / 1.6"
                  highlight-current-row stripe
                  @row-click="dianJiMuBanMing"
                  style="width: 300px">
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary"
                         icon="Edit"
                         v-if="muBanLeiXing !== 4 && props.editor"
                         link
                         title="编辑模板"
                         @click.stop="clickToEditTemplate(scope.row)"/>
              <el-button type="warning"
                         v-if="muBanLeiXing !== 4"
                         title="收藏模板"
                         link
                         @click.stop="clickToFavoriteTemplates(scope.row,scope.$index)"
                         :icon="scope.row.yiBeiShouCang ?  'StarFilled' : 'Star'"/>
              <el-button type="danger"
                         icon="Delete"
                         title="删除模板"
                         link
                         @click.stop="clickDeleteTemplate(scope.row.patternCode,scope.$index)"/>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="patternName" width="70"/>
        </el-table>
        <el-pagination
            :current-page="fuJiMuBanShuJu.currentPage"
            :page-size="fuJiMuBanShuJu.pageSize"
            :pager-count="5"
            :total="fuJiMuBanShuJu.total"
            layout="total,prev, pager, next"
            small
            @current-change="handleCurrentChange"
        >
        </el-pagination>
      </el-aside>
      <el-main>
        <el-button type="primary" @click="dianJiQueDing">确定</el-button>
        开始时间：
        <el-date-picker
            v-model="startTime"
            :disabled-date="disabledDate"
            format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
        ></el-date-picker>
        医嘱时间：
        <el-input v-model="orderTime" disabled style="width: 180px"></el-input>
        频率：
        <el-select
            v-model="frequCode"
            :remote-method="pinLvRemoteMethod"
            clearable
            filterable
            remote
            size="small"
            style="width: 120px"
            @change="getFrequCodeName"
            @clear="frequCode = null"
            ref="frequCodeRef">
          <el-option v-for="item in yaoPinPingLvData"
                     :key="item.code" :label="item.name"
                     :value="item.code">
            <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>{{ item.name }}</span>
          </el-option>
        </el-select>
        <xc-table ref="tableRef"
                  row-key="id"
                  :local-data="muBanShuJu"
                  :open-paging="false"
                  :height="windowSize.h / 1.6">
          <el-table-column fixed="left" type="selection"/>
          <el-table-column fixed="left" label="uuid" prop="id"></el-table-column>
          <el-table-column label="医嘱名称" prop="orderName" show-overflow-tooltip width="135"></el-table-column>
          <el-table-column label="规格" prop="drugSpecification"></el-table-column>
          <el-table-column label="频率" prop="frequCodeName"></el-table-column>
          <el-table-column label="一次剂量" prop="dose">
            <template #default="scope"> {{ scope.row.dose }} {{ scope.row.doseUnitName }}</template>
          </el-table-column>
          <el-table-column label="领量" prop="drugQuan">
            <template #default="scope"> {{ scope.row.drugQuan }} {{ scope.row.miniUnitName }}</template>
          </el-table-column>
          <el-table-column label="给药方式" prop="supplyCodeName"></el-table-column>
          <el-table-column label="执行科室" prop="execUnitName"></el-table-column>
          <el-table-column label="药房" prop="groupNoName"></el-table-column>
          <el-table-column label="父医嘱" prop="parentNo"></el-table-column>
        </xc-table>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script name="HuoQuMuBan" setup>
import store from '../../../store'
import {
  collectDoctorSOrderTemplate,
  deleteADoctorSOrderTemplate,
  huoQuMuBanShuJu,
  huoQuYiZhuMuBan,
  huoQuZhuYuanPinLv,
} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {muBanMing} from '@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng'
import {computed, ref} from 'vue'
import {stringNotBlank} from '@/utils/blank-utils'
import {ElMessageBox} from 'element-plus'
import {clone} from '@/utils/clone'
import {getServerDateApi} from '@/api/public-api'
import {BizException, ExceptionEnum} from "@/utils/BizException";
import XcTable from "@/components/xiao-chan/xc-table/XcTable.vue";

const props = defineProps({
  dialog: {
    type: Boolean,
    default: false
  },
  editor: {
    type: Boolean,
    default: true
  }

})

// 调用父组件的方法
const emit = defineEmits(['mu-ban-shu-ju', 'close', 'edit-template'])

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

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

const code = ref('')
const dialog = ref(props.dialog)
const muBanShuJu = ref([])
const tableRef = ref(null)
const muBanLeiXing = ref(3)

let startTime = $ref('')
let orderTime = $ref('')
const frequCode = ref('')
const frequCodeRef = ref(null)
const frequCodeName = ref('')
const yaoPinPingLvData = ref([])

const dianJiFuJiXinXi = ref('')

const fuJiMuBanShuJu = ref({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  data: [],
})
// 获取医嘱
const dianJiChaXun = () => {
  huoQuYiZhuMuBan(code.value, user.value.deptCode, muBanLeiXing.value, fuJiMuBanShuJu.value.currentPage, 0).then((res) => {
    fuJiMuBanShuJu.value.data = res.records
    fuJiMuBanShuJu.value.total = res.total
  })
}

const dianJiMuBanMing = async (row) => {
  dianJiFuJiXinXi.value = row
  muBanShuJu.value = await huoQuMuBanShuJu(row.inputType === '4' ? row.collectCode : row.patternCode)
  let serverDate = await getServerDateApi()
  orderTime = serverDate
  startTime = serverDate
}

// 分页
const handleCurrentChange = (val) => {
  fuJiMuBanShuJu.value.currentPage = val
  huoQuYiZhuMuBan(code.value, user.value.deptCode, muBanLeiXing.value, fuJiMuBanShuJu.value.currentPage, fuJiMuBanShuJu.value.total).then((res) => {
    fuJiMuBanShuJu.value.data = res.records
  })
}

// 删除模板
const clickDeleteTemplate = (patternCode, index) => {
  ElMessageBox.confirm('确定要删除该模板吗？', '提示', {
    type: 'error',
  }).then(() => {
    deleteADoctorSOrderTemplate(patternCode).then((res) => {
      fuJiMuBanShuJu.value.data.splice(index, 1)
      muBanShuJu.value = []
    })
  }).catch((e) => {
  })
}

// 收藏模板
const clickToFavoriteTemplates = ({inputId, patternCode}, index) => {
  if (inputId === store.state.user.info.code) {
    BizException(ExceptionEnum.MESSAGE_ERROR, "无法收藏自己创建的模板。")
  }
  collectDoctorSOrderTemplate(patternCode).then((res) => {
    fuJiMuBanShuJu.value.data[index].yiBeiShouCang = !fuJiMuBanShuJu.value.data[index].yiBeiShouCang
  });
}

// 点击编辑模板
const clickToEditTemplate = async (row) => {
  await dianJiMuBanMing(row)
  let temp = []
  muBanShuJu.value.forEach(item => {
    settingValue(item)
    temp.push(item)
    if (item.children) {
      item.children.forEach(value => {
        settingValue(value)
        temp.push(value)
      })
    }
  })
  emit('edit-template', clone(temp))
  muBanMing.value = dianJiFuJiXinXi.value
}

const settingValue = (item) => {
  item.startTime = startTime
  item.orderTime = orderTime
  if (stringNotBlank(frequCode.value)) {
    item.frequCode = frequCode.value
    item.frequCodeName = frequCodeName.value
  }
}

// 获取选中的 医嘱数据
const xuanZhongShuJu = ref([])

const dianJiQueDing = () => {
  xuanZhongShuJu.value = tableRef.value.getSelectionRows()
  xuanZhongShuJu.value.forEach((item) => {
    item.startTime = startTime
    item.orderTime = orderTime
    if (stringNotBlank(frequCode.value)) {
      item.frequCode = frequCode.value
      item.frequCodeName = frequCodeName.value
    }
  })
  emit('mu-ban-shu-ju', clone(xuanZhongShuJu.value))
}

const openTemplateByCode = (code) => {
  dianJiMuBanMing({
    patternCode: code
  })
}

// 时间限制
// 医嘱限制时间不能在之前
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 获取评率
const getFrequCodeName = async () => {
  await nextTick()
  frequCodeName.value = frequCodeRef.value.selected.currentLabel
}

const pinLvRemoteMethod = (val) => {
  if (val.length > 1) {
    huoQuZhuYuanPinLv(val).then((res) => {
      yaoPinPingLvData.value = res
    })
  }
}

onMounted(() => {
  dianJiChaXun()
})

const openOrCloseDialog = (val) => {
  dialog.value = val
}

defineExpose({
  openTemplateByCode,
  openOrCloseDialog
})
</script>

<style scoped>
:deep(.el-table .children-row) {
  background: rgba(145, 247, 145, 0.5);
}

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