<template>
  <div class="layout_display_flex">
    <div style="width: 195px">
      <HuoQuMuBan
          ref="muBanRef"
          @selectionFeiYong="xuanZeXiangMuTable"/>
    </div>
    <div class="layout_flex_1-x layout_display_flex_y">
      <div>
        <el-button icon="Document" 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>
        病区：
        <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="ssCode"
            @blur="ssCode = ssCode.trim()"
            clearable
            placeholder="请输入手术编码"
            style="width: 120px"/>
        <el-tag type="danger"> 项目总价：{{ xiangMuZongJia }}</el-tag>
      </div>
      <div class="layout_flex_1-y">
        <el-table :data="saveData"
                  height="100%"
                  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' ? 2 : 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>
      </div>
    </div>
  </div>

  <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"
        @change="clearXiangMuHuoYaoPinShuJu"
        :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="manuName"></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-button icon="Upload" style="margin-top: 10px" type="primary" @click="baoCunMuBan">保存</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script setup lang="ts">
import {computed, onMounted, ref, watch} from 'vue'
import {
  getBingQuDuiYingKeShi,
  getDept,
  getPyCode,
  getWard,
  queryDanGeXiangMu,
  shangChuanMuBan,
  xiangMuFeiYongShangChuan
} from '@/api/inpatient/xiang-mu-lu-ru'
import {getRenYuan} from '@/api/public-api'
import {ElMessage, ElMessageBox} from 'element-plus'
import {clone} from '@/utils/clone'
import HuoQuMuBan from './HuoQuMuBan.vue'
import {stringIsBlank, stringNotBlank} from "@/utils/blank-utils";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import {useUserStore} from "@/pinia/user-store";
import cyRefList from "@/utils/cyRefList";
import Dig from "@/utils/math";
import XEUtils from "xe-utils";
import useCompRef from "@/utils/useCompRef";

const props = defineProps<{
  patient: {
    inpatientNo: string;
    admissTimes: number;
    zySerialNo: string;
    referPhysician: string;
    ledgerSn: number
  }
}>()

const emits = defineEmits(['theUploadIsSuccessful'])

const userStore = useUserStore().userInfo
const tableHeight = window.innerHeight - 170
const deptData = ref([])
const wardData = ref([])
const muBanRef = useCompRef(HuoQuMuBan)

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

const xiaoKeShiList = ref([])

declare type ChargeCodeType = {
  chargeCodeMx: string;
  serial: string;
  chargeName: string
  deptCode: string;
  chargeAmount: number
  amount: number
}

const [saveData, saveProxy] = cyRefList<ChargeCodeType>((item) => {
  return item.chargeCodeMx.trim() + "_" + item.serial.trim();
}, (item) => {
  return `项目【${item.chargeName}】请勿重复添加`
});

// 获取选择的数据
const xuanZeXiangMuTable = (value) => {
  for (let i = 0; i < value.length; i++) {
    const item = value[i];
    item.deptCode = userStore.deptCode;
  }
  saveProxy.push(...value)
}

const chargeCode = ref([])

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

  if (operationRoom() && stringNotBlank(ssCode.value) && !XEUtils.isStringNumber(ssCode.value)) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "手术编码必须纯数字且中间不得有空格。");
  }

  if (stringIsBlank(props.patient.inpatientNo)) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "请先选择患者。");
  }

  if (saveData.value.length === 0) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "请先选择上传数据。");
  }

  const 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: saveData.value,
    orderNo: 3,
    ledgerSn: props.patient.ledgerSn,
  };

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

const shanChuXiangMuClick = (val) => {
  saveProxy.delIndex(val)
}
// 新增项目或者药品
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: ChargeCodeType) => {
  if (stringIsBlank(val.deptCode)) {
    val.deptCode = userStore.deptCode
  }
  saveProxy.push(val);
}

const xiangMuZongJia = computed(() => {
  let sum = 0

  saveData.value.forEach((item) => {
    sum += Dig.multiply(item.chargeAmount, item.amount)
  })

  return XEUtils.toFixed(sum, 2)
})

// 以下是保存模板
const baoCunMuBanDialog = ref(false)

const cunMuBanPojo = ref({
  pyCode: '',
  dcode: '',
  name: '',
  paiXu: '',
  dept: '',
  deptCode: userStore.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 (saveData.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(saveData.value)
  // 开始上传
  shangChuanMuBan(cunMuBanPojo.value).then(() => {
    cunMuBanPojo.value = {}
    muBanRef.value?.reloadData()
  })
}

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

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

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

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

const clearXiangMuHuoYaoPinShuJu = () => {
  xiangMuHuoYaoPinShuJu.value.data = []
}

const renYuanList = ref([])

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

function operationRoom() {
  let dept = userStore.deptCode
  return dept === '1300000'
}

const updateDeptAndWard = async (ward, dept) => {
  queryWard.value = ward
  await getBingQuDuiYingKeShiChange()
  queryDept.value = dept
}

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

defineExpose({
  updateDeptAndWard
})

</script>

<style></style>
