<template>
  <el-container>
    <el-aside width="195px">
      <HuoQuMuBan @selectionFeiYong="xuanZeXiangMuTable"></HuoQuMuBan>
    </el-aside>
    <el-main>
      <el-button icon="StarOff" type="warning" @click="baoCunMuBanDialog = true">存模板</el-button>
      <el-button icon="Upload" type="primary" @click="shangChuanXiangMu">保存</el-button>
      <el-button icon="Plus" type="success" @click="xinZhengXiangMuDialog = true">新增</el-button>
      <el-select v-model="zhiXingKeShi" filterable style="width: 120px; margin: 0px 10px 0px 10px">
        <el-option v-for="item in deptData" :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-button icon="Edit" type="warning" @click="xieGaiZhiXingKeShi">修改执行科室</el-button>
      <span v-if="panDuanSFWeiShouShuShi()">
        病区：
        <el-select v-model="queryWard" filterable style="width: 120px" @change="getBingQuDuiYingKeShiChange">
          <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-select v-model="queryDept" filterable style="width: 120px">
          <el-option v-for="item in xiaoKeShiList" :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-input
            v-model.number="ssCode"
            clearable
            placeholder="请输入手术编码"
            style="width: 120px"/>
      </span>
      <el-tag type="danger"> 项目总价：{{ xiangMuZongJia }}</el-tag>
      <el-table :data="feiYongShuJu" :height="tableHeight - 27" highlight-current-row stripe style="margin-top: 10px">
        <el-table-column label="录入信息">
          <el-table-column label="是否自费" width="130">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.ybSelfFlag"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#ff4949"
                  active-text="自费"
                  inactive-color="#13ce66"
                  inactive-text="医保"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="医生" width="70px">
            <template #default="scope">
              <el-select v-model="scope.row.doctorCode" :remote-method="remoteMethodRenYuan" clearable filterable remote
                         style="width: 100px">
                <el-option v-for="item in renYuanList" :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>
            </template>
          </el-table-column>
          <el-table-column label="项目编码" prop="chargeCodeMx"></el-table-column>
          <el-table-column label="名称" prop="chargeName"></el-table-column>
          <el-table-column label="执行科室" prop="deptCode">
            <template #default="scope">
              <el-select v-model="scope.row.deptCode" filterable style="width: 90%">
                <el-option v-for="item in deptData" :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>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="chargeAmount"></el-table-column>
          <el-table-column label="数量" prop="amount" width="130">
            <template #default="scope">
              <el-input-number v-model="scope.row.amount" :min="0"
                               :precision="scope.row.serial === '00' ? 1 : 3"
                               style="width: 120px"/>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="金额">
          <template #default="scope">
            {{ (scope.row.chargeAmount * scope.row.amount).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="账单码" prop="billItemName"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" @click="shanChuXiangMuClick(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-dialog v-model="xinZhengXiangMuDialog" :width="1500" title="新增">
      搜索：
      <el-input v-model="chargeCodePy" style="width: 140px" @keyup.enter="rmChargePyCode"></el-input>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" @click="rmChargePyCode">查询</el-button>
      <el-divider direction="vertical"></el-divider>
      <el-switch
          v-model="xiangMuHuoYaoPinFlag"
          :active-value="1"
          :inactive-value="0"
          active-color="#409EFF"
          active-text="药品"
          inactive-color="#13ce66"
          inactive-text="项目"
      ></el-switch>
      <el-divider direction="vertical"></el-divider>
      <el-table
          :data="
          xiangMuHuoYaoPinShuJu.data.slice(
            (xiangMuHuoYaoPinShuJu.currentPage - 1) * xiangMuHuoYaoPinShuJu.pageSize,
            xiangMuHuoYaoPinShuJu.currentPage * xiangMuHuoYaoPinShuJu.pageSize
          )
        "
          :height="tableHeight / 1.2"
      >
        <el-table-column label="操作" width="40">
          <template #default="scope">
            <el-button text @click="danGeXiangMuBaoCun(scope.row)" type="primary">添加</el-button>
          </template>
        </el-table-column>
        <el-table-column label="项目编码" prop="chargeCodeMx"></el-table-column>
        <el-table-column label="项目名称" prop="chargeName"></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="spec"></el-table-column>
        <el-table-column label="执行科室" prop="execUnitName"/>
        <el-table-column label="单价" prop="chargeAmount"></el-table-column>
        <el-table-column label="数量" prop="amount"/>
        <el-table-column label="金额">
          <template #default="scope">
            {{ (scope.row.chargeAmount * scope.row.amount).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="账单码" prop="billItemName"></el-table-column>
        <el-table-column label="规格" prop="descriptions" show-overflow-tooltip></el-table-column>
        <el-table-column v-if="xiangMuHuoYaoPinFlag === 1" label="库存" prop="stockAmount"></el-table-column>
        <el-table-column v-if="xiangMuHuoYaoPinFlag === 1" label="医保类型" prop="yblx"></el-table-column>
      </el-table>
      <el-pagination
          :current-page="xiangMuHuoYaoPinShuJu.currentPage"
          :page-size="xiangMuHuoYaoPinShuJu.pageSize"
          :total="xiangMuHuoYaoPinShuJu.data.length"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="xinZhengSizeChange"
          @current-change="xinZhengCurrentChange"
      >
      </el-pagination>
    </el-dialog>
    <el-dialog v-model="baoCunMuBanDialog" title="保存模板">
      <el-row>
        <el-col :span="24">
          模板名称：
          <el-input v-model="cunMuBanPojo.name" maxlength="15" show-word-limit @blur="zhuanPinYin"></el-input>
        </el-col>
        <el-col :span="12">
          拼音码：
          <el-input v-model="cunMuBanPojo.pyCode" maxlength="8" show-word-limit></el-input>
        </el-col>
        <el-col :span="12">
          五笔码：
          <el-input v-model="cunMuBanPojo.dcode" maxlength="8" show-word-limit></el-input>
        </el-col>
        <!-- <el-col :span="12"> 排序码：<el-input v-model="cunMuBanPojo.paiXu" maxlength="7" show-word-limit></el-input> </el-col> -->
        <el-col :span="12">
          <el-button icon="Upload" style="margin-top: 10px" type="primary" @click="baoCunMuBan">保存</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </el-container>
</template>

<script setup>
import {computed, onMounted, ref, watch} from 'vue'
import {
  getBingQuDuiYingKeShi,
  getDept,
  getMuBanXinXi,
  getPyCode,
  getWard,
  queryDanGeXiangMu,
  shangChuanMuBan,
  xiangMuFeiYongShangChuan
} from '@/api/inpatient/xiang-mu-lu-ru'
import {getRenYuan} from '../../api/public-api.js'
import store from '@/store'
import {getDatetime} from '@/utils/date'
import {ElMessage, ElMessageBox} from 'element-plus'
import {clone} from '@/utils/clone'
import HuoQuMuBan from './HuoQuMuBan.vue'
import {stringIsBlank} from "@/utils/blank-utils";
import {BizException, ExceptionEnum} from "@/utils/BizException";


const props = defineProps({
  patient: {
    type: Object,
  },
})


const windowSize = store.state.app.windowSize
const tableHeight = windowSize.h - 170
const deptData = ref([])
const wardData = ref([])

// 手术编码
const ssCode = ref('')

const muBanCurrentPage = ref(1)
const muBanPageSize = ref(10)

const queryDept = ref('')
const queryWard = ref('')

const xiaoKeShiList = ref([])

const muBanHandleCurrentChange = (val) => {
  muBanCurrentPage.value = val
}
// 获取模板信息
const getMuBanXinXiClick = (row) => {
  getMuBanXinXi(row.name, row.opIdCode).then((res) => {
    muBanXiangQing.value = res
  })
}

// 获取模板的详情
const muBanXiangQing = ref([])

// 获取选择的数据
const xuanZeXiangMuTable = (param) => {
  let val = param.val
  for (let i = 0; i < val.length; i++) {
    if (chargeCode.value.indexOf(val[i].chargeCodeMx) === -1) {
      chargeCode.value.push(val[i].chargeCodeMx)
      val[i].deptCode = store.state.user.info.deptCode
      feiYongShuJu.value.push(val[i])
    }
  }
}

const chargeCode = ref([])

onMounted(() => {
  // 获取科室
  getDept().then((res) => {
    deptData.value = res
  })
  getWard().then((res) => {
    wardData.value = res
  })
})

const feiYongShuJu = ref([])

const shangChuanXiangMu = () => {

  if (operationRoom() && stringIsBlank(ssCode)) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "请填写手术编码。");
  }

  let shangChuanFeiYong = {
    // 这里又要反回来 就尼玛坑爹 我也不知道为什么
    dept: queryWard.value,
    ward: queryDept.value,
    inpatientNo: props.patient.inpatientNo,
    admissTimes: props.patient.admissTimes,
    zySerialNo: props.patient.zySerialNo,
    ssCode: ssCode.value,
    referPhysician: props.patient.referPhysician,
    list: feiYongShuJu.value,
    orderNo: 3,
    ledgerSn: props.patient.ledgerSn,
  };

  if (feiYongShuJu.value.length === 0) {
    return ElMessage.error('请先选择上传数据。')
  }

  //在此处上传
  ElMessageBox.confirm('共上传【' + feiYongShuJu.value.length + '】条', '请认真核对', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
  })
      .then(() => {
        xiangMuFeiYongShangChuan(shangChuanFeiYong).then(() => {
          feiYongShuJu.value = []
          chargeCode.value = []
        })
      })
      .catch(() => {
      })
}

const shanChuXiangMuClick = (val) => {
  feiYongShuJu.value.splice(val, 1)
  chargeCode.value.splice(val, 1)
}
// 新增项目或者药品
const xinZhengXiangMuDialog = ref(false)
// 判断查询药品还是项目
const xiangMuHuoYaoPinFlag = ref(0)
// 这个是远程查询数据后 保存
const xiangMuHuoYaoPinShuJu = ref({
  currentPage: 1,
  pageSize: 20,
  data: [],
})
// 远程查询的
const chargeCodePy = ref('')

/**
 * 远程搜索
 */
const rmChargePyCode = () => {
  if (chargeCodePy.value.length >= 2) {
    queryDanGeXiangMu(chargeCodePy.value, xiangMuHuoYaoPinFlag.value).then((res) => {
      xiangMuHuoYaoPinShuJu.value.data = res
    })
  }
}

const danGeXiangMuBaoCun = (val) => {
  let key
  if (xiangMuHuoYaoPinFlag.value === 1) {
    key = val.chargeCodeMx + val.serial
  } else {
    key = val.chargeCodeMx
  }
  if (chargeCode.value.indexOf(key) > -1) {
    return ElMessage.warning({
      message: '请勿重复录入',
      showClose: true,
    })
  } else {
    if (typeof val.deptCode === 'undefined') {
      val.deptCode = store.state.user.info.deptCode
    }
    feiYongShuJu.value.push(val)
    chargeCode.value.push(key)
    ElMessage.success({
      message: '添加成功',
      showClose: true,
    })
  }
}

const xiangMuZongJia = computed(() => {
  let sum = 0
  for (let i = 0; i < feiYongShuJu.value.length; i++) {
    sum += feiYongShuJu.value[i].chargeAmount * feiYongShuJu.value[i].amount
  }
  return sum.toFixed(2)
})

watch(
    () => props.patient,
    () => {
      // 这里刚好是反着的
      queryWard.value = props.patient.admissDept
      getBingQuDuiYingKeShiChange()
      setTimeout(() => {
        queryDept.value = props.patient.zkWard
      }, 100)
    }
)
// 以下是保存模板
const baoCunMuBanDialog = ref(false)

const cunMuBanPojo = ref({
  pyCode: '',
  dcode: '',
  name: '',
  paiXu: '',
  dept: '',
  deptCode: store.state.user.info.deptCode,
  list: [],
})

// 获取到保存模板的拼音码和五笔码
const zhuanPinYin = () => {
  if (cunMuBanPojo.value.name !== '') {
    getPyCode(cunMuBanPojo.value.name).then((res) => {
      cunMuBanPojo.value.pyCode = res.pyCode
      cunMuBanPojo.value.dcode = res.wbCode
    })
  }
}

const baoCunMuBan = () => {
  if (feiYongShuJu.value.length === 0) {
    ElMessage.error({
      message: '请先选择项目',
      showClose: true,
    })
    return
  }
  if (cunMuBanPojo.value.name === '' || cunMuBanPojo.value.pyCode === '' || cunMuBanPojo.value.dcode === '') {
    ElMessage.error({
      message: '模板名称，拼音码，五笔码不能为空',
      showClose: true,
    })
    return
  }
  cunMuBanPojo.value.list = clone(feiYongShuJu.value)
  // 开始上传
  shangChuanMuBan(cunMuBanPojo.value).then(() => {
    cunMuBanPojo.value = {}
  })
}

// 根据病人的科室来获取
const getBingQuDuiYingKeShiChange = () => {
  getBingQuDuiYingKeShi(queryWard.value).then((res) => {
    xiaoKeShiList.value = res
    queryDept.value = ''
  })
}
const zhiXingKeShi = ref(store.state.user.info.deptCode)

const xieGaiZhiXingKeShi = () => {
  for (let i = 0; i < feiYongShuJu.value.length; i++) {
    feiYongShuJu.value[i].deptCode = zhiXingKeShi.value
  }
}

// 新增中的分页 事件
const xinZhengSizeChange = (val) => {
  xiangMuHuoYaoPinShuJu.value.pageSize = val
}

const xinZhengCurrentChange = (val) => {
  xiangMuHuoYaoPinShuJu.value.currentPage = val
}

watch(
    () => xiangMuHuoYaoPinFlag.value,
    () => {
      xiangMuHuoYaoPinShuJu.value.data = []
    }
)
const renYuanList = ref([])

// 搜索 医生工号
const remoteMethodRenYuan = (val) => {
  if (val.length >= 2)
    getRenYuan(val).then((res) => {
      renYuanList.value = res
    })
}

function panDuanSFWeiShouShuShi() {
  let dept = store.state.user.info.deptCode
  return dept === '1300000' || dept === '3100000' || dept === '1300010';
}

function operationRoom() {
  let dept = store.state.user.info.deptCode
  return dept === '1300000'
}

</script>

<style></style>
