
<script lang="ts">
export default {
  name: 'importdata' // 数据管理-导入数据
};
</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 { schoolIdsPlanIdQueryStudent,exportExamineResultStudent,updateExamineResult } from "@/api/planscreening";
import { downloadFile } from '@/utils/index'
import { getToken } from '@/utils/auth'
import * as XLSX from 'xlsx';
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();
const url = userStore.webApiBaseUrl;
const tableRowClassName = ({
    row,
    rowIndex,
}: {
    row: any
    rowIndex: number
}) => {
    if (row.is_sighted == 1) {
        return 'is_sightedbg'
    }
    return ''
}

const props:any = defineProps({
  planInfo: {
    required: false,
    type: Object,
    default: {}
  }
})
const planSchoolInfo:any = ref({})
const checkList=ref([])
const tableData = ref([])
watch(
  () => props.planInfo,
  (newVal: any) => {
    planSchoolInfo.value = newVal
    checkList.value = []
    tableData.value =[]
  },
  { immediate: true }
);

const queryInfo :any = ref({
  schoolId:"",
  gradeId:"",
  classId:"",
  gender:"",
  name:"",
  current:1,
  size:10,
  total:0
})

const loading = ref(false)
// 左侧树
onMounted(() => {
  planSchoolInfo.value = props.planInfo
});

function download(){

let params = {
    planId:  planSchoolInfo.value.id,
    schoolIds:checkList.value.join(',')

  };
  exportExamineResultStudent(params).then((response: any) => {
    downloadFile(response,planSchoolInfo.value.plan_name+ '-学生基本信息', 'xlsx')
  });
}
function checkchange(list:any){
  let tempSchoolName = []
  for(let i = 0;i<list.length;i++){
    for(let j = 0;j<planSchoolInfo.value.schoolList.length;j++){
      if(planSchoolInfo.value.schoolList[j].id == list[i]){
        tempSchoolName.push(planSchoolInfo.value.schoolList[j].name)
      }
    }   
  }
  schoolNames.value = tempSchoolName.join(",")
  if(list.length != 0){
    getData()
  }else{
    tableData.value =[]
  }
}
function getData(){
  let params = {
    planId:  planSchoolInfo.value.id,
    schoolIds:checkList.value.join(','),
    size:queryInfo.value.size,
    current:queryInfo.value.current
    }
    schoolIdsPlanIdQueryStudent(params).then((res) => {
        tableData.value = res.data.records;
        queryInfo.value.total = res.data.total;
      }).catch(()=>{
      });
}
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();
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    // 拼接
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  }
}
const upload:any = ref(null)
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 schoolNames:any = ref("")
function handleError(file: any){
  loading.value = false
  ElMessage({
    message: "导入失败！",
    type: "error",
  });
  upload.value.clearFiles()
}
function handlePreview(){
  loadingtext.value = "正在导入数据，请耐心等待！"
  loading.value = true
}

const loadingtext = ref("")

function exportToExcel() {
  // 获取表格的 DOM 元素
  const table = document.querySelector('.importdata_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 class="importdata-box">
      <div class="importdata-box-top">
        <el-checkbox-group v-model="checkList" v-for="(item,index) in planSchoolInfo.schoolList"  @change="checkchange">
          <el-checkbox  :value="item.id" :key="item.id" style="margin-right: 10px;">{{ item.name }}</el-checkbox>
        </el-checkbox-group>

        <!-- <div v-for="(item,index) in planSchoolInfo.schoolList" :key="index" style="margin-right: 10px;min-width: 150px;" >
            <el-checkbox v-model="item.id" :label="item.name" />
        </div> -->
      </div>
      <div class="importdata-box-bottom">
        <div style="margin-bottom: 15px; display: flex;">
            <el-button type="primary" @click="download" :disabled="checkList.length==0">
              <img src="@/assets/tableicon/download.png" style="padding-right: 5px;" alt="">下载模板
            </el-button>
            <el-upload
                :disabled="checkList.length==0"
                ref="upload"
                accept=".xlsx"
                class="upload-demo"
                :action=" url + '/vision_examine/examine-result/ImportExamineResultStudent/?planId=' + planSchoolInfo.id +'&schoolNames=' + schoolNames "
                :headers="{ token: getToken() }" 
                :show-file-list="false"
                :before-upload="handlePreview"
                :on-success="handlesSuccess"
                :on-error="handleError">
                <el-button type="primary" :disabled="checkList.length==0"  style="margin: 0 10px;"><img src="@/assets/MenuIcon/u455.png" alt=""  style="margin-right: 5px;">导入数据</el-button>
              </el-upload> 
        </div>
        <el-table v-loading="loading" :element-loading-text="loadingtext" :data="tableData" border :row-class-name="tableRowClassName"
           style="width: 100%; height:calc(100vh - 570px)" :header-cell-style="{background:'rgb(250 250 250)',height:'50px'}">
            <el-table-column fixed type="index" width="55" label="序号" align="center" />
            <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="185" align="center" />
            
            <el-table-column prop="school_name" label="所属学校" min-width="120" />
            <el-table-column prop="grade_name" label="所属年级" min-width="120" />
            <el-table-column prop="class_name" label="所属班级" min-width="100" />
            <el-table-column prop="exam_status" label="状态" align="center">
            <template #default="scope">
              <span v-if="scope.row.exam_status == '00'">未检</span>
              <span v-if="scope.row.exam_status == '01'">已检</span>
              <span v-if="scope.row.exam_status == '02'">漏检</span>
              </template>
            </el-table-column>
            <el-table-column prop="exam_time" label="检查时间" width="120" 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="id_code" label="身份证" width="180" align="center" />
            <el-table-column prop="is_view" label="家长是否查看"  width="80" align="center">
              <template #default="scope">
                <span v-if="scope.row.is_view == '1'">是</span>
                <span v-else>否</span>
              </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>
      <el-dialog v-model="dialogTableVisible" title="导入学生错误信息列表" width="800">
        <el-button style="margin-bottom: 10px" type="primary" @click="exportToExcel">导出错误信息</el-button>

        <el-table class="importdata_table_error" :data="errorData" style="height: calc(100vh - 200px);" border>
          <el-table-column type="index" label="序号" width="90" />
          <el-table-column prop="name" label="内容" />
        </el-table>
      </el-dialog>
    </div>
</template>
<style scoped  lang="scss">
  .importdata-box{
    height: calc(100vh - 285px);
    width: 100%;
    padding-top: 15px;
    .importdata-box-top{
      height: 125px;
      width: 100%;
      background: #fff;
      border-radius: 5px;
      box-shadow: 0px 0px 10px rgba(219, 225, 236, 0.498039215686275);
      margin-bottom: 15px;
      display: flex;
      padding: 10px;
      flex-wrap: wrap;
      align-content: flex-start;
      overflow: auto;
    }
    .importdata-box-bottom{
      width: 100%;
      height: calc(100vh - 440px);
     background: #fff;
      border-radius: 5px;
      box-shadow: 0px 0px 10px rgba(219, 225, 236, 0.498039215686275);
      padding: 15px;
    }
  }
  .dialog-footer {
    display: flex;
    display: -webkit-flex;
    justify-content: flex-end;
    -webkit-justify-content: flex-end;
  }
</style>
