<template>
  <el-page-header content="上传报告" style="margin-bottom: 30px" @back="this.$router.push('/Home')"/>
  <el-card style="padding-left: 60px;padding-right: 60px">
    <el-descriptions title="个人信息" border>
      <el-descriptions-item label="用户ID">{{ userInfo.userId }}</el-descriptions-item>
      <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
      <el-descriptions-item label="身份">{{ userInfo.role }}</el-descriptions-item>
    </el-descriptions>
  </el-card>
  <el-card style="margin-top: 10px">
    <el-table :data="itemList" style="width: 100%">
      <el-table-column fixed prop="experimentName" label="项目名称"/>
      <el-table-column prop="className" label="上课班级"/>
      <el-table-column label="附件">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="download(scope.row.annex)">下载</el-button>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-upload :on-change="fileChange" v-if="scope.row.filePath === null ||scope.row.filePath === '' "
                     :show-file-list="false"
                     :auto-upload="false">
            <el-button link type="primary" size="small" @click="change(scope.row)">上传</el-button>
          </el-upload>
          <el-button link type="primary" size="small" v-if="scope.row.filePath !== null && scope.row.filePath !== ''"
                     @click="download(scope.row.filePath)">下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="getList"
        @current-change="getList"
        v-model:current-page="form.pageNum"
        v-model:page-size="form.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="form.total"/>
  </el-card>
</template>

<script>
import {computed, ref} from 'vue'
import {ElMessage} from "element-plus";

let formData = new FormData;
const size = ref('')
computed(() => {
  const marginMap = {
    large: '32px',
    default: '28px',
    small: '24px',
  }
  return {
    marginTop: marginMap[size.value] || marginMap.default,
  }
});
export default {
  name: 'Sub',
  data() {
    return {
      itemList: [],
      upID: "",
      form: {
        name: '',
        className: '',
        time: '',
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      exFrom: {
        id: '',
        experimentId: '',
        studentId: '',
        filePath: '',
        score: ''
      },
      size: '',
      userInfo: {
        userId: '',
        role: '',
        username: '',
        newPassword: '',
        oldPassword: ''
      },
      pwdVisable: false
    }
  },
  mounted() {
    this.getList()
    this.userInfo.role = window.sessionStorage.getItem('role');
    this.userInfo.name = window.sessionStorage.getItem("username");
    this.userInfo.username = window.sessionStorage.getItem("username");
    this.userInfo.userId = window.sessionStorage.getItem("userId");
  },
  methods: {
    change(row) {
      this.exFrom.experimentId = row.experimentId;
      this.exFrom.studentId = row.studentId;
      this.exFrom.filePath = row.filePath;
      this.exFrom.score = row.score;
      this.exFrom.id = row.recordId;
    },
    update() {
      this.$http({
        url: "/records",
        method: 'put',
        data: this.exFrom
      }).then(({data}) => {
        if (data.code !== 200) {
          ElMessage({
            message: '更新成功',
            type: 'success',
          })
        } else {
          this.getList()
        }
      })

    },
    getList() {
      this.$http({
        url: "/getRecordST/" + this.form.pageNum + "/" + this.form.pageSize,
        method: 'post',
        data: {
          studentId: this.userInfo.userId,
          className: '',
        }
      }).then(({data}) => {
        if (data.code !== 200) {
          ElMessage({
            message: '信息获取失败',
            type: 'error',
          })
        } else {
          this.itemList = data.list;
          this.form.total = data.total;
        }
      })
    },
    download(fileName) {
      this.$http({
        url: '/download/' + fileName,
        method: 'GET',
        responseType: 'blob',
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
      }).catch((error) => {
        if (error.response && error.response.status === 404) {
          this.$message.error('文件不存在！');
        } else {
          // 对于其他错误，可以选择不同的处理方式
          this.$message.error('下载文件时发生错误！');
        }
      });
    },
    fileChange(files, fileList) {
      formData.append('file', files.raw)
      files = null;
      this.loading = true;
      this.$http({
        method: 'post',
        url: '/upload',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.$notify({
            title: '上传成功',
            message: res.data.msg,
            type: 'success'
          });
          this.exFrom.filePath = res.data.fileName;
          this.update();
        } else {
          this.$notify({
            title: '文件解析失败',
            message: res.data.msg,
            type: 'error'
          });
        }
        formData = null;
        formData = new FormData();
        this.loading = false;
      })
    },
  }
}
</script>
<style>
.btn-Ex {
  display: inline-flex;
  justify-content: center;
  text-align: center;
  width: 100%;
}
</style>

