<template>
  <el-container>
    <el-aside>
      <el-radio-group v-model="chaZhaoLeiXing" @change="dianJiLeiXingChaXun">
        <el-radio-button :label="1">新申请</el-radio-button>
        <el-radio-button :label="2">个人模板</el-radio-button>
        <el-radio-button :label="3">科室模板</el-radio-button>
      </el-radio-group>
      <div v-show="chaZhaoLeiXing === 1" style="height: 700px;overflow: auto">
        <JyJcTree yjyc="jy" @nodeClick="nodeClick"/>
      </div>
      <div v-show="chaZhaoLeiXing !== 1">
        <el-table
            :data="jianChaFenLeiShuJu.data"
            :height="windowSize.h / 1.4"
            highlight-current-row stripe>
          <el-table-column label="名称" prop="name">
            <template #default="{row}">
              <el-popover trigger="click" :width="0" placement="right">
                <template #reference>
                  <el-button @click="clickToViewData(row)">{{ row.name }}</el-button>
                </template>
                <template #default>
                  <el-button @click="dianJiQueRenXuanZhong">确定</el-button>
                  <el-button @click="okAndEdit">确定并编辑</el-button>
                  <xc-table :local-data="detailsOfNewInspectionItems"
                            :height="400"
                            @selection-change="xuanZhong"
                            :open-paging="false">
                    <el-table-column type="index"></el-table-column>
                    <el-table-column type="selection"></el-table-column>
                    <el-table-column label="项目名称" prop="orderName" width="220"></el-table-column>
                    <el-table-column label="说明" prop="ybComment"></el-table-column>
                  </xc-table>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button v-if="chaZhaoLeiXing !== 1" type="danger"
                         @click.stop="clickDeleteTemplate( scope.row,scope.$index)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            :current-page="jianChaFenLeiShuJu.currentPage"
            :page-size="20"
            :pager-count="5"
            :total="jianChaFenLeiShuJu.total"
            layout="prev,pager,next,total"
            small
            @current-change="jianChaFenLeiFenYe"/>
      </div>
    </el-aside>
    <el-main>
      <el-button @click="dianJiBaoCunShenQing">保存</el-button>
      <el-button @click="clickSaveTemplate">存为模板</el-button>
      <cuo-wu-xin-xi/>

      <!--   这里是检查的数据信息     -->
      <el-table :data="xuanZhongJianCha.data"
                :header-cell-class-name="starAdd"
                :height="windowSize.h / 1.4">
        <el-table-column label="操作" width="90" fixed="left">
          <template #default="scope">
            <el-button-group>
              <el-button icon="Edit" type="primary" @click="dianJiBianJi(scope.row, scope.$index)"></el-button>
              <el-button icon="Delete" type="danger" @click="deleteInspectionCheck(scope.$index)"></el-button>
            </el-button-group>
          </template>
        </el-table-column>
        <el-table-column label="项目编码" prop="orderCode"></el-table-column>
        <el-table-column label="项目名称" prop="orderName" show-overflow-tooltip></el-table-column>
        <el-table-column label="检查时间" prop="startTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="执行科室" prop="execDeptName"></el-table-column>
        <el-table-column label="急诊标识">
          <template #default="scope">
            <span v-if="scope.row.jzFlag === 1">√</span>
          </template>
        </el-table-column>
        <el-table-column label="自费">
          <template #default="scope">
            <span v-if="scope.row.ybSelfFlag === 1">√</span>
          </template>
        </el-table-column>
        <el-table-column v-if="!jianCha" label="标本" prop="inspectStuffName" show-overflow-tooltip></el-table-column>
        <el-table-column :label="jianCha ? '病室摘要' : '申请说明'" prop="reqComment"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="jianCha" label="体征信息" prop="reqTzComment" show-overflow-tooltip></el-table-column>
        <el-table-column v-if="jianCha" label="辅检结果" prop="reqOtherResult" show-overflow-tooltip></el-table-column>
        <el-table-column v-if="jianCha" label="临床诊断" prop="diagText" show-overflow-tooltip></el-table-column>
      </el-table>
    </el-main>
  </el-container>

  <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>
  <BianJiJianYan ref="bianJiRef"
                 :jian-cha="jianCha"
                 @fanYe="bianJiFanYe"/>
</template>

<script setup name="TianJiaJianChaJianYan">
import {computed, onMounted, ref} from 'vue'
import {
  baoCunJianChaJianYanMuBan,
  baoCunJianYanJianCha,
  chaKanFenLeiXiangQing,
  jianChaJianYanFenLei,
  jianChaJianYanMuBanMing,
  shanShuJianChaMuBan,
} from '@/api/zhu-yuan-yi-sheng/jian-yan-jian-cha-shen-qing'
import store from '@/store'
import {clone} from '@/utils/clone'
import {ElMessage, ElMessageBox} from 'element-plus'
import {listNotBlank, stringNotBlank} from '@/utils/blank-utils'
import BianJiJianYan
  from '@/views/hospitalization/zhu-yuan-yi-sheng/jian-cha-jian-yan-shen-qing/EditInspection.vue'
import {
  cuoWuXinXi,
  huanZheXinXi,
  youWuXuanZheHuanZhe,
  xuanZhongJianCha
} from '@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng'
import {getServerDateApi, yaoPinXiangMuPiPeiYiBao} from '@/api/public-api'
import CuoWuXinXi from '@/components/zhu-yuan-yi-sheng/CuoWuXinXi.vue'
import Sleep from '@/utils/sleep'
import XcTable from "@/components/xiao-chan/xc-table/XcTable.vue";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import JyJcTree from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/jy-jc-tree/JyJcTree.vue";
import {xcMessage} from "@/utils/xiaochan-element-plus";

const props = defineProps({
  jianCha: {
    type: Boolean,
    default: true,
  },
})
const chaZhaoLeiXing = ref(1)

const windowSize = computed(() => {
  return store.state.app.windowSize
})

const detailsOfNewInspectionItems = ref([])

const jianChaFenLeiShuJu = ref({
  currentPage: 1,
  total: 0,
  data: [],
})
const bianJiRef = ref(null)
const baoCunMuBanRef = ref()
const tcNameRef = $ref(null)
const baoCunMuBan = ref({
  dialog: false,
  tcName: '',
  orderType: 1,
  sortNo: 0,
  tcFlag: 1,
  fuGaiYuanShuJu: false,
  chongFuMing: false,
})

const dianJiLeiXingChaXun = () => {
  jianChaFenLeiShuJu.value.total = 0
  jianChaFenLeiShuJu.value.currentPage = 1
  jianChaJianYanFenLei(0, 1, chaZhaoLeiXing.value, props.jianCha).then((res) => {
    jianChaFenLeiShuJu.value.data = res.records
    jianChaFenLeiShuJu.value.total = res.total
  })
}

const jianChaFenLeiFenYe = (val) => {
  jianChaFenLeiShuJu.value.currentPage = val
  jianChaJianYanFenLei(jianChaFenLeiShuJu.value.total, val, chaZhaoLeiXing.value, props.jianCha).then((res) => {
    jianChaFenLeiShuJu.value.data = res.records
  })
}

const xuanZhong = (val) => {
  xuanZhongJianCha.value.daiXuanZhong = val
}

const okAndEdit = () => {
  dianJiQueRenXuanZhong()
  dianJiBianJi(xuanZhongJianCha.value.data[0], 0)
}

const dianJiQueRenXuanZhong = () => {
  if (xuanZhongJianCha.value.daiXuanZhong.length === 0) {
    BizException(ExceptionEnum.MESSAGE_ERROR, "请先选中数据")
  }
  let tiShi = false;
  xuanZhongJianCha.value.daiXuanZhong.forEach((item) => {
    if (xuanZhongJianCha.value.weiBianMa.indexOf(item.orderCode) > -1) {
      tiShi = true
    } else {
      xuanZhongJianCha.value.data.push(clone(item))
      xuanZhongJianCha.value.weiBianMa.push(clone(item.orderCode))
      console.log(xuanZhongJianCha.value.data)
    }
  })
  if (tiShi) {
    ElMessage.error('请勿重复添加。')
  }
}

const dianJiBianJi = (row, index) => {
  bianJiRef.value.daKaiBenDuiHua(row, index, xuanZhongJianCha.value.data.length)
}

const dianJiBaoCunShenQing = () => {
  if (xuanZhongJianCha.value.data.length < 0) {
    ElMessage.error('请选择数据')
    return
  }
  if (youWuXuanZheHuanZhe()) {
    clickSaveTemplate()
    return
  }
  let listCode = []
  xuanZhongJianCha.value.data.forEach((item) => {
    listCode.push(item.orderCode + '-00')
  })
  yaoPinXiangMuPiPeiYiBao(listCode).then((res) => {
    if (stringNotBlank(res)) {
      cuoWuXinXi.value = res
      ElMessageBox.confirm(res, '提示', {
        type: 'warning',
        dangerouslyUseHTMLString: true,
      }).then(() => {
        baoCunShuJu()
      }).catch(() => {
      })
    } else {
      baoCunShuJu()
    }
  })
}

function baoCunShuJu() {
  ElMessageBox.confirm('确定要保存这些数据吗？', '提示', {
    type: 'warning',
  }).then(() => {
    let data = huanZheXinXi.value
    data.list = xuanZhongJianCha.value.data
    data.reqType = props.jianCha ? 3 : 2
    baoCunJianYanJianCha(data)
        .then((res) => {
          xuanZhongJianCha.value.weiBianMa = []
          xuanZhongJianCha.value.data = []
        })
        .catch((e) => {
          cuoWuXinXi.value = e
        })
  }).catch(() => {
  })
}


const clickToViewData = ({code, bwCode}) => {
  if (!props.jianCha) {
    bwCode = ''
  }
  chaKanFenLeiXiangQing(code, chaZhaoLeiXing.value === 1 ? bwCode : 'mb', props.jianCha).then((res) => {
    if (listNotBlank(res)) {
      detailsOfNewInspectionItems.value = res
    } else {
      ElMessage.error('没有找到对应的数据')
    }
  })
}

const clickDeleteTemplate = ({code}, index) => {
  ElMessageBox.confirm('是否要删除该模板', '提示', {
    type: 'warning',
  })
      .then(() => {
        shanShuJianChaMuBan(code, store.state.user.info.deptCode).then(() => {
          jianChaFenLeiShuJu.value.data.splice(index, 1)
        })
      })
      .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, props.jianCha ? '3' : '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 = props.jianCha ? 3 : 2
  baoCunMuBan.value.list = xuanZhongJianCha.value.data
  baoCunMuBan.value.tcExec = store.state.user.info.deptCode
  console.log(baoCunMuBan.value)
  baoCunJianChaJianYanMuBan(baoCunMuBan.value).then((res) => {
    dianJiLeiXingChaXun()
    baoCunMuBan.value.dialog = false
  })
}

const bianJiFanYe = (val) => {
  let index = val.val - 1
  bianJiRef.value.daKaiBenDuiHua(xuanZhongJianCha.value.data[index], index, xuanZhongJianCha.value.data.length)
}

const clickSaveTemplate = async () => {
  if (xuanZhongJianCha.value.data.length > 0) {
    baoCunMuBan.value.dialog = true
    await Sleep(200)
    tcNameRef.focus()
  } else {
    ElMessage.error('请选择数据')
  }
}

const starAdd = (obj) => {
  let index = [0, 1, 2, 3, 6, 7, 8, 9]
  if (index.indexOf(obj.columnIndex) > -1) {
    return 'star'
  }
}


const nodeClick = async (val) => {
  if (val.code.length < 5) {
    BizException(ExceptionEnum.LOGICAL_ERROR, '无法添加目录')
  }
  let temp = {
    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
  }
  if (xuanZhongJianCha.value.weiBianMa.indexOf(temp.orderCode) > -1) {
    xcMessage.error('请勿重复添加。')
  } else {
    xuanZhongJianCha.value.weiBianMa.push(temp.orderCode)
    xuanZhongJianCha.value.data.push(temp)
  }
}

const deleteInspectionCheck = (index) => {
  xuanZhongJianCha.value.data.splice(index, 1)
  xuanZhongJianCha.value.weiBianMa.splice(index, 1)
}

onMounted(() => {
  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>
