<template>
  <el-container>
    <el-dialog v-model="huanZheXinXiDialog" fullscreen title="修改信息" @closed="emit('close')">
      <el-descriptions :column="4" border style="width: 100%" title="基本信息">
        <template #extra>
<!--          <el-button :disabled="shenHeSendFlag" size="small" type="primary" @click="fqsendAudit">申请审核</el-button>-->
<!--            <el-button size="small"  type="primary" @click="queryJianYanJianCha">检验检查记录</el-button>-->
            <el-button size="small" type="primary" @click="bingAnShouYe">病案首页</el-button>
            <el-button size="small" v-if="auditQuanXian()" type="primary" @click="shenQingCheHui">撤销审核</el-button>
            <el-button size="small" type="primary" @click="showChargeListClick">费用清单</el-button>
          <el-button size="small" type="primary" @click="querylistSetlAuditLog">审核历史记录</el-button>
          <el-button size="small" type="primary" @click="queryDianZiBingLi">电子病历</el-button>
          <el-button size="small" type="primary" @click="qualityTest('3')">质控测算</el-button>
          <el-button size="small" type="primary" @click="drgGroupTest">DRG分组测算</el-button>
          <el-button type="info" @click="shenHeClick">审核信息</el-button>
          <el-button size="small" type="primary" @click="shuJuDuiBi">数据对比</el-button>
          <el-button size="small" :disabled="shenHeSendFlag" type="success" @click="bingAnShouYeXiaoYan()">保存并申请审核</el-button>
            <el-button size="small" v-if="shenHeQuanXian()" type="success" @click="bingAnShouYeXiaoYan('1')">保存并审核通过</el-button>
          <bei-zhu v-if="beiZhuRef" :data="baoCunXiuGaiData" @baoCunHouGuanBi="baoCunHouGuanBi"
                   @close="beiZhuRef = false"></bei-zhu>
        </template>
        <el-descriptions-item label="姓名">
          {{ setlinfo.name }}
          <el-button @click="feiYongDrawer">{{ setlinfo.outDeptName }}</el-button>
          <ke-shi-fei-yong v-if="keShiFeiYongRef" :patNo="setlinfo.inpatientNo" :times="setlinfo.admissTimes"
                           @close="keShiFeiYongRef = false"></ke-shi-fei-yong>
        </el-descriptions-item>
        <el-descriptions-item label="性别">
          {{ cptSex(setlinfo.sex) }}
        </el-descriptions-item>
        <el-descriptions-item label="住院号">
          {{ setlinfo.inpatientNo }}
        </el-descriptions-item>
        <el-descriptions-item label="医保身份">
          <el-tag effect="dark" type="success">
            {{ setlinfo.responceTypeName }}
          </el-tag>
          <el-tag effect="dark" type="warning">
            {{ setlinfo.insutypeName }}
          </el-tag>
        </el-descriptions-item>
          <el-descriptions-item label="年龄">
              {{ setlinfo.upload.age }}
          </el-descriptions-item>
          <el-descriptions-item label="主管医生">
              {{ setlinfo.upload.referPhysicianName }}
          </el-descriptions-item>
        <el-descriptions-item label="住院次数">
          {{ setlinfo.admissTimes }}
        </el-descriptions-item>
        <el-descriptions-item label="总费用">
          {{ setlinfo.medfeeSumamt }}
        </el-descriptions-item>
        <el-descriptions-item label="诊断编码">
          {{ setlinfo.disDiag }}
        </el-descriptions-item>
        <el-descriptions-item label="治疗方式">
          <el-select v-model="setlinfo.operation" filterable style="width: 220px">
            <el-option v-for="item in operations" :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-descriptions-item>
        <el-descriptions-item label="住院天数">
          {{ setlinfo.actIptDays }}
        </el-descriptions-item>
        <el-descriptions-item label="报销金额">
          {{ setlinfo.fundPaySumamt }}
        </el-descriptions-item>
        <el-descriptions-item label="诊断名称">
          {{ setlinfo.disDiagComment }}
        </el-descriptions-item>
        <el-descriptions-item label="申报类型">
          <el-select v-model="setlinfo.decType" clearable filterable style="width: 150px">
            <el-option v-for="item in decTypes" :key="item.code" :disabled="item.dis" :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-descriptions-item>
        <el-descriptions-item v-if="auditQuanXian()" label="审核">
          <el-button :disabled="shenHeTongGuoFlag" type="success" @click="qualityTest('2')">审核通过</el-button>
<!--          <el-button :disabled="keFouShenHe" type="success" @click="shenHeTongGuoShangChuanClick">审核通过并上传-->
<!--          </el-button>-->
          <el-button :disabled="keFouShenHe" type="danger" @click="shenHeBoHuiClick">审核驳回</el-button>
        </el-descriptions-item>
      </el-descriptions>
      <el-tag size="small">住院诊断信息</el-tag>
      <el-button icon="CirclePlus" type="success" @click="addZhenDuanClick">新增诊断</el-button>
      入院病情： 1.有，2.临床未确定，3.情况不明，4.无
      <el-table id="sortable-diseinfo" :data="diseinfo" :height="store.state.app.windowSize.h / 2.5"
                highlight-current-row row-key="id" stripe>
        <el-table-column width="50">
          <template #default>
            <el-button class="shangxiatuodong"><i class="iconfont icon-shangxiatuodong"></i></el-button>
          </template>
        </el-table-column>
        <el-table-column label="诊断代码" prop="disDiag"></el-table-column>
        <el-table-column label="诊断名称" prop="disDiagComment"></el-table-column>
        <el-table-column label="手术分值" prop="ssfz"></el-table-column>
        <el-table-column label="科室" prop="deptCodeName"></el-table-column>
        <el-table-column label="入院病情" prop="admissCond" width="90">
          <template #default="scope">
            {{ getAdmissCond(scope.row.admissCond) }}
          </template>
        </el-table-column>
        <el-table-column label="诊断类别" prop="siDiagTypeName">
          <template #default="scope">
            {{ getsiDiagTypeName(scope.row.siDiagType) }}
          </template>
        </el-table-column>
        <el-table-column label="诊断排序" prop="disDiagNo">
          <template #default="scope">
            {{ scope.row.disDiagNo }}
            &nbsp;&nbsp;&nbsp;
            <el-button v-if="scope.row.disDiagNo !== 1" type="primary"
                       @click="sheZhiZhuZhenDuan(scope.$index, scope.row.disDiagNo)"> 设为主诊断
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="删除">
          <template #default="scope">
            <el-button icon="Edit" type="warning" @click="xiuGaiZhenDuanClick(scope.$index, scope.row)">修改</el-button>
            <el-popconfirm
                cancel-button-text="取消"
                confirm-button-text="确认"
                icon="Info"
                iconColor="#F56C6C"
                title="是否删除该诊断"
                @confirm="delZhenDuan(scope.$index, scope.row.disDiagNo)"
            >
              <template #reference>
                <el-button icon="Delete" size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-tag size="small">手术操作信息</el-tag>
      <el-button icon="CirclePlus" type="success" @click="tianJiaXiuGaiShouShu(-1)">新增手术</el-button>
      <el-table id="sortable-oprninfo" :data="oprninfo" :height="store.state.app.windowSize.h / 2.5" border
                highlight-current-row row-key="id" stripe>
        <el-table-column width="50">
          <template #default>
            <el-button class="shangxiatuodong"><i class="iconfont icon-shangxiatuodong"></i></el-button>
          </template>
        </el-table-column>
        <el-table-column label="手术及操作名称" prop="ssmc"></el-table-column>
        <el-table-column label="手术开始时间" prop="opStartDate" width="140"></el-table-column>
        <el-table-column label="手术结束时间" prop="opEndDate" width="140"></el-table-column>
        <el-table-column label="麻醉开始时间" prop="anstStartDate" width="140"></el-table-column>
        <el-table-column label="麻醉结束时间" prop="anstEndDate" width="140"></el-table-column>
        <el-table-column label="手术及操作日期" prop="ssrq" width="140"></el-table-column>
        <el-table-column label="科室" prop="deptCodeName"></el-table-column>
        <el-table-column label="手术级别" prop="ssjb"></el-table-column>
        <el-table-column label="手术及操作编码	" prop="ssbm"></el-table-column>
        <el-table-column label="手术及操作医师">
          <el-table-column label="术者" prop="ssysName"></el-table-column>
          <el-table-column label="I助" prop="sszsName1"></el-table-column>
          <el-table-column label="II助" prop="sszsName2"></el-table-column>
        </el-table-column>
        <el-table-column label="切口愈合等级" prop="qkjb">
          <template #default="scope">
            {{ qieKouName(scope.row.qkjb, scope.row.yhqk) }}
          </template>
        </el-table-column>
        <el-table-column label="麻醉方式" prop="mzff">
          <template #default="scope">
            {{ maZuiName(scope.row.mzff) }}
          </template>
        </el-table-column>
        <el-table-column label="麻醉医师" prop="mzysName"></el-table-column>
        <el-table-column label="手术排序" prop="ssxh" width="150">
          <template #default="scope">
            {{ scope.row.ssxh }}
            &nbsp;&nbsp;&nbsp;
            <el-button v-if="scope.row.ssxh !== 1" type="primary"
                       @click="sheZhiZhuShouShu(scope.$index, scope.row.ssxh)"> 设为主手术
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210">
          <template #default="scope">
            <el-button icon="Edit" type="warning" @click="tianJiaXiuGaiShouShu(scope.$index)">修改</el-button>
            <el-popconfirm cancel-button-text="取消" confirm-button-text="确认" icon="Info" iconColor="#F56C6C"
                           title="是否删除该手术" @confirm="delShouShu(scope.$index)">
              <template #reference>
                <el-button icon="Delete" size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-tag>患者输血信息</el-tag>
      <el-button icon="CirclePlus" type="success" @click="xinZhengShuXueXinXi">新增输血信息</el-button>
      <el-table :data="patientBldInfos" :height="store.state.app.windowSize.h / 3">
        <el-table-column label="输血品种" prop="bldCatName"></el-table-column>
        <el-table-column label="输血量" prop="bldAmt"></el-table-column>
        <el-table-column label="输血计量单位" prop="bldUnit"></el-table-column>
        <el-table-column label="操作" width="210">
          <template #default="scope">
            <el-button icon="Edit" type="warning" @click="modifiedBloodTransfusion(scope.row)"> 修改</el-button>
            <el-popconfirm
                cancel-button-text="取消"
                confirm-button-text="确认"
                icon="Info"
                iconColor="#F56C6C"
                title="是否删除该输血信息"
                @confirm="clickRemoveBloodTransfusion(scope.$index, scope.row.id)"
            >
              <template #reference>
                <el-button icon="Delete" size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <shu-xue-xin-xi v-if="shuXueXinXi.dialog" :data="shuXueXinXi.data" @addData="addBloodTransfusionData"
                      @close="shuXueXinXi.dialog = false"/>
    </el-dialog>
    <el-dialog v-model="zhenDuanDialog" width="60%" title="诊断">
      <el-select v-model="diagnosticQuery.method" filterable style="width: 100px">
        <el-option v-for="item in methods" :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="diagnosticQuery.content" clearable style="width: 120px"
                @keyup.enter="zhenDuanChaXunClick"></el-input>
      <el-button icon="Search" type="primary" @click="zhenDuanChaXunClick">查询</el-button>
      诊断类别：
      <el-select v-model="lingShiZhenDuan.siDiagType" style="width: 120px">
        <el-option v-for="item in siDiagTypes" :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="lingShiZhenDuan.admissCond" style="width: 60px">
        <el-option v-for="item in admissCondData" :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>
      科室:
      <xc-select v-model="lingShiZhenDuan"
                 :name="['deptCode','deptCodeName']"
                 :data=" props.data.deptList">
      </xc-select>

      <el-table :data="queryZhenDuanData" height="450px" highlight-current-row stripe>
        <el-table-column label="编码" prop="code"></el-table-column>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-popconfirm
                v-if="addZhenDuanFlag"
                cancel-button-text="取消"
                confirm-button-text="确认"
                icon="Info"
                iconColor="#67C23A"
                title="是否添加该诊断"
                @confirm="addZhenDuan(scope.row)"
            >
              <template #reference>
                <el-button icon="CirclePlus" size="small" type="success">新增</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm
                v-else
                cancel-button-text="取消"
                confirm-button-text="确认"
                icon="Info"
                iconColor="#E6A23C"
                title="是否修改为该诊断"
                @confirm="xuanZheZhenDuan(scope.row)"
            >
              <template #reference>
                <el-button icon="Edit" size="small" type="warning">修改</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <br/>
      <el-button :disabled="diagnosticQuery.page === 1" @click="pageZhenDuanChaXun((diagnosticQuery.page -= 1))">
        上一页
      </el-button>
      <el-button @click="pageZhenDuanChaXun((diagnosticQuery.page += 1))">下一页</el-button>
    </el-dialog>
    <jie-suan-dan-xiu-gai-shou-shu v-if="shouShuDialog"
                                   :dept-list="props.data.deptList"
                                   :data="formShouShu"
                                   @addShouShuClick="addShouShuClick"
                                   @close="shouShuDialog = false"/>
    <shen-he-xin-xi v-if="shenHeRef" :data="props.data.shenHeXinXi" @close="shenHeRef = false"></shen-he-xin-xi>
    <ShuJuDuiBi
        v-if="shuJuDuiBiDialogRef"
        :new-bat="props.data.newBatjBa4"
        :newYbZyDisDiag="props.data.newYbZyDisDiag"
        :oldBat="props.data.batjBa4"
        :oldYbZyDisDiag="props.data.ybZyDisDiag"
        @close="shuJuDuiBiDialogRef = false"
    ></ShuJuDuiBi>
    <el-dialog v-model="setlAuditLogFlag"  title="审核历史记录" width="50%" class="maxhight">
      <el-timeline>
        <el-timeline-item v-for="item in setlAuditLogData" :data="setlAuditLogData" :key="item.id" :timestamp="item.createTime" placement="top" color="red" >
          <el-card>
            <h4>{{item.auditTypeName}}</h4>
            <p>审核状态： {{item.auditFlagName}} </p>
            <p>{{item.auditTypeName+'人:'}} {{item.createName}}</p>
            <p>备注： {{item.remark}} </p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
    <el-dialog v-model="qualityDialogFlag"  title="质控结果" width="50%" class="maxhight">
      <el-table  :data="qualityData" height="100%"
                highlight-current-row row-key="id" :stripe="true" :border="true" >
        <el-table-column label="质控字段名称" prop="check_filed"></el-table-column>
        <el-table-column label="字段原始值" prop="original_value"></el-table-column>
        <el-table-column label="规则等级" prop="rule_level">
          <template #default="scope">
            {{ getRuleLevelName(scope.row.rule_level) }}
          </template>
        </el-table-column>
        <el-table-column label="质控规则类型" prop="rule_category">
          <template #default="scope">
            {{ getRuleCategoryName(scope.row.rule_category) }}
          </template>
        </el-table-column>
        <el-table-column label="是否影响入组" prop="affect_group">
          <template #default="scope">
            {{ getAffectGroupName(scope.row.affect_group) }}
          </template>
        </el-table-column>
        <el-table-column label="质控结果" prop="result_msg"></el-table-column>
      </el-table>
        <el-row>
            <el-button v-show="quRenShenHeTongGuoFlag" type="primary" @click="queRenShenHeTongGuo">确认审核通过</el-button>
            <el-button v-if="queRenBaoCunFlag" type="primary" @click="queRenbaoCunXiuGai()">确认保存</el-button>
            <el-button v-if="zhiJieBaoCunFlag" type="primary" @click="queRenbaoCunXiuGai('1')">确认审核通过并且保存</el-button>
        </el-row>
    </el-dialog>
      <el-dialog v-model="jianYanJianChaDialogFlag" width="60% " title="检验检查">
          <jian-yan-jian-cha :huanZheXinXi="huanZheXinXi" ></jian-yan-jian-cha>
      </el-dialog>
      <charge-list v-if="showChargeList" :pat-no="setlinfo.inpatientNo" :times="setlinfo.admissTimes" @close="showChargeList = false"></charge-list>
      <span class="m-drawer">
            <el-drawer v-model="showMessageDrawer" title="病案首页质控" size="260px" modal-class="modal-class" >
              <div class="page-inner">
                <div v-if="forceVerifies.length === 0 && adviceVerifies.length === 0" class="no-verify-message">暂无校验内容</div>
                <div v-show="forceVerifies.length > 0" style="padding: 8px 0 4px 0; font-weight: bold">以下条目为强制要求，请完善。</div>
                <div v-for="(item, index) in forceVerifies" :key="index" class="message-item" :style="messageColor(index)">
                  {{ index + 1 }}、{{ item.name }}
                </div>
                <div v-show="adviceVerifies.length > 0" style="padding: 8px 0 4px 0; font-weight: bold">以下条目为建议执行，不做强制要求。</div>
                <div v-for="(item, index) in adviceVerifies" :key="index" style="padding: 6px; margin-bottom: 6px; border-radius: 4px; background: #eea7a752; color: #ff2b2b">
                  {{ index + 1 }}、{{ item.name }}
                </div>
              </div>
            </el-drawer>
          </span>
  </el-container>
</template>

<script name="JieSuanDanXiangQing" setup>
import store from '@/store'
import {cptSex} from '@/utils/computed'
import {searchYbDiag} from '@/api/inpatient/dictionary'
import {decTypes, operations} from '../../../data'
import {clone} from '@/utils/clone'
import {ElMessage, ElMessageBox} from 'element-plus'
import ChargeList from '@/components/medical-insurance/charge-list/Index.vue'
import {
  removeBloodTransfusion,
  setlUploadAudit,
  shouShuBianMa,
  upldSetlList,
  sendDrgGroupTest,
  sendAudit,
  listSetlAuditLog,
  drgQualityTest,
  isInHospital,
sendShenQingCheHui,
    querySetlModifyReq,
    sheetVerification
} from '@/api/medical-insurance/si-setl-upload'
import {formatDatetime} from '@/utils/date'
import {listIsBlank, stringIsBlank, stringNotBlank} from '@/utils/blank-utils'
import {getAdmissCond, getsiDiagTypeName, maZuiName, qieKouName, shenHeQuanXian,auditQuanXian,auditBmzzQuanXian,getRuleLevelName, getRuleCategoryName,getAffectGroupName} from '../jieSuanDanXiuGai'
import ShenHeXinXi from '../ShenHeXinXi.vue'
import KeShiFeiYong from '../KeShiFeiYong.vue'
import BeiZhu from '../BeiZhu.vue'
import Sortable from 'sortablejs'
import ShuJuDuiBi from '../ShuJuDuiBi.vue'
import {ArrayIsEqual} from '@/utils/list-utlis'
import JieSuanDanXiuGaiShouShu from '@/components/si-sheet-upload/jie-suan-dan-xiu-gai/JieSuanDanXiuGaiShouShu.vue'
import ShuXueXinXi from '@/components/si-sheet-upload/ShuXueXinXi.vue'
import XcSelect from "@/components/xiao-chan/select/XcSelect.vue";
import {getEmrUrl,getInEmrUrl} from '@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/emr-init';
import router from "@/router";
const props = defineProps({
  data: {},
})

const emit = defineEmits(['close','queryCurrentPage'])

// 基本信息
const setlinfo = ref({})
// 住院诊断信息
const diseinfo = ref([])
// 手术操作信息
const oprninfo = ref([])
const huanZheXinXiDialog = ref(true)
const jianYanJianChaDialogFlag = ref(false)
const huanZheXinXi = ref({
    inpatientNo:'',
    admissTimes:'',
    name:'',
    sexName:'',
    age:''
})

const code = store.state.user.info.code
const name = store.state.user.info.name
//审核历史记录弹出框
const setlAuditLogFlag = ref(false)
//审核历史记录数据
const setlAuditLogData =  ref([])

const qualityDialogFlag = ref(false)

const qualityData = ref([])
const showChargeList =ref(false)
/*以下全部都是诊断  */
const diagnosticQuery = ref({
  method: 'name',
  target: 'diag',
  // 内容
  content: '',
  medType: '',
  // 当前页
  page: 1,
})
const lingShiZhenDuan = ref({
  disDiag: '',
  disDiagComment: '',
  admissCond: '',
  siDiagType: '',
})

const zhenDuanDialog = ref(false)
const addZhenDuanFlag = ref(false)
let zhenDuanIndex = 0
const xiuGaiZhenDuanClick = (index, val) => {
  queryZhenDuanData.value = []
  diagnosticQuery.value.content = val.disDiagComment
  lingShiZhenDuan.value = val
  addZhenDuanFlag.value = false
  zhenDuanDialog.value = true
  zhenDuanIndex = index
  diseinfo.value.forEach((item, index) => {
    item.disDiagNo = index + 1
  })
}
const queryZhenDuanData = ref([])
const xuanZheZhenDuan = (val) => {
  if (zhenDuanTianJiaTiaoJian()) return
  diseinfo.value[zhenDuanIndex].disDiag = val.code
  diseinfo.value[zhenDuanIndex].disDiagComment = val.name
  setTimeout(() => {
    ElMessage({
      message: '修改成功',
      type: 'success',
      showClose: true,
    })
    zhenDuanDialog.value = false
  }, 100)
}
const zhenDuanChaXunClick = () => {
  searchYbDiag(diagnosticQuery.value).then((res) => {
    queryZhenDuanData.value = res
  })
}
const pageZhenDuanChaXun = (val) => {
  searchYbDiag(diagnosticQuery.value).then((res) => {
    queryZhenDuanData.value = res
  })
}
const showChargeListClick =()=>{
    showChargeList.value = true
}
const sheZhiZhuZhenDuan = (index, val) => {
  let data = []
  for (let item of diseinfo.value) {
    if (val !== item.disDiagNo) {
      data.push(item)
    }
  }
  data.unshift(diseinfo.value[index])
  for (let i = 0; i < data.length; i++) {
    data[i].disDiagNo = i + 1
  }
  diseinfo.value = data
}

const sheZhiZhuShouShu = (index, val) => {
  let data = []
  for (let item of oprninfo.value) {
    if (val !== item.ssxh) {
      data.push(item)
    }
  }
  data.unshift(oprninfo.value[index])
  for (let i = 0; i < data.length; i++) {
    data[i].ssxh = i + 1
  }
  oprninfo.value = data
}


const addZhenDuanClick = () => {
  lingShiZhenDuan.value = {
    disDiag: '',
    disDiagComment: '',
    admissCond: '',
    siDiagType: '',
    id: null,
  }
  queryZhenDuanData.value = []
  addZhenDuanFlag.value = true
  zhenDuanDialog.value = true
}
const addZhenDuan = (val) => {
  if (zhenDuanTianJiaTiaoJian()) return
  lingShiZhenDuan.value.disDiag = val.code
  lingShiZhenDuan.value.id = diseinfo.value.length + 1
  lingShiZhenDuan.value.disDiagComment = val.name
  lingShiZhenDuan.value.disDiagNo = diseinfo.value.length + 1
  lingShiZhenDuan.value.newData = true
  diseinfo.value.push(lingShiZhenDuan.value)
  zhenDuanDialog.value = false
  setTimeout(() => {
    sortableDiseinfo()
  }, 100)
}
const delZhenDuan = (index, val) => {
  diseinfo.value.splice(index, 1)
  for (let i = 0; i < diseinfo.value.length; i++) {
    diseinfo.value[i].disDiagNo = i + 1
  }
}

function zhenDuanTianJiaTiaoJian() {
  if (stringIsBlank(lingShiZhenDuan.value.siDiagType)) {
    ElMessage.error('请先选择诊断类别')
    return true
  }
  if (stringIsBlank(lingShiZhenDuan.value.admissCond)) {
    ElMessage.error('请先选择入院院病情')
    return true
  }
  return false
}

/*诊断结束*/

/*一下都是手术的*/
const shouShuDialog = ref(false)
const formShouShu = ref({
  id: 0,
  ssxh: 0,
  ssmc: '',
  ssrq: '',
  ssjb: '',
  ssbm: '',
  ssys: '',
  ssysName: '',
  sszs1: '',
  sszsName1: '',
  sszs2: '',
  sszsName2: '',
  qkjb: '',
  yhqk: '',
  qkName: '',
  mzff: '',
  mzys: '',
  mzysName: '',
  deptCode: '',
  deptCodeName: '',
})

const oprninfoIndex = ref(-1)
const tianJiaXiuGaiShouShu = (index) => {
  if (index !== -1) {
    formShouShu.value = clone(oprninfo.value[index])
  } else {
    formShouShu.value = null
  }
  oprninfoIndex.value = index
  shouShuDialog.value = true
}

const addShouShuClick = async (val) => {
  val.ssrq = formatDatetime(val.ssrq)
  if (oprninfoIndex.value !== -1) {
    oprninfo.value[oprninfoIndex.value] = clone(val)
  } else {
    // 只有在新增的 时候才需要 加长度
    val.id = oprninfo.value.length + 1
    val.ssxh = oprninfo.value.length + 1
    val.newData = true
    oprninfo.value.push(clone(val))
  }
  shouShuDialog.value = false
  setTimeout(() => {
    sortableOprninfo()
  }, 100)
}

const delShouShu = (index) => {
  oprninfo.value.splice(index, 1)
  oprninfo.value.forEach((item, index) => {
    item.ssxh = index + 1
  })
  ElMessage.success('删除成功。')
}
/*手术结束*/

/* 提交审核信息 */
const baoCunXiuGaiData = ref({})
const beiZhuRef = ref(false)
const baoCunHouGuanBi = () => {
  huanZheXinXiDialog.value = false
  // ctx.emit('shua-xin')
  emit('queryCurrentPage')
}
//病案首页质控抽屉
const showMessageDrawer = ref(false)
//强制要求数据
const forceVerifies = ref([])
//建议要求数据
const adviceVerifies = ref([])
const currentMessageIndex = ref(null)


const messageColor = (id) => {
    return currentMessageIndex.value === id
        ? {
            background: '#ff2b2b',
            color: 'white',
        }
        : {
            background: '#eea7a752',
            color: '#ff2b2b',
        }
}

const queRenBaoCunFlag = ref(false)
const zhiJieBaoCunFlag = ref(false)
const quRenShenHeTongGuoFlag = ref(false)


//确认保存修改
const queRenbaoCunXiuGai = (flag) =>{
    qualityDialogFlag.value = false
    baoCunXiuGai(flag)
}

const baoCunXiuGai = (flag) => {
    let newData = {
        decType: setlinfo.value.decType,
        operation: setlinfo.value.operation,
        diseinfo: diseinfo.value,
        oprninfo: oprninfo.value,
    }
    let data =  createSaveData(newData,flag)
    baoCunXiuGaiData.value = data
    beiZhuRef.value = true
}









function createSaveData(newData,flag) {
    let changeData = ''
    let data = setlinfo.value
    data['opIdCode'] = code
    data['opIdName'] = name
    if (newData.decType !== oldData.decType) {
        changeData = `申报类型变动：原：【${getDeclarationType(oldData.decType)}】新：【${getDeclarationType(newData.decType)}】。`
    }
    if (newData.operation !== oldData.operation) {
        changeData += `治疗方式变动：原：【${getTreatmentName(oldData.operation)}】新：【${getTreatmentName(newData.operation)}】。`
    }
    // 住院诊断信息
    if (!ArrayIsEqual(oldData.diseinfo, newData.diseinfo)) {
        changeData += '【诊断有变动】'
    }
    // 手术有变动
    if (!ArrayIsEqual(oldData.oprninfo, newData.oprninfo)) {
        changeData += '【手术有变动】'
    }
    data['dataChanges'] = changeData
    data['saveAuditPassFlag'] = flag? flag : ''
    data.batjBa4 = oprninfo.value
    data.ybZyDisDiag = diseinfo.value
   return data
}
//病案首页效验
const  bingAnShouYeXiaoYan=(flag)=> {
    if (setlinfo.value.operation === '1' || setlinfo.value.operation === '2' || setlinfo.value.operation === '3') {
        if (listIsBlank(oprninfo.value)) {
            return ElMessage.error('选择治疗类型为手术的，至少要有一个手术。')
        }
    }
    if (listIsBlank(diseinfo.value)) {
        return ElMessage.error('诊断不能为空。')
    }
    let sheetVerificationParam = {
        inpatientNo:props.data.inpatientNo,
        admissTimes:props.data.admissTimes
    }
    forceVerifies.value = []
    adviceVerifies.value = []
    sheetVerification(sheetVerificationParam).then((res) => {
        if( !listIsBlank(res.force) ){
            forceVerifies.value = res.force
            adviceVerifies.value = res.advice
            showMessageDrawer.value  = true
        }else {
           qualityTest(flag)
        }
    })
}


/**
 * 获取治疗方式
 * @param val 治疗方式code
 * @returns {*}
 */
function getTreatmentName(val) {
  for (let i = 0; i < operations.length; i++) {
    if (operations[i].code === val) {
      return operations[i].name
    }
  }
  return '无'
}

/**
 * 获取申报类型
 */
function getDeclarationType(val) {
  for (let i = 0; i < decTypes.length; i++) {
    if (decTypes[i].code === val) {
      return decTypes[i].name
    }
  }
  return '无'
}

/* 提交审核信息 */

/* 查看审核信息 */
const shenHeRef = ref(false)
//审核驳回
const keFouShenHe = ref(true)
//审核通过
const shenHeTongGuoFlag = ref(true)
//保存申请按钮
const shenHeSendFlag = ref(true)

const shenHeClick = () => {
  if (stringIsBlank(props.data.shenHeXinXi.id)) {
    return ElMessage.error('您还没有进行申请。')
  }
  shenHeRef.value = true
}

/* 查看审核信息 */

/* 审核操作 确认审核通过 */
const queRenShenHeTongGuo=() =>{
    const data = {
        id: props.data.shenHeXinXi.id,
        auditFlag: 1,
        auditRemark: '审核通过 ❥(^_-)',
        auditStaff: code,
        auditName: name,
    }
    setlUploadAudit(data)
        .then((res) => {
            guanBi()
        })
        .catch((e) => {
        })
}

const shenHeTongGuoShangChuanClick = () => {
  ElMessageBox.confirm('是否通过该审核并上传', '提示', {
    type: 'warning',
  }).then(() => {
    const data = {
      id: props.data.shenHeXinXi.id,
      auditFlag: 1,
      auditRemark: '审核通过 ❥(^_-)',
      auditStaff: code,
      auditName: name,
    }
    setlUploadAudit(data)
        .then((res) => {
          let data = []
          data.push(props.data.upload)
          upldSetlList(data).then((res) => {
            guanBi()
          })
        })
        .catch((e) => {
        })
  })
}

const shenHeBoHuiClick = () => {
  ElMessageBox.prompt('驳回信息', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '驳回信息不能为空',
  })
      .then(({value}) => {
        if (typeof value === 'undefined' || value.length <=0) {
          return ElMessage.error('驳回信息不能为空。')
        }
        const data = {
          id: props.data.shenHeXinXi.id,
          auditFlag: 2,
          auditRemark: value,
          auditStaff: code,
          auditName: name,
        }
        setlUploadAudit(data).then((res) => {
          guanBi()
        })
      })
      .catch((e) => {
      })
}

function guanBi() {
  huanZheXinXiDialog.value = false
  // ctx.emit('shua-xin')
  emit('queryCurrentPage')
}

/* 审核操作 */

/* 数据对比 */
let shuJuDuiBiDialogRef = $ref(false)
const shuJuDuiBi = () => {
  if (stringIsBlank(props.data.shenHeXinXi.id)) {
    return ElMessage.error('您还没有进行申请。')
  }
  shuJuDuiBiDialogRef = true
}
/*drg分组测算*/
const drgGroupTest = () => {
  let newData = {};
  newData = clone(props.data)
  newData.newYbZyDisDiag =  diseinfo.value
  newData.newBatjBa4 =  oprninfo.value
  newData.decType=setlinfo.value.decType
  newData.operation=setlinfo.value.operation
  sendDrgGroupTest(newData).then((res) => {
   return  window.open(res,'');
  })

}

/*质控测算  */
const qualityTest = (flag) => {
    if(flag ==='1'){
        zhiJieBaoCunFlag.value = true
        queRenBaoCunFlag.value = false
        quRenShenHeTongGuoFlag.value = false
    }else if(flag === '2'){
        quRenShenHeTongGuoFlag.value = true
        zhiJieBaoCunFlag.value = false
        queRenBaoCunFlag.value = false
    }else if(flag === '3'){
        quRenShenHeTongGuoFlag.value = false
        zhiJieBaoCunFlag.value = false
        queRenBaoCunFlag.value = false
    }
    else {
        queRenBaoCunFlag.value = true
        zhiJieBaoCunFlag.value = false
        quRenShenHeTongGuoFlag.value = false
    }
  let newData = {};
  newData = clone(props.data)
  newData.newYbZyDisDiag =  diseinfo.value
  newData.newBatjBa4 =  oprninfo.value
  newData.decType=setlinfo.value.decType
  newData.operation=setlinfo.value.operation
  qualityData.value = []
    qualityDialogFlag.value = true
  drgQualityTest(newData).then((res) => {
    if(res.length > 0){
      qualityData.value = res
    }
  })

}





/*申请审核*/

const fqsendAudit = () => {

  ElMessageBox.prompt('申请备注', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '申请备注 100 字 (∩•̀ω•́)⊃-*⋆',
  }).then(({value}) => {
            if (value.length > 100) {
              return ElMessage.error('申请备注超过 100 字。')
            }
    let setlAuditlog = {
      patNo: props.data.inpatientNo,
      times: props.data.admissTimes,
      createCode: code,
      createName: name,
      remark:value
    }
    sendAudit(setlAuditlog).then((res) => {
      guanBi()
    })
        })
          .catch((e) => {
          })
}

/*查询审核历史记录*/
const  querylistSetlAuditLog = () => {
  if (stringIsBlank(props.data.shenHeXinXi.id)) {
    return ElMessage.error('您还没有进行审核申请。')
  }
  refreshAuditLog()
  setlAuditLogFlag.value=true
}
//申请撤回
const shenQingCheHui=()=>{
ElMessageBox.confirm('是否撤销审核', '提示', {
    type: 'warning',
  }).then(() => {
    sendShenQingCheHui(props.data.inpatientNo,props.data.admissTimes).then((res) =>{
        //    刷新审核信息  刷新审核记录   审核通过或审核驳回的 权限刷新下 保存申请的权限
        refreshAuditLog()

        refresShenHeXinXin()
    })
    })
}
//检查检查记录
const  queryJianYanJianCha=() =>{
        jianYanJianChaDialogFlag.value = true
}

//病案首页
const bingAnShouYe=() =>{

    router.push({
        name: 'fillCaseFrontSheet',
        query: {
            patNo: props.data.inpatientNo,
            deptCode: props.data.smallDept,
            times: props.data.admissTimes,
            disdate:props.data.disDate.split(' ')[0]
        }
    })
    huanZheXinXiDialog.value = false
}

//调用电子病历
const queryDianZiBingLi = () => {
  isInHospital(props.data.inpatientNo,props.data.admissTimes).then((res) =>{
    //在院病人
    if(res){
      window.open(getEmrUrl(props.data.inpatientNo,props.data.admissTimes))
    }else {
      window.open(getInEmrUrl(props.data.inpatientNo,props.data.admissTimes))
    }
  })
}
//刷新最新的审核信息
function refresShenHeXinXin() {
    querySetlModifyReq(props.data.inpatientNo,props.data.admissTimes).then((res) => {
        props.data.shenHeXinXi.id =res.id
        props.data.shenHeXinXi.reqOpId= res.reqOpId,
        props.data.shenHeXinXi.reqOpName= res.reqOpName,
        props.data.shenHeXinXi.reqOpDate= res.reqOpDate,
        props.data.shenHeXinXi.reqRemark= res.reqRemark,
        props.data.shenHeXinXi.auditStaff= res.auditStaff,
        props.data.shenHeXinXi.auditName= res.auditName,
        props.data.shenHeXinXi.auditDate= res.auditDate,
        props.data.shenHeXinXi.auditRemark= res.auditRemark,
        props.data.shenHeXinXi.auditFlag= res.auditFlag
        initQuanXian()
        }
    )
}

//刷新审核信息
function refreshAuditLog() {
  listSetlAuditLog(props.data.inpatientNo,props.data.admissTimes).then((res) => {
    if(res.length > 0){
      setlAuditLogData.value = []
      for (let item of res){
        let setAuditLog = {
          id: '',
          createName: '',
          createCode: '',
          createTime: '',
          remark: '',
          auditFlag: '',
          auditType: '',
          auditTypeName: '',
          auditFlagName: ''
        };
        setAuditLog.id = item.id
        setAuditLog.createName = item.createName
        setAuditLog.createTime = item.createTime
        setAuditLog.remark = item.remark
        setAuditLog.auditFlag = item.auditFlag
        setAuditLog.auditType = item.auditType
        if(setAuditLog.auditType == 0){
          setAuditLog.auditTypeName = '申请'
        }else{
          setAuditLog.auditTypeName = '审核'
        }
        setAuditLog.auditFlagName = getAduitFlagName(setAuditLog.auditFlag)
        setlAuditLogData.value.push(setAuditLog)
      }
    }else {
       ElMessage.info('没有审核历史记录。')
    }
  })
}

/* 数据对比结束 */

/* 获取患者各个科室的费用 */
const keShiFeiYongRef = ref(false)
const feiYongDrawer = () => {
  keShiFeiYongRef.value = true
}
/* 获取患者各个科室的费用结束 */

// 老数据的信息
let oldData = $ref({})

const init = () => {
  setlinfo.value = clone(props.data)
  patientBldInfos = clone(props.data.patientBldInfos)
  // 如果新的没有就用老的
  if (stringNotBlank(props.data.shenHeXinXi.id)) {
    if (stringNotBlank(props.data.shenHeXinXi.reqRemark) && props.data.shenHeXinXi.auditFlag === 0) {
      setTimeout(() => {
        shenHeRef.value = true
      }, 1000)
    }
  }
  if(listIsBlank(props.data.newYbZyDisDiag)){
    diseinfo.value = clone(props.data.ybZyDisDiag)
  }else {
    diseinfo.value = clone(props.data.newYbZyDisDiag)
  }
  if(stringNotBlank(props.data.shenHeXinXi.id)){
      oprninfo.value = clone(props.data.newBatjBa4)
  }else {
      oprninfo.value = clone(props.data.batjBa4)
  }

  //初始化拖拽表格
  if (diseinfo.value.length > 0) {
    setTimeout(() => {
      sortableDiseinfo()
    }, 100)
  }
  if (oprninfo.value.length > 0) {
    setTimeout(() => {
      sortableOprninfo()
    }, 100)
  }
  let data = {
    decType: setlinfo.value.decType,
    operation: setlinfo.value.operation,
    diseinfo: diseinfo.value,
    oprninfo: oprninfo.value,
  }
  oldData = clone(data)
  diagnosticQuery.value.medType = props.data.medType
}

function getAduitFlagName(val) {
  switch (val) {
    case 0:
      return '申请审核'
    case 1:
      return '审核通过'
    case 2:
      return '驳回'
    case 3:
      return '正在审核'
  }
}

/**
 * 诊断的拖拽
 */
function sortableDiseinfo() {
  const el = document.querySelector('#sortable-diseinfo tbody')
  //设置拖拽的参数
  const ops = {
    animation: 200, //动画时长
    handle: '.shangxiatuodong', // 拖动的 class
    onEnd({newIndex, oldIndex}) {
      const currRow = diseinfo.value.splice(oldIndex, 1)[0]
      diseinfo.value.splice(newIndex, 0, currRow)
      diseinfo.value.forEach((item, index) => {
        item.disDiagNo = index + 1
      })
    }, //拖拽完成回调函数（新index，旧index）
  }
  Sortable.create(el, ops)
}

function sortableOprninfo() {
  const el = document.querySelector('#sortable-oprninfo tbody')
  const ops = {
    animation: 200, //动画时长
    handle: '.shangxiatuodong',
    onEnd({newIndex, oldIndex}) {
      const currRow = oprninfo.value.splice(oldIndex, 1)[0]
      oprninfo.value.splice(newIndex, 0, currRow)
      oprninfo.value.forEach((item, index) => {
        item.ssxh = index + 1
      })
    }, //拖拽完成回调函数（新index，旧index）
  }
  Sortable.create(el, ops)
}

///////////////// 患者输血量信息
let shuXueXinXi = $ref({
  dialog: false,
  data: {
    id: -1,
    patNo: '',
    times: 0,
    bldCat: '',
    bldCatName: '',
    bldAmt: 0,
    bldUnit: '',
  },
})
let patientBldInfos = $ref([])
const xinZhengShuXueXinXi = () => {
  shuXueXinXi.dialog = true
  shuXueXinXi.data.id = -1
  shuXueXinXi.data.patNo = setlinfo.value.inpatientNo
  shuXueXinXi.data.times = setlinfo.value.admissTimes
}

const modifiedBloodTransfusion = (val) => {
  shuXueXinXi.dialog = true
  shuXueXinXi.data = val
}

const addBloodTransfusionData = (val) => {
  patientBldInfos.push(val)
}

const clickRemoveBloodTransfusion = (index, id) => {
  removeBloodTransfusion(id).then((res) => {
    patientBldInfos.splice(index, 1)
  })
}

///////////////// 患者输血量信息 结束

onMounted(() => {
  init()
    initQuanXian()
    huanZheXinXi.value.inpatientNo =props.data.inpatientNo
    huanZheXinXi.value.admissTimes =props.data.admissTimes
    huanZheXinXi.value.name =props.data.name
    huanZheXinXi.value.sexName =cptSex(props.data.sex)
    huanZheXinXi.value.age = props.data.upload.age
})
//初始化权限
function initQuanXian() {

        if (stringNotBlank(props.data.shenHeXinXi.id) && props.data.shenHeXinXi.auditFlag === 0){
            keFouShenHe.value = false
        }
        if(auditBmzzQuanXian() && props.data.shenHeXinXi.auditFlag == 2 ){
            shenHeTongGuoFlag.value = false
        }else if (auditQuanXian() && (props.data.shenHeXinXi.auditFlag === 0 || props.data.shenHeXinXi.auditFlag == 2)){
            shenHeTongGuoFlag.value = false
        }
        if(!stringNotBlank(props.data.shenHeXinXi.id) || props.data.shenHeXinXi.auditFlag == 2){
            shenHeSendFlag.value = false
        }
}

const methods = [
  {code: 'alpha', name: '拼音'},
  {code: 'code', name: '编码'},
  {code: 'name', name: '名称'},
]

const admissCondData = [
  {code: 1, name: '有'},
  {code: 2, name: '临床未确定'},
  {code: 3, name: '情况不明'},
  {code: 4, name: '无'},
]

const siDiagTypes = [
  {code: '1', name: '西医诊断'},
  {code: '2', name: '中医主病诊断'},
  {code: '3', name: '中医主证诊断'},
]
</script>

<style scoped>
  .maxhight{
    height: 700px;
    overflow: auto;
  }

  :deep(.m-drawer .el-overlay) {
      right: 0;
      left: calc(100vw - 260px);
      background: transparent !important;
  }



  .page-inner {
      padding: 0 20px 10px 26px;
      border-radius: 12px;
      text-align: justify;
  }



  .no-verify-message {
      width: 100%;
      text-align: center;
      margin-top: 50px;
      font-size: 18px;
      color: gray;
  }

  .message-item {
      padding: 6px;
      margin-bottom: 6px;
      border-radius: 4px;
  }

</style>
