<template>
  <el-card class="account-container scheduling">
    <div class="control">
      <p class="control_name">学生基本信息导入</p>
      <div>
        <el-button type="primary" icon="el-icon-download" @click="handleExport" style="margin-left: 0; margin-left: 0; margin-right: 10px"
          >文件导出</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-upload2"
          v-for="(item, index) in fileType"
          :key="index"
          @click="
            uploadShow = true;
            activeIndex = index;
          "
          style="margin-left: 0; margin-right: 10px"
          >导入{{ item.name }}</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-refresh"
          v-if="userInfo.userType == 3"
          @click="handleRefresh"
          style="margin-left: 0; margin-right: 10px"
          >更新学生基本信息</el-button
        >

        <el-input placeholder="搜索" v-model="search" clearable prefix-icon="el-icon-search" @change="searchChange"> </el-input>
      </div>
    </div>
    <el-table v-loading="loading" :data="tableData" stripe v-if="tableData && tableData.length > 0">
      <el-table-column prop="studentName" label="姓名" align="center"> </el-table-column>
      <el-table-column prop="sex" label="性别" align="center"> </el-table-column>
      <!-- <el-table-column prop="className" label="班级" align="center">
      </el-table-column> -->
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <a
            v-if="scope.row.userId"
            @click="handleDetail(scope.row)"
            style="text-decoration: underline; cursor: pointer; margin-right: 10px"
            >查看详情</a
          >
        </template>
      </el-table-column>
    </el-table>
    <el-empty description="暂无内容" v-if="tableData && tableData.length == 0" style="width: 80%"></el-empty>
    <el-dialog :title="fileType[activeIndex].name + '文件'" v-model="uploadShow">
      <el-upload class="uploader" action="" :http-request="upload" :show-file-list="false">
        <i v-if="uploadArr.length > 0" class="el-icon-document-checked uploader-icon" style="border-color: #67c23a; color: #67c23a"></i>
        <i v-else class="el-icon-plus uploader-icon"></i>
        <template #tip>
          <div class="el-upload__tip">上传文件</div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="hideEditBox">取 消</el-button>
          <el-button type="primary" @click="submitUpload">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { formatTimeDay } from '@/utils'
import download from 'downloadjs'
import axios from '@/utils/axios'
export default {
  name: 'UserExtraInfo',
  setup() {
    const formRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const internalInstance = getCurrentInstance()
    const { termId, termName } = route.query

    const state = reactive({
      userInfo: {},
      search: '',
      tableData: [],
      total: 0,
      currentPage: 1,
      loading: false,
      fileType: [
        {
          name: '个人情况',
          download: '/Download/StudentsPersonalConditionFile',
          upload: '/Upload/StudentInfoFile/List',
          add: '/User/UserAllInfoList',
        },
      ],
      uploadShow: false, //导入模板弹出框
      activeIndex: 0, //当前打开的文件上传下标
      uploadArr: [], //待保存的上传文件
    })
    onMounted(() => {
      getUserExtraInfo()
      let userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        state.userInfo = JSON.parse(userInfo)
      }
    })
    // 基本信息列表
    const getUserExtraInfo = () => {
      state.loading = true
      axios
        .post('/User/User/List', {
          StudentName: state.search,
          PageIndex: state.currentPage,
          PageSize: 10,
        })
        .then((res) => {
          // console.log('基本信息列表:', res)
          let tableData = res.data
          state.tableData = tableData
          state.total = res.count
          state.loading = false
        })
        .catch((err) => {
          console.log('err', err)
        })
    }
    // 搜索
    const searchChange = (e) => {
      getUserExtraInfo()
    }
    // 页码改变时
    const handleCurrentChange = (e) => {
      state.currentPage = e
      getUserExtraInfo()
    }
    // 编辑窗点取消
    const hideEditBox = () => {
      state.editBoxShow = false
      state.uploadShow = false
      state.uploadArr = []
    }

    // 下载模板
    // const handleDownload = (item) => {
    //   axios.post(item.download, {}, { responseType: 'blob' },).then(res => {
    //     var blob = new Blob([res]);
    //     download(blob, item.name + '.xlsx')
    //   })
    // }
    // 上传
    const upload = (param) => {
      console.log(param)
      const formData = new FormData()
      formData.append('file', param.file)
      axios.post(state.fileType[state.activeIndex].upload, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then((res) => {
        state.uploadArr = res
      })
    }
    // 保存上传文件
    const submitUpload = () => {
      if (state.uploadArr.length > 0) {
        let uploadArr = state.uploadArr
        // console.log('待保存原始数据：', uploadArr)
        // console.log('待保存数据：', uploadArr)
        axios.post(state.fileType[state.activeIndex].add, uploadArr).then(() => {
          ElMessage.success('导入成功')
          state.uploadShow = false
          state.uploadArr = []
          getUserExtraInfo()
        })
      } else {
        ElMessage.error('文件未上传，或文件中无有效数据')
      }
    }

    // 点击基本信息详情
    const handleDetail = (item) => {
      router.push({ path: '/infoDetail', query: { userId:item.userId,id: item.id } })
    }
    const handleExport = () => {
      let apiUrl = internalInstance.appContext.config.globalProperties.apiUrl
      location.href = `${apiUrl}wwwroot/DownloadExcel/新昌中学教育集团心理健康档案模板.xlsx`
      // axios.post(`${apiUrl}wwwroot/DownloadExcel/新昌中学教育集团心理健康档案模板.xlsx`, {}, { responseType: 'blob' }).then((res) => {
      //   var blob = new Blob([res])
      //   download(blob, item.name + '.xlsx')
      // })
    }
    const handleRefresh = () => {
      axios
        .get(`/User/PullUserListInfo`)
        .then((res) => {
          ElMessage.success('更新成功')
        })
        .catch((err) => {
          ElMessage.success('更新失败')
        })
    }
    return {
      ...toRefs(state),
      searchChange,
      handleCurrentChange,
      hideEditBox,
      // handleDownload,
      submitUpload,
      upload,
      handleDetail,
      handleExport,
      handleRefresh,
    }
  },
}
</script>
<style lang="scss" scoped>
.account-container {
  position: relative;
  min-height: 500px;
}

.control {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .control_name {
    font-size: 23px;
    font-weight: bold;
  }
  .el-input {
    width: 300px;
  }
}
.scheduling {
  background: #fff;
  padding: 0 20px;
  padding-bottom: 40px;
  .week_item {
    text-align: center;
    padding: 10px 0;
    position: relative;
    p {
      margin: 0;
    }
    .control_box {
      display: none;
      width: 100%;
      height: 100%;
      background: #f5f6fa;
      border-radius: 4px;
      border: 1px solid #3a84ff;
      box-sizing: border-box;
      position: absolute;
      top: 0;
      left: 0;
      a {
        display: block;
        width: 100%;
      }
    }
    &:hover {
      .control_box {
        display: flex;
        align-content: center;
        justify-content: center;
        flex-wrap: wrap;
      }
    }
  }
  .uploader {
    margin-bottom: 50px;
  }
  .uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .el-upload__tip {
    display: inline-block;
    font-size: 16px;
    color: #999;
    margin-left: 50px;
  }
}
</style>
