<template>

  <div style="display: flex;height: 100% ; width: 100%">
    <div style="width: 220px">
      <CyFlex>
        <template #header>
          <el-radio-group v-model="chaZhaoLeiXing" @change="dianJiLeiXingChaXun">
            <el-radio-button :value="1">新申请</el-radio-button>
            <el-radio-button :value="2">个人模板</el-radio-button>
            <el-radio-button :value="3">科室模板</el-radio-button>
          </el-radio-group>
        </template>
        <div style="height: 100% ; width: 100%">
          <div v-show="chaZhaoLeiXing === 1" style="height: 100% ; width: 100%">
            <JyJcTree yjyc="jy" @nodeClick="nodeClick"/>
          </div>
          <div v-show="chaZhaoLeiXing !== 1" style="height: 100% ; width: 100%">
            <jc-jy-template :data="templateData"
                            :is-check="false"
                            @del-click="deleteTemplate"
                            @node-click="rowClick"/>
          </div>
        </div>
      </CyFlex>
    </div>

    <div style="flex: 1; height: 100%;width: 0">
      <JianChaJianYanTable :data="jyList"
                           @del-click="delCLick"
                           v-model:public-data="jyExtraInformation"/>
    </div>
  </div>


  <el-dialog v-model="baoCunMuBan.dialog" center title="保存检查模板" width="30%">
    <el-form ref="baoCunMuBanRef" :model="baoCunMuBan" :rules="baoCunMuBanJiaoYan" label-width="80px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="模板类型" prop="orderType">
            <el-radio-group v-model="baoCunMuBan.orderType">
              <el-radio-button :label="1">个人</el-radio-button>
              <el-radio-button :label="2">科室</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="名称" prop="tcName">
            <el-input v-model="baoCunMuBan.tcName" ref="tcNameRef" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="排序码" prop="sortNo">
            <el-input-number v-model="baoCunMuBan.sortNo" :max="9999" :min="0"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="录入方式" prop="tcFlag">
            <el-radio-group v-model="baoCunMuBan.tcFlag">
              <el-radio-button :label="0">自动选择</el-radio-button>
              <el-radio-button :label="1">手工录入</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-button @click="dianJiBaoCunMuBan(baoCunMuBanRef)">提交</el-button>
          <el-button>关闭</el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>

</template>

<script setup>
import {onMounted, ref} from 'vue'
import {
  baoCunJianChaJianYanMuBan,
  baoCunJianYanJianCha,
  getTemplateGrouping,
  jianChaJianYanMuBanMing,
  shanShuJianChaMuBan,
} from '@/api/zhu-yuan-yi-sheng/jian-yan-jian-cha-shen-qing'
import {ElMessageBox} from 'element-plus'
import {stringIsBlank, stringNotBlank} from '@/utils/blank-utils'
import {
  cuoWuXinXi,
  huanZheXinXi,
  jsQueryYzData,
  jyExtraInformation,
  jyJcRestriction,
  jyList,
  jyProxy,
  yzMitt
} from '@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng'
import {getServerDateApi, yaoPinXiangMuPiPeiYiBao} from '@/api/public-api'
import Sleep from '@/utils/sleep'
import {BizException, ExceptionEnum} from "@/utils/BizException";
import JyJcTree from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/jy-jc-tree/JyJcTree.vue";
import JianChaJianYanTable
  from "@/views/hospitalization/zhu-yuan-yi-sheng/jian-cha-jian-yan-shen-qing/components/public/JianChaJianYanTable.vue";
import JcJyTemplate
  from "@/views/hospitalization/zhu-yuan-yi-sheng/jian-cha-jian-yan-shen-qing/components/public/JcJyTemplate.vue";
import CyFlex from "@/components/cy/flex/src/CyFlex.vue";
import {CyMessageBox} from "@/components/cy/message-box";
import XEUtils from 'xe-utils'
import {useUserStore} from "@/pinia/user-store";

const chaZhaoLeiXing = ref(1)
const userInfo = useUserStore().userInfo
const baoCunMuBanRef = ref()
const tcNameRef = ref(null)
const baoCunMuBan = ref({
  dialog: false,
  tcName: '',
  orderType: 1,
  sortNo: 0,
  tcFlag: 1,
  fuGaiYuanShuJu: false,
  chongFuMing: false,
})

const templateData = ref()
const dianJiLeiXingChaXun = () => {
  if (chaZhaoLeiXing.value !== 1) {
    getTemplateGrouping('2', chaZhaoLeiXing.value).then((res) => {
      templateData.value = res
    });
  }
}


const rowClick = async (data) => {
  if (data.isTheParentNode === '2') {
    const temp = XEUtils.clone(data, true);
    temp.startTime = await getServerDateApi();
    jyProxy.push(temp);
  }
}

const delCLick = (index) => {
  jyProxy.delIndex(index)
}

const dianJiBaoCunShenQing = async () => {
  jyProxy.emptyError();

  const listCode = jyProxy.eachAndReturnList((item) => item.orderCode + '-00')
  const 未匹配医保码 = await yaoPinXiangMuPiPeiYiBao(listCode).catch(() => '')
  cuoWuXinXi.value = 未匹配医保码
  if (stringNotBlank(未匹配医保码)) {
    await CyMessageBox.confirm({
      message: '未匹配医保码',
      title: '提示，仅提示，请继续点击确认完成保存。',
      confirmButtonText: '继续录入',
      dangerouslyUseHTMLString: true,
      type: 'warning',
    })
  }
  baoCunShuJu().then(() => {
  })
}

async function baoCunShuJu() {
  await CyMessageBox.confirm({
    message: '确定要保存这些数据吗? ',
    title: '提示',
    type: 'warning',
  })

  let data = XEUtils.clone(huanZheXinXi.value, true)
  data.list = jyList.value
  data.reqType = 2
  await baoCunJianYanJianCha(data)
  jyProxy.clear();
  // 查询医嘱
  jsQueryYzData().then(() => {
  })
}

const deleteTemplate = (data) => {
  ElMessageBox.confirm('是否要删除该模板', '提示', {
    type: 'warning',
  }).then(() => {
    shanShuJianChaMuBan(data.code, userInfo.deptCode).then(() => {
      dianJiLeiXingChaXun()
    })
  }).catch(() => {
  })
}

const baoCunMuBanJiaoYan = ref({
  tcName: [
    {required: true, message: '名称不能为空', trigger: 'blur'},
    {min: 1, max: 30, message: '长度在 1 到 30 个字', trigger: 'blur'},
  ],
  orderType: [{required: true, message: '名称不能为空', trigger: 'blur'}],
  sortNo: [{required: true, message: '名称不能为空', trigger: 'blur'}],
  tcFlag: [{required: true, message: '名称不能为空', trigger: 'blur'}],
})

const dianJiBaoCunMuBan = async (form) => {
  if (!form) return
  try {
    await form.validate()
    jianChaJianYanMuBanMing(baoCunMuBan.value.tcName, '2').then((res) => {
      if (res) {
        ElMessageBox.confirm('已经存在相同的模板名称，是否覆盖数据', '温馨提示', {
          type: 'warning',
          distinguishCancelAndClose: true,
          confirmButtonText: '覆盖',
          cancelButtonText: '取消',
        })
            .then(() => {
              faSongBaoCunMuBan()
            })
            .catch((e) => {
            })
      } else {
        faSongBaoCunMuBan()
      }
    })
  } catch (e) {
    console.log(e)
  }
}

const faSongBaoCunMuBan = () => {
  baoCunMuBan.value.reqType = 2
  baoCunMuBan.value.list = jyList.value
  baoCunMuBan.value.tcExec = userInfo.deptCode
  baoCunJianChaJianYanMuBan(baoCunMuBan.value).then((res) => {
    dianJiLeiXingChaXun()
    baoCunMuBan.value.dialog = false
  })
}

const clickSaveTemplate = async () => {
  jyProxy.emptyError();
  baoCunMuBan.value.dialog = true
  await Sleep(200)
  tcNameRef.value.focus()
}

const nodeClick = async (val) => {
  if (val.code.length < 5) {
    BizException(ExceptionEnum.LOGICAL_ERROR, '无法添加目录')
  }
  jyJcRestriction(val)
  let temp = {
    classes: val.classes,
    orderType: "",
    execDept: val.execUnit,
    execDeptName: val.execUnitName,
    inspectStuff: val.inspectStuff,
    orderCode: val.code,
    startTime: await getServerDateApi(),
    inspectStuffName: val.inspectStuffName,
    orderName: val.name,
    checkFlag: "0",
    jzFlag: 0,
    ybSelfFlag: 0,
    note: val.note,
    collectionInfo: val.ccollectionInfo,
    genderRestriction: val.genderRestriction,
    minAgeRestriction: val.minAgeRestriction,
    maxAgeRestriction: val.maxAgeRestriction
  };
  jyProxy.push(temp)
}


onMounted(() => {
  yzMitt.on('jySave', () => {
    jyProxy.emptyError();

    function error() {
      if (stringNotBlank(huanZheXinXi.value.inpatientNo)) {
        BizException(ExceptionEnum.LOGICAL_ERROR, "根据病理科要求，检验有病理项目需要填写，病史摘要、体征信息、相关辅检结果、临床诊断。")
      }
    }

    let isPathology = false

    jyProxy.forEach((item) => {
      if (item.classes === '038') {
        item.reqComment = jyExtraInformation.value.reqComment
        item.reqTzComment = jyExtraInformation.value.reqTzComment
        item.reqOtherResult = jyExtraInformation.value.reqOtherResult
        item.diagCode = jyExtraInformation.value.diagCode
        item.diagText = jyExtraInformation.value.diagText;
        isPathology = true
      }
    })

    if (isPathology) {
      if (stringIsBlank(jyExtraInformation.value.reqComment)) {
        error()
      }
      if (stringIsBlank(jyExtraInformation.value.reqTzComment)) {
        error()
      }
      if (stringIsBlank(jyExtraInformation.value.reqOtherResult)) {
        error();
      }
      if (stringIsBlank(jyExtraInformation.value.diagCode)) {
        error()
      }
    }

    // 没有选择患者启动保存模板
    if (stringIsBlank(huanZheXinXi.value.inpatientNo)) {
      BizException(ExceptionEnum.LOGICAL_ERROR, "请先选择患者后保存。")
    }

    dianJiBaoCunShenQing();
  })

  yzMitt.on('jySaveTemplate', () => {
    clickSaveTemplate()
  })

  dianJiLeiXingChaXun()
})

</script>

<style scoped>
:deep(.el-table .children-row) {
  background: rgba(145, 247, 145, 0.5);
}

:deep(.el-table) {
  --el-table-row-hover-background-color: #85dbfd7a;
}
</style>
