<template>
  <el-container>
    <el-main>
      <el-row>
        <el-col>
          <el-date-picker
              type="daterange"
              v-model="dateRange"
              placeholder="选择日期"
              style="width: 280px"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="shortcuts"
          ></el-date-picker>
          <el-input style="width: 160px" placeholder="请输入住院号" clearable v-model.trim="queryTerm.inpatientNo"
                    @keyup.enter="getHuanZheXinXiClick"></el-input>
          <el-select v-model="queryTerm.wardCode" filterable clearable placeholder="请选择病区">
            <el-option v-for="item in wardData" :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>
          <el-divider direction="vertical"></el-divider>
          <el-button type="primary" icon="Search" @click="getHuanZheXinXiClick">查询</el-button>
          <el-button type="primary" icon="RefreshLeft" @click="getXuQueFeiYiZhuClick">刷新</el-button>
        </el-col>
        <el-col>
          排序：
          <el-select v-model="queryTerm.fenLei" style="width: 100px; margin: auto 10px auto 10px">
            <el-option :value="0" label="病区"></el-option>
            <el-option :value="1" label="执行人"></el-option>
          </el-select>
          <el-button type="success" @click="baoCunYiZhuQueFeiClick" icon="Upload" :disabled="queryTerm.liShi === 1"> 保存
          </el-button>
          <el-divider direction="vertical"></el-divider>
          <el-radio-group v-model="queryTerm.liShi" @change="getHuanZheXinXiClick">
            <el-radio-button :label="0">未确认</el-radio-button>
            <el-radio-button :label="1">历史</el-radio-button>
          </el-radio-group>
          <el-divider direction="vertical"></el-divider>
          <el-button type="warning" @click="chaoZuoZhiNan = true">操作指南</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-switch
              v-show="queryTerm.liShi === 1"
              v-model="zhiKanZiJi"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="只看自己"
              inactive-text="全部"
              :active-value="true"
              :inactive-value="false"
          >
          </el-switch>
        </el-col>
        <el-col>
          <div v-show="queryTerm.liShi === 0">
            <el-table :data="huanZheYiZhuFeiYongData" :height="winHeight / 1.15" stripe highlight-current-row
                      @cell-click="lingShiQueFeiShuJuClick" ref="tableRef">
              <el-table-column prop="name" label="姓名" width="90">
                <template #default="scope">
                  <el-button size="small" :type="scope.row.shiFouYouChuYuanYiZhu === 0 ? 'success' : 'danger'"
                             style="width: 100px"
                  ><span style="font-size: 20px">{{ scope.row.name }}</span></el-button
                  >
                </template>
              </el-table-column>
              <el-table-column prop="inpatientNo" label="住院号" width="90"></el-table-column>
              <el-table-column prop="admissTimes" label="住院次数" width="90"></el-table-column>
              <el-table-column prop="bedNo" label="床号" width="50"></el-table-column>
              <el-table-column prop="sex" label="性别">
                <template #default="scope">
                  {{ cptSex(scope.row.sex) }}
                </template>
              </el-table-column>
              <el-table-column prop="admissDate" label="住院日期"></el-table-column>
              <el-table-column prop="responceTypeName" label="医保身份"></el-table-column>
              <el-table-column prop="wardName" label="病区"></el-table-column>
              <el-table-column prop="totalCharge" label="总费用"></el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <span v-html="chaoZuo(scope.row.list)"></span>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                background
                @current-change="changeYiZhuQueFei"
                :current-page="queryTerm.currentPage"
                :page-size="queryTerm.pageSize"
                layout=" prev, pager, next,total"
                :total="queryTerm.total"
                style="margin-top: 5px"
                :pager-count="5"
            ></el-pagination>
          </div>
          <div v-show="queryTerm.liShi === 1">
            <el-table
                :data="liShiShuJu.list.slice((liShiShuJu.currentPage - 1) * liShiShuJu.pageSize, liShiShuJu.currentPage * liShiShuJu.pageSize)"
                :height="winHeight / 1.15"
                stripe
                highlight-current-row
                ref="liShiShuJuRef"
            >
              <el-table-column label="患者姓名" prop="name">
                <template #default="scope">
                  <el-button size="small" :type="scope.row.color" style="width: 100px"
                  ><span style="font-size: 20px">{{ scope.row.name }}</span></el-button
                  >
                </template>
              </el-table-column>
              <el-table-column label="住院号" prop="inpatientNo"></el-table-column>
              <el-table-column label="住院次数" prop="admissTimes"></el-table-column>
              <el-table-column label="医嘱号" prop="actOrderNo"></el-table-column>
              <el-table-column label="医嘱时间" prop="occTime" width="70"></el-table-column>
              <el-table-column label="项目名称" prop="chargeName"></el-table-column>
              <el-table-column label="金额" prop="chargeFee"></el-table-column>
              <el-table-column label="数量" prop="orderCount"></el-table-column>
              <el-table-column label="医生姓名" prop="docotrName"></el-table-column>
              <el-table-column label="操作人" prop="opIdName"></el-table-column>
              <el-table-column label="操作时间" prop="opDate" width="70"></el-table-column>
              <el-table-column label="操作内容" prop="chargeStatus">
                <template #default="scope">
                  <span v-html="yiZhuZhuangTai(scope.row.chargeStatus)"></span>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                background
                @current-change="liShiShuJuFanYe"
                :current-page="liShiShuJu.currentPage"
                :page-size="liShiShuJu.pageSize"
                layout=" prev, pager, next,total"
                :total="liShiShuJu.list.length"
                style="margin-top: 5px"
                :pager-count="5"
            ></el-pagination>
          </div>
        </el-col>
      </el-row>
    </el-main>
    <el-drawer v-model="xiangXiYiZhuXinXiDrawer" direction="ltr" size="70%" title="患者医嘱的详细信息">
      <div style="margin: auto 20px auto 20px">
        <el-descriptions :title="lingShiQueFeiShuJu.name" border>
          <template #extra>
            <el-button type="success" @click="baoCunYiZhuQueFeiClick" icon="Upload" :disabled="queryTerm.liShi === 1">
              保存
            </el-button>
          </template>
          <el-descriptions-item label="住院号">{{ lingShiQueFeiShuJu.inpatientNo }}</el-descriptions-item>
          <el-descriptions-item label="姓名">
            <el-tag size="small" style="font-size: 24px">{{ lingShiQueFeiShuJu.name }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="性别">{{ cptSex(lingShiQueFeiShuJu.sex) }}</el-descriptions-item>
          <el-descriptions-item label="床号">{{ lingShiQueFeiShuJu.bedNo }}</el-descriptions-item>
          <el-descriptions-item label="医保身份">{{ lingShiQueFeiShuJu.responceTypeName }}</el-descriptions-item>
          <el-descriptions-item label="病区">{{ lingShiQueFeiShuJu.wardName }}</el-descriptions-item>
        </el-descriptions>
        <el-table
            :data="lingShiQueFeiShuJu.list.slice((lingShiQueFeiShuJu.currentPage - 1) * lingShiQueFeiShuJu.pageSize, lingShiQueFeiShuJu.currentPage * lingShiQueFeiShuJu.pageSize)"
            highlight-current-row
            stripe
            class="qf_table"
            :height="360">
          <el-table-column label="医嘱信息">
            <el-table-column prop="actOrderNo" label="医嘱号"></el-table-column>
            <el-table-column prop="occTime" label="医嘱日期" width="80"></el-table-column>
            <el-table-column prop="chargeCode" label="项目编码"></el-table-column>
            <el-table-column prop="chargeName" label="项目名称"></el-table-column>
            <el-table-column prop="docotrName" label="医生"></el-table-column>
            <el-table-column prop="orderCount" label="数量"></el-table-column>
            <el-table-column prop="chargeFee" label="单价"></el-table-column>
            <el-table-column label="金额">
              <template #default="scope">
                {{ (scope.row.chargeFee * scope.row.orderCount).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
              <template #default="scope">
                <el-radio-group v-model="scope.row.chargeStatus"
                                :fill="scope.row.chargeStatus === '1' ? '#67C23A' : scope.row.chargeStatus === '2' ? '#F56C6C' : '#909399'">
                  <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-group>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
        <el-pagination
            background
            @current-change="lingShiFanYe"
            @size-change="handleSizeChange"
            :current-page="lingShiQueFeiShuJu.currentPage"
            :page-size="lingShiQueFeiShuJu.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[8, 20, 30, 100]"
            :total="lingShiQueFeiShuJu.total"
            style="margin-top: 5px"
            :pager-count="5"
        ></el-pagination>
      </div>
    </el-drawer>
    <el-dialog v-model="chaoZuoZhiNan" title="操作指南(*^▽^*)" width="1000px">
      <div id="jinRiShuJuTuXin" style="width: 100%; height: 300px"></div>
      1、输入住院号，点击查询即可查询出该住院患者的信息，同理病区也是一样选择的病区就只会查询该病区的患者，住院号和病区二选一。
      <br/>
      <br/>
      2、排序：默认根据病区来排，选择了执行人后会根据算法来把当前登陆的人员，执行过最多的患者来排到靠前的位置。
      <br/><br/>
      3、未确认和历史：默认会查询患者未确认的项目，点击历史后一定要选择时间，该时间是医嘱的执行时间，默认会查询当天的时间，（提示选择时间的跨度建议不要过长，可能会导致数据加载慢。）同时查询历史时
      也可以使用住院号和病区来查询。
      <br/>
      <br/>
      4、患者姓名：有出院医嘱会显示为红色，无则显示绿色。
      <br/>
      <br/>
      <span style="color: red">
        5、现在无需点击患者姓名，直接点击该栏会弹出抽屉，患者基本信息会显示在上方，请按照需求来选择对应的操作，默认每页显示八条，表格中的分页按钮，跳转至上一页或下一页。
        点击抽屉外的任意位置即可消失，或点击保存旁边的关闭按钮。
      </span>
      <br/><br/>
      6、分页：该分页指页面下方的分页，点击下一页后，且没有点击保存，那么您此前的操作将会丢失，请在分页之前（如果有操作）点击保存（小表格中点击分页不会出现该情况）。
      <br/><br/>
      7、保存：在确定数据正确后，点击保存（数据一旦，保存成功就没有回头路了，请认真仔细的确认），<span style="color: red">点击弹出来的抽屉中的保存也是一样的效果。（新增）</span>
      <br/><br/>
      8、错误：在点击保存后，系统会自动接受患者的费用，如出错会在右上角，出现提示，可以请对应病区的护士在出院结算页面中点击费用接受重算按钮即可，或在老系统中护士打印费用清单时，会自动接收。
      <br/><br/>
      9、如有新的需求或出现未知的意外可联系管理员，如是操作失误后果自负（我觉得我已经写的很详细了，各种提示都有，都是简单的操作，还出现操作失误那就没得办法了）
      (>ω･* )ﾉ
    </el-dialog>
  </el-container>
</template>

<script>
import {onMounted, ref, watch} from 'vue'
import {
  getXuQueFeiYiZhu,
  baoCunYiZhuQueFeiShuJu,
  huoQuLiShiQueFeiYiZhu
} from '../../api/zhu-yuan-yi-ji/que-ren-yi-zhu-shou-fei'
import {getWard} from '@/api/inpatient/xiang-mu-lu-ru'
import {cptSex} from '@/utils/computed'
import store from '@/store'
import {getDate, getDateRangeFormatDate} from '@/utils/date'
import {ElMessage, ElMessageBox} from 'element-plus'
import {shortcuts} from '@/data/shortcuts'
import {barUtils} from '@/utils/echarts-utils'

export default {
  setup() {
    const windowSize = store.state.app.windowSize
    const winHeight = windowSize.h

    const dept = store.state.user.info.deptCode
    const queryTerm = ref({
      inpatientNo: '',
      admissTimes: 0,
      wardCode: '',
      execUnit: dept,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      fenLei: 0,
      startTimeString: '',
      endTimeString: '',
      liShi: 0,
    })
    const tableRef = ref(null)
    const liShiShuJuRef = ref(null)
    const chaoZuoZhiNan = ref(true)
    const zhiKanZiJi = ref(true)

    const liShiShuJu = ref({
      pageSize: 50,
      currentPage: 1,
      list: [],
    })

    const xiangXiYiZhuXinXiDrawer = ref(false)

    // 患者信息
    const patient = ref({})
    // 病房信息
    const wardData = ref([])
    // 需要确费的信息
    const huanZheYiZhuFeiYongData = ref([])
    // 操作
    const chargeStatusData = ref([
      {code: '1', name: '确认'},
      {code: '2', name: '取消'},
      {code: '3', name: '不操作'},
    ])

    const dateRange = ref([new Date(), new Date()])

    /**
     * 这个是查询当前病人的
     */
    const getHuanZheXinXiClick = () => {
      let date = getDateRangeFormatDate(dateRange.value)
      queryTerm.value.startTimeString = date.startTime
      queryTerm.value.endTimeString = date.endTime
      queryTerm.value.execUnit = dept
      queryTerm.value.currentPage = 1
      queryTerm.value.pageSize = 20
      if (queryTerm.value.liShi === 0) {
        getXuQueFeiYiZhu(queryTerm.value)
            .then((res) => {
              huanZheYiZhuFeiYongData.value = res.records
              queryTerm.value.total = res.total
              qingKongLingShiShuJu()
            })
            .catch(() => {
              huanZheYiZhuFeiYongData.value = []
              queryTerm.value.total = 0
            })
      } else {
        huoQuLiShiQueFeiYiZhu(
            queryTerm.value.startTimeString,
            queryTerm.value.endTimeString,
            queryTerm.value.inpatientNo,
            queryTerm.value.wardCode,
            queryTerm.value.execUnit,
            queryTerm.value.fenLei,
            zhiKanZiJi.value ? store.state.user.info.code : ''
        ).then((res) => {
          liShiShuJu.value.list = res
          if (liShiShuJu.value.list.length > 0) {
            let patNo = liShiShuJu.value.list[0].inpatientNo
            let color = 'success'
            liShiShuJu.value.list.forEach((item) => {
              if (item.inpatientNo === patNo) {
                item.color = color
              } else {
                color = color === 'success' ? 'warning' : 'success'
                item.color = color
                patNo = item.inpatientNo
              }
            })
          }
          liShiShuJu.value.currentPage = 1
        })
      }
    }

    /**
     * 这个是刷新页面用的
     */
    const getXuQueFeiYiZhuClick = () => {
      queryTerm.value.inpatientNo = ''
      queryTerm.value.admissTimes = 0
      queryTerm.value.wardCode = ''
      queryTerm.value.execUnit = dept
      queryTerm.value.currentPage = 1
      queryTerm.value.pageSize = 20
      queryTerm.value.startTimeString = ''
      queryTerm.value.endTimeString = ''
      getXuQueFeiYiZhu(queryTerm.value).then((res) => {
        huanZheYiZhuFeiYongData.value = res.records
        queryTerm.value.total = res.total
      })
    }

    watch(huanZheYiZhuFeiYongData, (orlData, newData) => {
      let echartsXdata = []
      let echartsYdata = []
      huanZheYiZhuFeiYongData.value.forEach((item) => {
        if (item.shiFouYouChuYuanYiZhu > 0) {
          let a = {
            value: item.list.length,
            itemStyle: {
              color: '#a90000',
            },
          }
          echartsYdata.push(a)
        } else {
          echartsYdata.push(item.list.length)
        }
        echartsXdata.push(item.name)
      })
      barUtils(jinRiShuJuTuXin, '仅对当前页数据有效', echartsXdata, echartsYdata)
    })

    /**
     * 这个是在点击了 下一页触发的
     */
    const changeYiZhuQueFei = (val) => {
      queryTerm.value.currentPage = val
      getXuQueFeiYiZhu(queryTerm.value).then((res) => {
        tableRef.value.$refs.bodyWrapper.scrollTop = 0
        queryTerm.value.total = res.total
        huanZheYiZhuFeiYongData.value = res.records
      })
    }

    /**
     * 在这里保存数据
     */
    const baoCunYiZhuQueFeiClick = () => {
      if (queryTerm.value.liShi === 1)
        return ElMessage.error({
          message: '历史数据无法操作。',
        })
      let queRenCount = 0
      let quXiaoCount = 0
      for (let i = 0; i < huanZheYiZhuFeiYongData.value.length; i++) {
        for (let a = 0; a < huanZheYiZhuFeiYongData.value[i].list.length; a++) {
          if (huanZheYiZhuFeiYongData.value[i].list[a].chargeStatus === '1') {
            queRenCount += 1
          } else if (huanZheYiZhuFeiYongData.value[i].list[a].chargeStatus === '2') {
            quXiaoCount += 1
          }
        }
      }
      ElMessageBox.confirm(`请确认数据其中<br><span style='color:#67C23A'>确认【${queRenCount}】条</span><br><span style='color:#F56C6C'>取消【${quXiaoCount}】条</span>`, '提示', {
        type: 'warning',
        dangerouslyUseHTMLString: true,
      })
          .then(() => {
            let shaungChuanData = {
              list: huanZheYiZhuFeiYongData.value,
              execUnit: store.state.user.info.deptCode,
            }
            baoCunYiZhuQueFeiShuJu(shaungChuanData).then((res) => {
              xiangXiYiZhuXinXiDrawer.value = false
              getXuQueFeiYiZhuClick()
            })
          })
          .catch(() => {
          })
    }

    const qingKongLingShiShuJu = () => {
      lingShiQueFeiShuJu.value.list = []
      lingShiQueFeiShuJu.value.currentPage = 1
      lingShiQueFeiShuJu.value.pageSize = 40
      lingShiQueFeiShuJu.value.total = 0
      lingShiQueFeiShuJu.value.name = ''
      lingShiQueFeiShuJu.value.sex = 1
      lingShiQueFeiShuJu.value.bedNo = 0
      lingShiQueFeiShuJu.value.responceTypeName = ''
      lingShiQueFeiShuJu.value.wardName = ''
    }

    const lingShiQueFeiShuJu = ref({
      list: [],
      currentPage: 1,
      pageSize: 40,
      total: 0,
      name: '',
      sex: 0,
      bedNo: 0,
      responceTypeName: '',
      wardName: '',
    })

    const lingShiQueFeiShuJuClick = (row) => {
      if (!(lingShiQueFeiShuJu.value.inpatientNo === row.inpatientNo && lingShiQueFeiShuJu.value.admissTimes === row.admissTimes)) {
        lingShiQueFeiShuJu.value = row
        let val = row.list
        lingShiQueFeiShuJu.value.list = val
        lingShiQueFeiShuJu.value.currentPage = 1
        lingShiQueFeiShuJu.value.pageSize = 40
        lingShiQueFeiShuJu.value.total = val.length
      }
      xiangXiYiZhuXinXiDrawer.value = true
    }

    const lingShiFanYe = (val) => {
      lingShiQueFeiShuJu.value.currentPage = val
    }

    const handleSizeChange = (val) => {
      lingShiQueFeiShuJu.value.pageSize = val
    }

    const liShiShuJuFanYe = (val) => {
      liShiShuJuRef.value.$refs.bodyWrapper.scrollTop = 0
      liShiShuJu.value.currentPage = val
    }

    onMounted(() => {
      getWard().then((res) => {
        wardData.value = res
      })
      setTimeout(() => {
        barUtils(jinRiShuJuTuXin, '仅对当前页数据有效', [], [])
      }, 100)

      getXuQueFeiYiZhuClick()
    })

    return {
      patient,
      getHuanZheXinXiClick,
      wardData,
      cptSex,
      queryTerm,
      getXuQueFeiYiZhuClick,
      huanZheYiZhuFeiYongData,
      winHeight,
      changeYiZhuQueFei,
      chargeStatusData,
      getDate,
      baoCunYiZhuQueFeiClick,
      dateRange,
      chaoZuo,
      shortcuts,
      lingShiQueFeiShuJu,
      lingShiQueFeiShuJuClick,
      lingShiFanYe,
      yiZhuZhuangTai,
      chaoZuoZhiNan,
      xiangXiYiZhuXinXiDrawer,
      handleSizeChange,
      tableRef,
      liShiShuJu,
      liShiShuJuFanYe,
      liShiShuJuRef,
      zhiKanZiJi,
    }
  },
}

function chaoZuo(val) {
  let quXiao = 0
  let queRen = 0
  for (let i = 0; i < val.length; i++) {
    if (val[i].chargeStatus === '1') {
      queRen += 1
    } else if (val[i].chargeStatus === '2') {
      quXiao += 1
    }
  }
  if (quXiao > 0 && queRen == 0) {
    return `<span style='color:#F56C6C;font-size: 20px;'>取消【${quXiao}】</span>`
  } else if (quXiao == 0 && queRen > 0) {
    return `<span style='color:#67C23A;font-size: 20px;'>确认【${queRen}】</span>`
  } else if (quXiao > 0 && queRen > 0) {
    return `<span style='color:#67C23A;font-size: 20px;'>确认【${queRen}】</span><br><span style='color:#F56C6C;font-size: 20px;'>取消【${quXiao}】</span>`
  }
  return ''
}

function yiZhuZhuangTai(val) {
  switch (val) {
    case '0':
      return '<span style="color:#67C23A;font-size: 24px">上账</span>'
    case '1':
      return ' <span style="color:#E6A23C;font-size: 24px">确认但未上账</span>'
    case '2':
      return ' <span style="color:#F56C6C;font-size: 24px">取消</span>'
    case '5':
      return '科室确认'
    case '6':
      return '科室录入'
    case '7':
      return '科室撤销'
    case '8':
      return '科室录入粗项（检验费）'
    default:
      return '未知'
  }
}
</script>

<style scoped lang="scss">
.qf_table {

  :deep(.el-table__inner-wrapper .el-table__body-wrapper ) {
    overflow: scroll;
  }

}
</style>
