<template>
  <el-dialog v-model="dialog" title="搜索医嘱" width="95%" @close="emit('close')">
    <el-input ref="searchInput" v-model="orderName" autofocus clearable style="width: 220px"
              @keyup.enter="dianJiChaXunYiZhu"
    ></el-input>
    <el-button icon="Search" type="primary" @click="dianJiChaXunYiZhu">搜索</el-button>
    <xc-code code="ctrl+1" description="重新获取焦点"/>
    <xc-code code="Alt+↓/↑" description="上下选择"></xc-code>
    <xc-code code="Alt+←/→" description="左右翻页"></xc-code>
    <xc-code code="Alt+Enter" description="选中"></xc-code>
    <xc-code code="Alt+Q" description="查看药品用法"></xc-code>
    <el-table :data="tempOrderData"
              :height="windowSize.h / 1.6"
              ref="elTableRef"
              @row-click="selectedData"
              :row-class-name="tableRowClassName">
      <el-table-column label="编码" prop="orderCode"></el-table-column>
      <el-table-column label="名称" prop="orderName"></el-table-column>
      <el-table-column label="规格" prop="drugSpecification"></el-table-column>
      <el-table-column label="描述" prop="discription"></el-table-column>
      <el-table-column label="库存" prop="stockAmount"></el-table-column>
      <el-table-column label="大包装" prop="specPack"></el-table-column>
      <el-table-column label="医保类型" prop="ybFlagNew"></el-table-column>
      <el-table-column label="医保编码" prop="nationalCode"></el-table-column>
      <el-table-column label="医保名称" prop="nationalName"></el-table-column>
      <el-table-column label="医保备注" prop="ybComment"></el-table-column>
      <el-table-column label="大输液" prop="infusionFlagName"></el-table-column>
      <el-table-column label="厂家" prop="manuName"></el-table-column>
      <el-table-column label="类型" prop="orderType"></el-table-column>
      <el-table-column label="毒麻类型" prop="drugFlagName"></el-table-column>
      <el-table-column label="药品详情">
        <template #default="scope">
          <el-button
              v-if="scope.row.serial !== '00'"
              @click.stop.prevent="queryDrugDetails(scope.row.orderCode.trim() + '_' + scope.row.serial.trim())">
            药品详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :current-page="orderData.currentPage"
        :page-size="orderData.pageSize"
        :total="orderData.data.length"
        layout="total,prev,pager,next,jumper"
        @current-change="orderDataCurrent"
        ref="pageRef"
    >
    </el-pagination>
    <yao-ping-xiang-qing v-if="yaoPinXiangQing.dialog" :code="yaoPinXiangQing.code"
                         @close="yaoPinXiangQing.dialog = false"></yao-ping-xiang-qing>
  </el-dialog>
</template>

<script name="SouSuoYiZhu" setup>
import {huoQuXiangMu} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {computed, ref} from 'vue'
import store from '@/store'
import YaoPingXiangQing from '@/components/zhu-yuan-yi-sheng/he-li-yong-yao/YaoPingXiangQing.vue'
import {xcHotKey} from '@/utils/xckeydown'
import {ElMessage} from 'element-plus'
import Sleep from '@/utils/sleep'
import {setScrollTop} from "@/utils/el-table-scroll";

const emit = defineEmits(['xuanZhongFeiYong', 'close'])

const windowSize = computed(() => {
  return store.state.app.windowSize
})
let dialog = $ref(true)
const orderName = ref('') // 01672
let searchInput = $ref(null)
let dataIndex = $ref(-1)
let elTableRef = $ref(null)
let count = computed(() => {
  return Math.ceil(orderData.value.data.length / orderData.value.pageSize)
})

const orderData = ref({
  currentPage: 1,
  pageSize: 10,
  data: [],
})

const tempOrderData = computed(() => {
  return orderData.value.data.slice((orderData.value.currentPage - 1) * orderData.value.pageSize, orderData.value.currentPage * orderData.value.pageSize)
})

const dianJiChaXunYiZhu = () => {
  huoQuXiangMu(orderName.value).then(async (res) => {
    orderData.value.data = res
    orderData.value.currentPage = 1
    dataIndex = -1
  })
}

const queryDrugDetails = (code) => {
  yaoPinXiangQing.dialog = true;
  yaoPinXiangQing.code = code
}

const orderDataCurrent = (val) => {
  dataIndex = 0
  orderData.value.currentPage = val
}

const tableRowClassName = ({row, rowIndex}) => {
  if (dataIndex === rowIndex) {
    return 'input_and_table_to_be_selected'
  }
}

let yaoPinXiangQing = $ref({
  dialog: false,
  code: '',
})

const direction = (val) => {
  let pageDataLength = tempOrderData.value.length
  if (pageDataLength > 0) {
    removeHoverStyle()
    switch (val) {
      case 'ArrowUp':
        dataIndex <= 0 ? (dataIndex = pageDataLength - 1) : dataIndex--
        break
      case 'ArrowDown':
        dataIndex === pageDataLength - 1 ? (dataIndex = 0) : dataIndex++
        break
      case 'ArrowRight':
        orderDataCurrent(orderData.value.currentPage + 1 > count.value ? 1 : orderData.value.currentPage + 1)
        break
      case 'ArrowLeft':
        orderDataCurrent(orderData.value.currentPage - 1 < 1 ? count.value : orderData.value.currentPage - 1)
        break
    }
    setScrollTop(elTableRef, dataIndex)
  }
}

const selectedData = (row) => {
  emit('xuanZhongFeiYong', row)
}

const enter = () => {
  if (dataIndex > -1) {
    emit('xuanZhongFeiYong', tempOrderData.value[dataIndex])
  } else {
    ElMessage.error('请先选择数据')
  }
}

const viewDrugUsage = () => {
  if (dataIndex > -1) {
    let data = tempOrderData.value[dataIndex]
    if (data.serial !== '00') {
      yaoPinXiangQing.dialog = true
      yaoPinXiangQing.code = data.orderCode.trim() + '_' + data.serial.trim()
    } else {
      ElMessage.error('这个是项目')
    }
  } else {
    ElMessage.error('请先选择数据')
  }
}

const regainFocus = () => {
  searchInput.focus()
}

let registerShortcuts = {
  alt: {direction: direction, Enter: enter, q: viewDrugUsage},
  ctrl: {1: regainFocus},
}

const hotKey = () => {
  xcHotKey(registerShortcuts)
}

onMounted(async () => {
  await Sleep(500)
  if (searchInput) {
    searchInput.focus()
  }
  hotKey()
})

const removeHoverStyle = () => {
  let oldItem = elTableRef.$el.classList
  let newItem = []
  for (let i = 0; i < oldItem.length; i++) {
    if (oldItem[i] !== 'el-table--enable-row-hover') {
      newItem.push(oldItem[i])
    }
  }
  elTableRef.$el.classList = newItem
  elTableRef.$el.className = newItem.join(' ')
}
</script>

<style scoped></style>
