
<script lang="ts">
export default {
  name: 'screeningresults' // 常态化筛查-筛查结果
};
</script>
<script setup lang="ts">
import { onMounted, ref, nextTick ,watch} from "vue";
import { ElMessage, ElMessageBox, FormRules,ElTable,ElTree} from "element-plus";
import Page from '@/components/Pagination/page.vue';
import Viewfile from "@/views/component/Viewfile.vue";
import Archive from './archive.vue'
import { queryRegionSchool } from "@/api/regionmodule/school";
import { querySchoolGradeList } from "@/api/regionmodule/schoolGrade";
import { querySchoolClassList } from "@/api/regionmodule/schoolClass";
import { queryStudentVisdataPage,exportStudentResult,exportSchoolHealthNetwork } from "@/api/planscreening";
import { downloadFile } from '@/utils/index'
import { publicTree } from '@/utils/validate';
import { getToken } from '@/utils/auth'
import * as XLSX from 'xlsx';
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();
const url = userStore.webApiBaseUrl;
const queryInfo :any = ref({
  idCode:"",
  studyCode:"",
  isSighted:"",
  gradeId:"",
  classId:"",
  gender:"",
  name:"",
  current:1,
  size:10,
  total:0
})
const searchlist:any = ref({})
const tableData = ref([])
const multipleSelection = ref([])
const defaultcontent = ref(true)
const genderoptions:any = ref([{label:'男',value:'1'},{label:'女',value:'2'}])

const sightedData:any = ref([{label:'是',value:'1'},{label:'否',value:'0'}])

const loading = ref(false)
const isViewfile = ref(false)
const studentInfo = ref({})
// 左侧树
const treeData: any = ref([]);
const treeloading = ref(false)
const defaultProps = { label: "name" }
const checktreelist:any = ref({})
//树形控件类型定义
interface Tree {
  [x: string]: any;
  label: string;
  children?: Tree[];
}
const treeRef = ref<InstanceType<typeof ElTree>>()

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}
const vMove = {
  mounted(el: any) {
    el.onmousedown = function (e: any) {
      var init = e.clientX;
      var parent: any = document.getElementById("silderLeft");
      const initWidth: any = parent.offsetWidth;
      document.onmousemove = function (e) {
        var end = e.clientX;
        var newWidth = end - init + initWidth;
        parent.style.width = newWidth + "px";
      };
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
      };
    };
  }
}
onMounted(() => {
  getTree()
});
// 初始化
const schoolId = ref("")
const handleNodeClick = (data: Tree) => {
  if(data.org_type == null){
    nextTick(() => {
      treeRef.value?.setCurrentKey(schoolId.value);
    });
  }else{
    schoolId.value = data.id
    schoolName.value = data.name
    treeRef.value?.setCurrentKey(data.id);
    queryInfo.value = {
      idCode:"",
      studyCode:"",
      isSighted:"",
      gradeId:"",
      classId:"",
      gender:"",
      name:"",
      current:1,
      size:10,
      total:0
    }
    gradeinData.value = []
    classData.value = []
    getGrade()
    getData()
  }

};
//表格分页
function getData(){
  let params = {
    studentName:queryInfo.value.name,
    idCode:queryInfo.value.idCode,
    studyCode:queryInfo.value.studyCode,
    isSighted:queryInfo.value.isSighted,
    schoolId:schoolId.value,
    gradeId:queryInfo.value.gradeId,
    classId:queryInfo.value.classId,
    gender:queryInfo.value.gender,
    current: queryInfo.value.current,
    size:queryInfo.value.size,
    type:'2'
  };
  console.log(queryInfo.value)
  loading.value = true
  queryStudentVisdataPage(params).then((res:any) => {
    tableData.value = res.data.records;
    queryInfo.value.total = res.data.total
    loading.value = false
  });
}

//导出
function exportclick(){
  let params = {
    studentName:queryInfo.value.name,
    idCode:queryInfo.value.idCode,
    studyCode:queryInfo.value.studyCode,
    isSighted:queryInfo.value.isSighted,
    schoolId:schoolId.value,
    gradeId:queryInfo.value.gradeId,
    classId:queryInfo.value.classId,
    gender:queryInfo.value.gender
  };
  if(radioStr.value == "1"){
    loading.value = true
    exportStudentResult(params).then((response: any) => {
      isExportVisible.value = false
      downloadFile(response,schoolName.value+ '-学生筛查结果', 'xlsx')
      loading.value = false
    }).catch(()=>{
      loading.value = false
    });
  }else if(radioStr.value == "2"){
    loading.value = true
    exportSchoolHealthNetwork(params).then((response: any) => {
      isExportVisible.value = false
      downloadFile(response,schoolName.value+ '-学生体质健康网模板', 'xlsx')
      loading.value = false
    }).catch(()=>{
      loading.value = false
    });
  }
  
}
//查看结果记录表
function viewreportclick(row:any){
  ViewfileUrl.value =  url + '/vision_examine/examine-result/exportVisionForm?id=' + row.id
  isViewfile.value = true
}
function CloseView(){
  isViewfile.value = false
}
// 历史档案
function archiveclick(row:any){
  studentInfo.value = row
  defaultcontent.value = false 
}
function handleSelectionChange(val:any){
  multipleSelection.value = val
}
function resetdata(){
  queryInfo.value = {
    idCode:"",
    studyCode:"",
    isSighted:"",
    gradeId:"",
    classId:"",
    gender:"",
    name:"",
    current:1,
    size:10,
    total:0
  }
  getData()
}
function returnClick(){
  defaultcontent.value = true
}
const regionName = ref("")
function searchInit(){
  treeData.value = publicTree(tempData.value,regionName.value)
}
function checkId(tree:any){
  for(let i=0; i<tree.length;i++){
    if(tree[i].region_id==null && tree[i].children){
      checkId(tree[i].children)
    }else{
      if(tree[i].region_id!=null){
        schoolId.value =  tree[i].id
        schoolName.value =  tree[i].name
        return 
      }
    } 
  }
}
const tempData:any = ref([])
//获取行政区域
function getTree() {
  const params = {
    status:'01',
    name: regionName.value,
  };
  treeloading.value = true
  queryRegionSchool(params).then((res: any) => {
    for(let i=0;i<res.data.length;i++){
      if(res.data[i].org_type == "5"){
        schoolId.value = res.data[i].id
        schoolName.value =res.data[i].name
        break
      }
    }
    tempData.value =  JSON.parse(JSON.stringify(res.data)) 
    treeData.value = publicTree(res.data,"")
    gradeinData.value = []
    classData.value = []
    
    checkId(res.data)
    treeloading.value = false
    if(schoolId.value != ""){
      nextTick(() => {
        treeRef.value?.setCurrentKey(schoolId.value);
        getGrade()
        getData();
      });
    }
  })
  .catch((error:any)=>{
    treeloading.value = false
  })
}
const gradeinData:any = ref([])
const classData:any = ref([])

function getGrade(){
  let params = {
    schoolId: schoolId.value
  }
  classData.value = []
  queryInfo.value.classId = ""
  querySchoolGradeList(params).then((res) => {
    gradeinData.value = res.data;
  }).catch(()=>{
  });
}
function getClass(id:any){
  let params = {
    gradeId: id
  }
  classData.value = []
  queryInfo.value.classId = ""
  if(id != null && id != '' ){
    querySchoolClassList(params).then((res) => {
    classData.value = res.data;
    }).catch(()=>{
    });
  }
  getData()
}
function dateFormat(row: any) {
  const daterc = row;
  if (daterc != null) {
    var date = new Date(daterc);
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
    // 拼接
    return year + "-" + month + "-" + day ;
  }
}
const ViewfileUrl = ref("")
const errorData:any = ref([])
const dialogTableVisible = ref(false)
function handlesSuccess(file: any) {
  loading.value = false
  if(file.code == "0"){
    ElMessage({
      message: "导入成功！",
      type: "success",
    });
    getData()
  }else{
    errorData.value = []
    let msg =  file.msg.split("！！<br>")
    msg.forEach(element => {
      errorData.value.push({name:element})
    });
    dialogTableVisible.value = true
    // ElMessage({
    //   message: file.msg,
    //   type: "error",
    // });
  }

  upload.value.clearFiles()
}
const upload:any = ref(null)
const schoolName:any = ref("")
function handleError(file: any){
  loading.value = false
  ElMessage({
    message: "导入失败！",
    type: "error",
  });
  upload.value.clearFiles()
}
function handlePreview(){
  loading.value = true
}

const isExportVisible = ref(false)
const radioStr = ref("1")
function exportVisibleClick(){
  radioStr.value = "1"
  isExportVisible.value = true
}


function exportToExcel() {
  // 获取表格的 DOM 元素
  const table = document.querySelector('.screeningresults_table_error');

  // 使用 html-to-xlsx 工具将表格转换为工作表
  const ws = XLSX.utils.table_to_sheet(table);
  // 设置列的宽度
  const colWidths = [
    { wch: 5 }, 
    { wch: 70 },
  ];
  ws['!cols'] = colWidths;
  // 创建一个工作簿
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

  // 导出 Excel 文件
  XLSX.writeFile(wb, '导入错误信息.xlsx');
};
</script>

<template>
    <div v-if="defaultcontent" class="printcode-box">
      <aside id="silderLeft">
        <div class="lefttitle">
          <div class="line"></div>
          <div class="treetitle">数据列表</div>
        </div>
          <div style="width:100%;padding: 5px 15px;">
            <el-input v-model="regionName" placeholder="请输入关键字" @input="searchInit"  />
          </div>
          <div>
            <el-tree v-loading="treeloading" ref="treeRef" node-key="id" :data="treeData" default-expand-all 
          :highlight-current="true" :props="defaultProps" :expand-on-click-node="false"
          @node-click="handleNodeClick" style="height: calc(100vh - 260px); overflow: auto;margin-top: 10px;">
        </el-tree>
          </div>
        <div class="moveBtn" v-move>
          <div class="moveBtn-line" v-move></div>
        </div>
      </aside>
      <div class="silderRight">
        <div class="searchinfo">
          <el-input v-model="queryInfo.name" placeholder="请输入学生姓名" style="width: 16%;" clearable />
           
            <el-select v-model="queryInfo.gender" @change="getData"  clearable style="width: 16%;" class="ml-3" placeholder="请选择性别">
              <el-option v-for="item in genderoptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
            <el-input v-model="queryInfo.studyCode" class="ml-3" placeholder="请输入学籍号" style="width: 24%;" clearable />
            <el-input v-model="queryInfo.idCode" class="ml-3" placeholder="请输入身份证号" style="width: 24%;" clearable />
            <el-select v-model="queryInfo.isSighted" class="ml-3" placeholder="是否近视" style="width: 16%" @change="getData" clearable >
              <el-option v-for="item in sightedData" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
        </div>
        <div class="searchinfo">
            <div style="width:50%" class="flex">
              <el-select v-model="queryInfo.gradeId" @change="getClass"  placeholder="请选择年级"  clearable style="width: 33%;" :disabled="schoolId==''|| schoolId==null">
              <el-option v-for="item in gradeinData" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            <el-select v-model="queryInfo.classId" @change="getData" class="ml-3" placeholder="请选择班级" clearable style="width: 33%;" :disabled="queryInfo.gradeId==''|| queryInfo.gradeId==null">
              <el-option v-for="item in classData" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            <div style="width: 34%">
            <el-button type="primary" @click="getData">搜索</el-button>
             <el-button @click="resetdata">重置</el-button>
            </div>
            </div>
            <div style="width:50%;text-align: right; display: flex;justify-content: end;">
             <el-button type="primary" @click="exportVisibleClick">
              <img src="@/assets/visionscreening/exports.png" style="padding-right: 5px;" alt="">导出
            </el-button>
            </div>
        </div>
        <div v-loading="loading">
        <el-table ref="multipleTableRef" :data="tableData" border style="width: 100%; height:calc(100vh - 340px)" @selection-change="handleSelectionChange" :header-cell-style="{background:'rgb(250 250 250)',height:'50px'}">
            <el-table-column type="selection" width="55" fixed />
            <el-table-column fixed prop="student_name" label="姓名" width="100" />
            <el-table-column prop="gender" label="性别" width="80" align="center">
              <template #default="scope">
              <span v-if="scope.row.gender == '1'">男</span>
              <span v-if="scope.row.gender == '2'">女</span>
              </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" width="80" />
            <el-table-column prop="birth_date" label="出生日期" width="120" align="center" />
            <el-table-column prop="nation" label="民族" width="80" align="center" />
            <el-table-column prop="study_code" label="学籍号" width="190" align="center" />
            <el-table-column prop="id_code" label="身份证" width="180" align="center" />
            <el-table-column prop="grade_name" label="所属年级" min-width="90" />
            <el-table-column prop="class_name" label="所属班级" min-width="90" />
            <el-table-column prop="exam_time" label="检查时间" width="140" align="center">
              <template #default="scope">
                {{dateFormat(scope.row.exam_time)}}
              </template>
            </el-table-column>
            <el-table-column prop="vision_left" label="左眼视力" width="60" align="center">
              <template #default="scope">
                <span v-if="scope.row.vision_left !=0 && scope.row.vision_left!=null"> {{scope.row.vision_left.toFixed(1)}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="vision_right" label="右眼视力" width="60" align="center">
              <template #default="scope">
              <span v-if="scope.row.vision_right !=0 && scope.row.vision_right!=null"> {{scope.row.vision_right.toFixed(1)}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sph_left" label="左眼球镜"  width="90" align="center">
              <template #default="scope">
                <span v-if="scope.row.sph_left !=0 && scope.row.sph_left!=null">
                  <span v-if="scope.row.sph_left>0">+{{scope.row.sph_left.toFixed(2)}}D</span>
                  <span v-else>{{scope.row.sph_left.toFixed(2)}}D</span> 
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="sph_right" label="右眼球镜"  width="90" align="center">
            <template #default="scope">
              <span v-if="scope.row.sph_right !=0 && scope.row.sph_right!=null">
                <span v-if="scope.row.sph_right>0">+{{scope.row.sph_right.toFixed(2)}}D</span>
                <span v-else>{{scope.row.sph_right.toFixed(2)}}D</span> 
              </span>
              </template>
            </el-table-column>
            <el-table-column prop="cytdnder_left" label="左眼柱镜"  width="90" align="center">
              <template #default="scope">
                <span v-if="scope.row.cytdnder_left !=0 && scope.row.cytdnder_left!=null">
                  <span v-if="scope.row.cytdnder_left>0">+{{scope.row.cytdnder_left.toFixed(2)}}D</span>
                <span v-else>{{scope.row.cytdnder_left.toFixed(2)}}D</span> 
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="cytdnder_right" label="右眼柱镜"  width="90" align="center">
              <template #default="scope">
                <span v-if="scope.row.cytdnder_right !=0 && scope.row.cytdnder_right!=null">
                  <span v-if="scope.row.cytdnder_right>0">+{{scope.row.cytdnder_right.toFixed(2)}}D</span>
                  <span v-else>{{scope.row.cytdnder_right.toFixed(2)}}D</span> 
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="axies_left" label="左眼轴位"  width="60" align="center"/>
            <el-table-column prop="axies_right" label="右眼轴位"  width="60" align="center"/>
            <el-table-column prop="se_left" label="左眼等效球镜"  width="120" align="center">
              <template #default="scope">
                <span v-if="scope.row.se_left !=0 && scope.row.se_left!=null">
                  <span v-if="scope.row.se_left>0">+{{scope.row.se_left.toFixed(2)}}D</span>
                  <span v-else>{{scope.row.se_left.toFixed(2)}}D</span> 
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="se_right" label="右眼等效球镜"  width="120" align="center">
              <template #default="scope">
                <span v-if="scope.row.se_right !=0 && scope.row.se_right!=null">
                  <span v-if="scope.row.se_right>0">+{{scope.row.se_right.toFixed(2)}}D</span>
                  <span v-else>{{scope.row.se_right.toFixed(2)}}D</span> 
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="rectify_vision_left" label="左眼矫正视力"  width="80" align="center">
              <template #default="scope">
              <span v-if="scope.row.rectify_vision_left !=0 && scope.row.rectify_vision_left!=null"> {{scope.row.rectify_vision_left.toFixed(1)}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="rectify_vision_right" label="右眼矫正视力"  width="80" align="center">
              <template #default="scope">
              <span v-if="scope.row.rectify_vision_right !=0 && scope.row.rectify_vision_right!=null"> {{scope.row.rectify_vision_right.toFixed(1)}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="is_sighted" label="是否近视"  width="60" align="center">
              <template #default="scope">
                <span v-if="scope.row.is_sighted == '0'">否</span>
                <span v-if="scope.row.is_sighted == '1'">是</span>
              </template>
            </el-table-column>
            <el-table-column prop="is_hyperopia" label="远视储备是否充足" width="90" align="center">
              <template #default="scope">
                <span v-if="scope.row.age >12">/</span>
                <span v-else-if="scope.row.is_hyperopia == '1'">否</span>
                <span v-else-if="scope.row.is_hyperopia == '0'">是</span>
              </template>
            </el-table-column>
            <el-table-column prop="is_glasses" label="是否戴镜" width="100" align="center">
              <template #default="scope">
                <span v-if="scope.row.is_glasses == '0'||scope.row.is_glasses == ''||scope.row.is_glasses == null">未知</span>
                <span v-if="scope.row.is_glasses == '4'">不带镜</span>
                <span v-if="scope.row.is_glasses == '3'">角膜塑形镜</span>
                <span v-if="scope.row.is_glasses == '2'">隐形眼镜</span>
                <span v-if="scope.row.is_glasses == '1'">框架眼镜</span>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" width="80" fixed="right" align="center">
              <template #default="scope">
                <div style="display: -webkit-flex;display: flex; justify-content: space-around;-webkit-justify-content: space-around; ">
                  <img src="@/assets/visionscreening/viewreport.png" alt="" title="查看结果记录表" @click="viewreportclick(scope.row)" style="cursor: pointer;">
                  <img src="@/assets/visionscreening/archive.png" alt="" title="历史档案" @click="archiveclick(scope.row)" style="cursor: pointer;">
                </div> 
              </template>
            </el-table-column>
          </el-table>
          <Page class="mt-[20px]" :total="queryInfo.total" v-model:size="queryInfo.size" v-model:current="queryInfo.current"
          @pagination="getData" />
      </div>
      </div>
    <Viewfile v-if="isViewfile"  :showTime="true" :title="'查看结果记录表'"  :type="'docx'" :clientHeight="600" @update="CloseView"/>
    <Viewfile v-if="isViewfile" :url="ViewfileUrl" :showTime="true" :title="'查看结果记录表'"  :type="'docx'" :clientHeight="600" @update="CloseView"/>
    </div>
    <Archive v-if="!defaultcontent" :studentInfo="studentInfo" @returnStudent="returnClick" />
    <el-dialog v-model="dialogTableVisible" title="导入学生错误信息列表" width="800">
      <el-button style="margin-bottom: 10px" type="primary" @click="exportToExcel">导出错误信息</el-button>
      <el-table  class="screeningresults_table_error" :data="errorData" style="height: calc(100vh - 200px);" border>
        <el-table-column type="index" width="90" />
        <el-table-column prop="name" label="内容" />
      </el-table>
    </el-dialog>

    <el-dialog v-model="isExportVisible" title="导出数据" width="350">
      <div v-loading="loading">
        <div>
          <el-radio label="1" size="large" v-model="radioStr">系统模版数据导出</el-radio>
        </div>
        <div>
          <el-radio label="2" size="large" v-model="radioStr">体质健康网模版数据（最近）导出</el-radio>
        </div>
          <!-- <el-radio label="3" size="large" v-model="radioStr">体质健康网模版数据（最优）导出</el-radio> -->
        <div style="display: flex;justify-content: end;margin-top: 10px;">
          <el-button type="primary" @click="exportclick" style="padding:5px;width: 60px;">确定</el-button>
        </div>
      </div>
      
      </el-dialog>

</template>
<style scoped  lang="scss">
  .printcode-box{
    margin-top: 15px;
    height: 100%;
    display: -webkit-flex;
    display: flex;
    .box-search{
      display: flex;
      display: -webkit-flex;
      justify-content: space-between;
      margin-bottom: 20px;
      :deep(){
        .el-input{
            width: 240px;
        }
    }
    }
  }
  #silderLeft {
  width: 242px;
  box-sizing: border-box;
  background: #fff;
  border-radius: 3px;
  position: relative;
  &:hover {
    .moveBtn {
      opacity: 1;
    }
  }
}
/* 拖动条 */
.moveBtn {
  height: 100%;
  width: 15px;
  padding: 0 6px;
  opacity: 0;
  position: absolute;
  right: -15px;
  top: 0;
}

.moveBtn-line {
  width: 100%;
  height: 100%;
  cursor: col-resize;
  user-select: none;
  background-color: #60bfff;
}
.silderRight {
  flex: 1;
  position: relative;
  width: 100%;
  height: calc(100vh - 145px);
  overflow: auto;
  background-color: rgba(255, 255, 255, 1);
  border-radius: 3px;
  padding: 20px;
  padding-bottom: 0px;
  margin-left: 15px;
  box-sizing: border-box;
}
.lefttitle {
  min-width: 130px;
  display: flex;
  align-items: center;
  padding: 10px 20px;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial';
  font-weight: 700;
  font-style: normal;
  font-size: 16px;
  color: #1B1B1B;
  border-bottom: 1px var(--el-border-color) var(--el-border-style);
  margin-bottom: 10px;
  .line{
    border-width: 0px;
    width: 5px;
    height: 14px;
    margin-right: 7px;
    background: inherit;
    background-color: rgba(64, 158, 255, 1);
    border: none;
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
  }
}
:deep(){
   .el-button{
    margin-left: 10px;
  }
  // .el-tree-node__content{
  //   height: 40px;
  //   padding-left: 12px !important;
  //   color: #505050;
  //  }
  //  .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{
  //   color: #409eff;
  //  }
  //  .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content:hover{
  //   color: #409eff;
  //   background-color: #ecf5ff;
  //  }
  // .el-tree-node__content:hover{
  //   color: #409eff;
  //   background-color: transparent;
  //   // #ecf5ff
  // }
  // .el-tree-node__expand-icon{
  //   color: #333333;
  // }
}
.searchinfo{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.my-header{
  display: flex;
  justify-content: space-between;
  align-items: center;
  .icontext{
    font-size: 12px;
    color: #787878;
    width: 25px;
    text-align: center;
    cursor: pointer;
    img{
        padding-left: 4px;
    }
  }
  
}
.QRbox{
    height: calc(100vh - 200px);
    text-align: center;
}
</style>
