<template>
  <el-container>
    <el-aside width="195px">
      <HuoQuMuBan @selectionFeiYong="xuanZeXiangMuTable"></HuoQuMuBan>
    </el-aside>
    <el-main>
      <el-button type="warning" size="mini" icon="el-icon-star-off" @click="baoCunMuBanDialog = true">存模板</el-button>
      <el-button type="primary" size="mini" @click="shangChuanXiangMu" icon="el-icon-upload">保存</el-button>
      <el-button type="success" size="mini" icon="el-icon-plus" @click="xinZhengXiangMuDialog = true">新增</el-button>
      <el-select style="width: 120px; margin: 0px 10px 0px 10px" v-model="zhiXingKeShi" size="mini" filterable>
        <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 type="warning" size="mini" icon="el-icon-edit" @click="xieGaiZhiXingKeShi">修改执行科室</el-button>
      <span v-if="panDuanSFWeiShouShuShi()">
        病区：
        <el-select style="width: 120px" size="mini" filterable v-model="queryWard" @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 style="width: 120px" size="mini" filterable v-model="queryDept">
          <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 style="width: 120px" size="mini" v-model="ssCode" clearable placeholder="请输入手术编码"></el-input>
      </span>
      <el-tag type="danger"> 项目总价：{{ xiangMuZongJia }}</el-tag>
      <el-table :data="feiYongShuJu" :height="tableHeight - 27" style="margin-top: 10px" stripe highlight-current-row>
        <el-table-column label="录入信息">
          <el-table-column label="是否自费">
            <template #default="scope">
              <el-switch
                active-color="#ff4949"
                inactive-color="#13ce66"
                active-text="自费"
                inactive-text="医保"
                :active-value="1"
                :inactive-value="0"
                v-model="scope.row.ybSelfFlag"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="录入时间" width="80px">
            <template #default>
              {{ getDatetime(new Date()) }}
            </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 style="width: 90%" size="mini" v-model="scope.row.deptCode" filterable>
                <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">
            <template #default="scope">
              <!--precision 限制输入的精度 0 就是不带任何一位小数点  -->
              <el-input-number v-model="scope.row.amount" size="mini" :min="0" :precision="1"></el-input-number>
            </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 size="mini" type="danger" @click="shanChuXiangMuClick(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-dialog v-model="xinZhengXiangMuDialog" title="新增" :width="1500">
      搜索：
      <el-select v-model="chargeCodePy" size="mini" remote filterable clearable @change="getDanGeXiangMu" default-first-option :remote-method="rmChargePyCode">
        <el-option v-for="item in xiangMuHuoYaoPinShuJu" :key="item.chargeCodeMx" :label="item.chargeName" :value="item.chargeCodeMx">
          <span v-if="xiangMuHuoYaoPinFlag == 0">
            <span style="color: #8492a6; font-size: 12px">{{ item.chargeCodeMx }}</span>
            <el-divider direction="vertical"></el-divider>
            <span> {{ item.chargeName }}</span>
            <el-divider direction="vertical"></el-divider>
            <span style="color: red"> {{ item.ybComment }}</span>
            <el-divider direction="vertical"></el-divider>
            <span style="color: #e6a23c"> {{ item.chargeAmount }} 元</span>
          </span>
          <span v-else>
            <span style="color: #8492a6; font-size: 12px">{{ item.chargeCodeMx }}</span>
            <el-divider direction="vertical"></el-divider>
            <span> {{ item.chargeName }}</span>
            <el-divider direction="vertical"></el-divider>
            <span style="color: #e6a23c"> {{ item.spec }} </span>
            <el-divider direction="vertical"></el-divider>
            <span style="color: #8492a6"> {{ item.yblx }} </span>
            <el-divider direction="vertical"></el-divider>
            <span style="color: #e6a23c"> {{ item.chargeAmount }} 元</span>
          </span>
        </el-option>
      </el-select>
      <el-switch
        active-color="#409EFF"
        inactive-color="#13ce66"
        active-text="药品"
        inactive-text="项目"
        :active-value="1"
        :inactive-value="0"
        v-model="xiangMuHuoYaoPinFlag"
      ></el-switch>
      <el-button size="mini" type="success" @click="danGeXiangMuBaoCun">保存</el-button>
      <el-table :data="danGeFeiYong">
        <el-table-column label="项目编码" prop="chargeCodeMx"></el-table-column>
        <el-table-column label="项目名称" prop="chargeName"></el-table-column>
        <el-table-column label="规格" prop="spec"></el-table-column>
        <el-table-column label="执行科室" prop="deptCode">
          <template #default="scope">
            <el-select style="width: 90%" size="mini" v-model="scope.row.deptCode" filterable>
              <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">
          <template #default="scope">
            <el-input-number v-model="scope.row.amount" size="mini" :min="1" :precision="1"></el-input-number>
          </template>
        </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>
    </el-dialog>
    <el-dialog title="保存模板" v-model="baoCunMuBanDialog">
      <el-row>
        <el-col :span="24"> 模板名称：<el-input size="mini" v-model="cunMuBanPojo.name" maxlength="15" @blur="zhuanPinYin" show-word-limit></el-input> </el-col>
        <el-col :span="12"> 拼音码：<el-input size="mini" v-model="cunMuBanPojo.pyCode" maxlength="8" show-word-limit></el-input> </el-col>
        <el-col :span="12"> 五笔码：<el-input size="mini" v-model="cunMuBanPojo.dcode" maxlength="8" show-word-limit></el-input> </el-col>
        <!-- <el-col :span="12"> 排序码：<el-input size="mini" v-model="cunMuBanPojo.paiXu" maxlength="7" show-word-limit></el-input> </el-col> -->
        <el-col :span="12">
          <el-button size="mini" style="margin-top: 10px" icon="el-icon-upload" type="primary" @click="baoCunMuBan">保存</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </el-container>
</template>

<script>
import { computed, onMounted, ref, watch } from 'vue'
import { getMuBan, getMuBanXinXi, xiangMuFeiYongShangChuan, getDept, queryDanGeXiangMu, shanChuMuBan, getPyCode, shangChuanMuBan } from '@/api/yibao/xiang-mu-lu-ru'
import Cookie from 'js-cookie'
import store from '@/store'
import { getDatetime } from '@/utils/date'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBingQuDuiYingKeShi, getWard } from '@/api/yibao/xiang-mu-lu-ru'
import { clone } from '@/utils/clone'
import HuoQuMuBan from './HuoQuMuBan.vue'

export default {
  components: {
    HuoQuMuBan,
  },
  props: {
    patient: {
      type: Object,
    },
  },
  setup(props, cxt) {
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 170
    const deptData = ref([])
    const wardData = ref([])

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

    // 项目录入模板数据
    const muBanData = 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 = Cookie.get('dept')
          feiYongShuJu.value.push(val[i])
        }
      }
    }

    const chargeCode = ref([])

    onMounted(() => {
      // 获取模板信息
      getMuBan(Cookie.get('dept')).then((res) => {
        muBanData.value = res
      })
      // 获取科室
      getDept().then((res) => {
        deptData.value = res
      })
      getWard().then((res) => {
        wardData.value = res
      })
    })

    const feiYongShuJu = ref([])

    const shangChuanXiangMu = () => {
      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,
      }
      //在此处上传
      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([])
    // 远程查询的
    const chargeCodePy = ref('')

    /**
     * 远程搜索
     */
    const rmChargePyCode = (val) => {
      if (val.length >= 2) {
        queryDanGeXiangMu(val, xiangMuHuoYaoPinFlag.value).then((res) => {
          xiangMuHuoYaoPinShuJu.value = res
        })
      }
    }
    // 单个费用
    const danGeFeiYong = ref([])

    // 获取单个费用录入 并且放入表格中选择
    const getDanGeXiangMu = () => {
      xiangMuHuoYaoPinShuJu.value.filter((item) => {
        if (item.chargeCodeMx === chargeCodePy.value) {
          item.deptCode = Cookie.get('dept')
          danGeFeiYong.value = []
          danGeFeiYong.value.push(item)
        }
      })
    }

    const danGeXiangMuBaoCun = () => {
      if (chargeCodePy.value === '') {
        return ElMessage.error({
          showClose: true,
          message: '请先选择一条费用',
        })
      }
      for (let i = 0; i < chargeCode.value.length; i++) {
        if (chargeCode.value[i] === danGeFeiYong.value[0].chargeCodeMx) {
          return ElMessage.error({
            showClose: true,
            message: '请勿重复录入',
          })
        }
      }
      feiYongShuJu.value.push(danGeFeiYong.value[0])
      chargeCode.value.push(danGeFeiYong.value[0].chargeCodeMx)
      danGeFeiYong.value = []
      chargeCodePy.value = ''
    }

    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: Cookie.get('dept'),
      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(Cookie.get('dept'))

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

    return {
      muBanData,
      tableHeight,
      muBanCurrentPage,
      muBanHandleCurrentChange,
      muBanPageSize,
      getMuBanXinXiClick,
      muBanXiangQing,
      xuanZeXiangMuTable,
      deptData,
      feiYongShuJu,
      getDatetime,
      shangChuanXiangMu,
      shanChuXiangMuClick,
      xinZhengXiangMuDialog,
      xiangMuHuoYaoPinFlag,
      xiangMuHuoYaoPinShuJu,
      chargeCodePy,
      rmChargePyCode,
      getDanGeXiangMu,
      danGeFeiYong,
      danGeXiangMuBaoCun,
      wardData,
      queryWard,
      queryDept,
      ssCode,
      xiangMuZongJia,
      baoCunMuBanDialog,
      cunMuBanPojo,
      zhuanPinYin,
      baoCunMuBan,
      getBingQuDuiYingKeShiChange,
      panDuanSFWeiShouShuShi,
      zhiXingKeShi,
      xieGaiZhiXingKeShi,
      xiaoKeShiList,
    }
  },
}

function panDuanSFWeiShouShuShi() {
  let dept = Cookie.get('dept')
  if (dept === '1300000' || dept === '3100000' || dept === '1300010') {
    return true
  }
  return false
}
</script>

<style></style>
