<template>
  <page-layer>
    <template #header>
      <el-input
          v-model="inpatientNo"
          clearable
          placeholder="在此输入住院号"
          prefix-icon="Search"
          size="small"
          style="width: 300px"
          @blur="inpatientNo = $event.target.value.trim()"
          @keyup.enter="queryClick"
      >
        <template #prepend>住院号</template>
      </el-input>
      <el-button style="margin-left: 10px" type="primary" @click="queryClick">查询患者信息</el-button>
      <el-divider direction="vertical"></el-divider>
      <el-input
          v-model="serialNo"
          clearable
          onkeyup="this.value=this.value.replace(/[^\d]/g,'') "
          placeholder="在此输入机制号"
          prefix-icon="Search"
          size="small"
          style="width: 300px"
          @blur="serialNo = $event.target.value.trim()"
          @keyup.enter="querySerialNo"
      >
        <template #prepend>机制号</template>
      </el-input>
      <el-select v-model="liShiFlag" size="small">
        <el-option v-for="item in chaKanLiShi" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      <el-button style="margin-left: 10px" type="primary" @click="querySerialNo">查询机制号信息</el-button>
      <el-button style="margin-left: 10px" type="warning" @click="huanZheFeiYongDrawer = true">查看患者费用</el-button>
      <el-button style="margin-left: 10px" type="success" @click="baoCunClick">保存</el-button>
    </template>
    <template #main>
      <div>
        <el-descriptions border title="基本信息">
          <el-descriptions-item>
            <template #label>
              <i class="el-icon-user"></i>
              患者姓名
            </template>
            {{ huanZheXinXi.name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <i class="el-icon-user"></i>
              住院次数
            </template>
            {{ huanZheXinXi.admissTimes }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <i class="el-icon-user-solid"></i>
              性别
            </template>
            {{ cptSex(huanZheXinXi.sex) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <i class="el-icon-house"></i>
              床号
            </template>
            {{ huanZheXinXi.bedNo }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <i class="el-icon-s-home"></i>
              病房
            </template>
            {{ huanZheXinXi.wardName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <i class="el-icon-date"></i>
              入院日期
            </template>
            {{ huanZheXinXi.admissDate }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <i class="el-icon-tickets"></i>
              身份
            </template>
            {{ huanZheXinXi.responceTypeName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <i class="el-icon-coin"></i>
              总费用
            </template>
            {{ huanZheXinXi.totalCharge }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <i class="el-icon-coin"></i>
              余额
            </template>
            <span style="color: red">{{ huanZheXinXi.balance }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      收费日期：
      <el-date-picker v-model="chargeDate" type="datetime"></el-date-picker>
      执行科室：
      <el-select
          v-model="huanZheXinXi.execUnit"
          :remote-method="remoteMethodHuiZhenKeShi"
          clearable
          filterable
          placeholder="根据拼音首字母查找"
          remote
          value-key="code">
        <el-option v-for="item in deptList"
                   :key="item.code"
                   :value="item.code"
                   :label="item.name">
          <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
          <el-divider direction="vertical"></el-divider>
          <span>{{ item.name }}</span>
        </el-option>
      </el-select>
      <div style="width: 100%">
        <div style="float: left; width: 45%">
          <el-table ref="multipleTable" :data="mzXinXiList" :height="windowHeight / 1.4" highlight-current-row
                    @selection-change="mzSelectChecked">
            <el-table-column label="门诊发票信息">
              <el-table-column label="项目名称" prop="itemName"></el-table-column>
              <el-table-column label="收费编码" prop="chargeCodeMx"></el-table-column>
              <el-table-column label="数量" prop="chargeQuantity"></el-table-column>
              <el-table-column label="单价" prop="unitPrice"></el-table-column>
              <el-table-column label="金额" prop="chargeFee"></el-table-column>
              <el-table-column label="选择" type="selection" width="60"></el-table-column>
            </el-table-column>
          </el-table>
          <el-tag>合计:{{ mzSum }}</el-tag>
        </div>
        <div :style="{ lineHeight: windowHeight / 1.4 + 'px' }"
             style="width: 9%; float: left; margin-left: 4px; text-align: center">
          <el-button icon="Right" type="primary"></el-button>
        </div>
        <div style="float: right; width: 45%">
          <el-table :data="zyXinXiList" :height="windowHeight / 1.4" stripe>
            <el-table-column label="住院收费项目">
              <el-table-column label="项目名称" prop="itemName"></el-table-column>
              <el-table-column label="收费编码" prop="chargeCodeMx"></el-table-column>
              <el-table-column label="数量" prop="chargeQuantity"></el-table-column>
              <el-table-column label="单价" prop="unitPrice"></el-table-column>
              <el-table-column label="金额" prop="chargeFee"></el-table-column>
            </el-table-column>
          </el-table>
          <el-tag>合计:{{ zySum }}</el-tag>
        </div>
      </div>
      <el-drawer v-model="huanZheFeiYongDrawer" size="50%" title="查看患者通过急门诊转入的费用">
        <div style="margin-left: 20px">
          <el-input
              v-model="inpatientNo"
              clearable
              placeholder="住院号"
              style="width: 200px"
              @blur="inpatientNo = $event.target.value.trim()"
              @keyup.enter="getZyJiMenZhenZhuangRuFeiYongClick"
          >
            <template #prepend>住院号</template>
          </el-input>
          <el-divider direction="vertical"></el-divider>
          项目名称：
          <el-select v-model="chargeCodeMX" :remote-method="remoteMethodEntryName" clearable filterable
                     placeholder="根据拼音首字母查找" remote>
            <el-option v-for="item in entryNameList" :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" @click="getZyJiMenZhenZhuangRuFeiYongClick">查询</el-button>
          <el-table :data="zyDetailChargeList" :height="windowHeight / 1.1">
            <el-table-column label="住院号" prop="inpatientNo"></el-table-column>
            <el-table-column label="流水号" prop="detailSn"></el-table-column>
            <el-table-column label="收费日期" prop="chargeDate" width="80"></el-table-column>
            <el-table-column label="收费代码" prop="chargeCode"></el-table-column>
            <el-table-column label="项目名称" prop="chargeCodeName" show-overflow-tooltip></el-table-column>
            <el-table-column label="费用录入日期" prop="genTime" width="80"></el-table-column>
            <el-table-column label="金额" prop="chargeFee"></el-table-column>
            <el-table-column label="数量" prop="chargeAmount"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-popconfirm
                    cancel-button-text="取消"
                    confirm-button-text="删除"
                    icon="Info"
                    iconColor="red"
                    title="是否删除该费用"
                    @confirm="shanChuFeiYongClick(scope.$index, scope.row)"
                >
                  <template #reference>
                    <el-button type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              :page-size="huanZheFeiYongPageSize"
              :total="huanZheFeiYongTotal"
              background
              layout="prev, pager, next, total"
              @current-change="huanZheFeiYongCurrentChange"
          ></el-pagination>
          <el-tag style="margin-left: 7px">合计：{{ huanZheFeiYongZongHe }}</el-tag>
        </div>
      </el-drawer>
    </template>
  </page-layer>
</template>

<script setup name="TransferInOfExpenses">
import {ref} from '@vue/reactivity'
import {
  baoCunHuanZheZhuYuanFeiYong,
  getSerialNo,
  getZyJiMenZhenZhuangRuFeiYong,
  queryEntryName,
  queryHuanZhe,
  shanChuFeiYong
} from '@/api/inpatient/transfer-in-of-expenses'
import {cptSex} from '@/utils/computed'
import store from '@/store'
import {computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {compareDate, formatDatetime} from '@/utils/date'
import {getServerDateApi, queryDept} from '@/api/public-api'
import {stringNotBlank} from '@/utils/blank-utils'
import PageLayer from "@/layout/PageLayer";

const windowSize = store.state.app.windowSize
const windowHeight = windowSize.h

//查询条件
//住院号
const inpatientNo = ref('') // 016868
//机制号
const serialNo = ref('') // 11516328
//是否查看历史记录
const liShiFlag = ref(0)
//收费代码
const chargeCodeMX = ref('')
// 住院次数
const admissTimes = ref('')

const huanZheXinXi = ref({})

const mzXinXiList = ref([])
const zyXinXiList = ref([])

//查询患者信息
const queryClick = async () => {
  if (!inpatientNo.value) {
    ElMessage({
      type: 'warning',
      message: '请先输入患者住院号',
      showClose: true,
      duration: 2500,
    })
    return
  }
  chargeDate.value = await getServerDateApi()
  deptList.value = [{code: '1070000', name: '急诊科'}]
  queryHuanZhe(inpatientNo.value).then((res) => {
    huanZheXinXi.value = res
    admissTimes.value = res.admissTimes
    huanZheXinXi.value.execUnit = '1070000'
  })
}

//查询机制号
const querySerialNo = () => {
  if (!serialNo.value) {
    ElMessage({
      type: 'warning',
      message: '请先输入机制号',
      showClose: true,
      duration: 2500,
    })
    return
  }
  getSerialNo(serialNo.value, liShiFlag.value)
      .then((res) => {
        mzXinXiList.value = res
      })
      .catch(() => {
        mzXinXiList.value = []
      })
}

//定义用来删除 多选框的选中状态 以及点击选中多选框
const multipleTable = ref(null)
//点击多选框，把里面的内容添加进去
const mzSelectChecked = (selection, row) => {
  zyXinXiList.value = selection
}

//门诊发票信息 金额总和
let mzSum = computed(() => {
  let sum = 0
  mzXinXiList.value.forEach((item) => {
    sum += item.unitPrice * item.chargeQuantity
  })
  return sum.toFixed(2)
})
//住院收费项目 金额总和
let zySum = computed(() => {
  let sum = 0
  zyXinXiList.value.forEach((item) => {
    sum += item.unitPrice * item.chargeQuantity
  })
  return sum.toFixed(2)
})

const huanZheFeiYongDrawer = ref(false)

const HuanZheFeiYongCurrentPage = ref(1)
const huanZheFeiYongPageSize = ref(10)
const huanZheFeiYongTotal = ref(0)
const huanZheFeiYongZongHe = ref(0)

//住院患者的费用信息
const zyDetailChargeList = ref([])

let resInpatientNo = null
let resChargeCodeMx = null

//点击查询患者 门急诊转入的费用 在定义两个字段，用来分页的时候就算输入框没值了 也能拿到数据
const getZyJiMenZhenZhuangRuFeiYongClick = () => {
  if (!admissTimes.value) {
    ElMessage.warning({
      message: '请先查询出患者信息',
      showClose: true,
      duration: 2500,
    })
    return
  }
  //通过住院号和项目编码 获取住院门诊装入费用
  getZyJiMenZhenZhuangRuFeiYong(inpatientNo.value, chargeCodeMX.value, admissTimes.value, HuanZheFeiYongCurrentPage.value, huanZheFeiYongPageSize.value).then((res) => {
    resInpatientNo = inpatientNo.value
    resChargeCodeMx = chargeCodeMX.value
    zyDetailChargeList.value = res.data
    huanZheFeiYongTotal.value = res.total
    huanZheFeiYongZongHe.value = res.sum
  })
}

//点击上下分页触发的事件
const huanZheFeiYongCurrentChange = (val) => {
  HuanZheFeiYongCurrentPage.value = val
  if (zyDetailChargeList.value) {
    getZyJiMenZhenZhuangRuFeiYong(resInpatientNo, resChargeCodeMx, admissTimes.value, HuanZheFeiYongCurrentPage.value, huanZheFeiYongPageSize.value).then((res) => {
      zyDetailChargeList.value = res.data
      huanZheFeiYongTotal.value = res.total
    })
  }
}

//删除住院收费项目 前端删除 后端也删除 只是不执行一个查找的动作了
const shanChuFeiYongClick = (index, val) => {
  shanChuFeiYong(val).then((res) => {
    zyDetailChargeList.value.splice(index, 1)
  })
}
//点击保存触发的事件
const baoCunClick = () => {
  if (compareDate(huanZheXinXi.value.admissDate, chargeDate.value)) {
    return ElMessage.error('费用发生时间不能在入院时间之前。')
  }
  if (stringNotBlank(huanZheXinXi.value.disDate) && compareDate(chargeDate.value, huanZheXinXi.value.disDate)) {
    return ElMessage.error('费用发生时间不能在出院时间之后。')
  }
  huanZheXinXi.value.chargeDate = formatDatetime(chargeDate.value)
  if (typeof huanZheXinXi.value.inpatientNo === 'undefined') {
    ElMessage({
      type: 'warning',
      message: '请先选择患者',
      showClose: true,
      duration: 2500,
    })
    return
  }
  if (zyXinXiList.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请先选择要添加的费用',
      showClose: true,
      duration: 2500,
    })
    return
  }
  huanZheXinXi.value.list = zyXinXiList.value
  if (huanZheXinXi.value.chargeDate === '') {
    return ElMessage.error({
      message: '请选择日期',
    })
  }
  console.log(huanZheXinXi.value);
  for (let i = 0; mzXinXiList.value.length; i++) {
    if (huanZheXinXi.value.name !== mzXinXiList.value[i].patientName && typeof mzXinXiList.value[i].patientName !== 'undefined') {
      return ElMessageBox.confirm('', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        type: 'warning',
        message: `门诊病人姓名【'${mzXinXiList.value[i].patientName}  '】住院病人姓名【'  ${huanZheXinXi.value.name}  '】不一致,是否继续？<br>收费日期：${huanZheXinXi.value.chargeDate}`,
      })
          .then(() => {
            baoCunHuanZheZhuYuanFeiYong(huanZheXinXi.value).then((res) => {
              zyXinXiList.value = []
              mzXinXiList.value = []
            })
          })
          .catch(() => {
          })
    } else if (huanZheXinXi.value.name === mzXinXiList.value[i].patientName && typeof mzXinXiList.value[i].patientName !== 'undefined') {
      return ElMessageBox.confirm('', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        type: 'warning',
        message: `收费日期：${huanZheXinXi.value.chargeDate}`,
      })
          .then(() => {
            baoCunHuanZheZhuYuanFeiYong(huanZheXinXi.value).then((res) => {
              zyXinXiList.value = []
              mzXinXiList.value = []
            })
          })
          .catch(() => {
          })
    }
  }
}
//项目名称 数组
const entryNameList = ref([])

//远程搜索项目名称
const remoteMethodEntryName = (val) => {
  if (val.length >= 2) {
    queryEntryName(val).then((res) => {
      entryNameList.value = res
    })
  }
}

const chargeDate = ref(new Date())

// 科室
const deptList = ref([])
//远程搜索会诊科室
const remoteMethodHuiZhenKeShi = (val) => {
  if (val !== '' && val.length > 1) {
    queryDept(val)
        .then((res) => {
          deptList.value = res
        })
        .catch(() => {
          deptList.value = []
        })
  }
}


let chaKanLiShi = [
  {code: 0, name: '不查看历史记录'},
  {code: 1, name: '查看历史记录'},
]
</script>

<style></style>
