<template>

  <el-page-header content="用户管理" style="margin-bottom: 30px" @back="this.$router.push('/Login')"/>
  <el-card style="max-width: 1200px;margin:0 auto;background-color: #f9fafb">
    <div style="display: flex;justify-content: space-between;align-items: center">
      <el-space>
        <el-button type="primary" style="margin-right: 10px;" @click="dialogVisibleForAdd = true">添加成员</el-button>
        <el-upload :on-change="fileChange" :show-file-list="false" :auto-upload="false">
          <el-button type="warning" :loading="loading">上传</el-button>
        </el-upload>
        <el-button type="success" :loading="loading" @click="download">下载模版</el-button>
      </el-space>
      >
    </div>
    <!--表格展示-->
    <div style="margin-top: 20px">
      <el-table :data="userList" border stripe v-loading="loading">
        <el-table-column align="center" prop="id" label="ID"/>
        <el-table-column align="center" prop="username" label="姓名"/>
        <el-table-column align="center" prop="className" label="班级"/>
        <el-table-column align="center" prop="department" label="学院"/>
        <el-table-column align="center" prop="role" label="身份"/>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button type="primary" @click="update(scope.row)">
              <span style="margin-left: 3px">更新</span>
            </el-button>
            <el-button type="danger" @click="remove(scope.row.id)">
              <span style="margin-left: 3px">删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
        @size-change="getUser"
        @current-change="getUser"
        v-model:current-page="pageNum"

        v-model:page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <!--添加用户的对话框-->
    <el-dialog title="添加用户" v-model="dialogVisibleForAdd" width="30%" style="padding-top: 30px">
      <el-form ref="addForm" :model="addForm" label-width="100px">
        <el-form-item label="工号">
          <el-input :disabled="isEdit" v-model="addForm.id" placeholder="请输入工号..."></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="addForm.username" placeholder="请输入姓名..."></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="addForm.className" placeholder="请输入班级..."></el-input>
        </el-form-item>
        <el-form-item label="学院">
          <el-input v-model="addForm.department" placeholder="请输入班级..."></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="addForm.password" placeholder="请输入密码..."></el-input>
        </el-form-item>
        <el-form-item label="身份">
          <el-input v-model="addForm.role" placeholder="请输入密码..."></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addUser">确 定</el-button>
          <el-button @click="dialogVisibleForAdd = false">取 消</el-button>
        </span>
    </el-dialog>
  </el-card>

</template>

<script>
import {ElMessage, ElMessageBox} from "element-plus";

let formData = new FormData;
export default {
  name: "UserManage",
  data() {
    return {
      loading: true,
      isEdit: false,

      pageSize: 30,
      pageNum: 1,
      total: 0,

      addForm: {
        id: '',
        username: '',
        role: 'teacher',
        password: '123456',
        className: '',
        department: ''
      },
      userList: [],
      dialogVisibleForAdd: false,
    }
  },
  mounted() {
    this.getUser();
  },
  methods: {
    getUser() {
      this.loading = true;
      this.userList = [];
      this.$http({
        method: 'post',
        url: '/user/' + this.pageNum + '/' + this.pageSize,
        data: {
          id: '',
          username: ''
        }
      }).then(({data}) => {
        this.userList = data.list;
        this.total = data.total;
        this.loading = false;
      })
    },
    addUser() {
      let method = '';
      if (this.isEdit) {
        method = 'put';
      } else {
        method = 'post';
      }
      this.$http({
        method: method,
        url: '/user',
        data: this.addForm
      }).then(({data}) => {
        if (data.code === 200) {
          ElMessage({
            message: '操作成功',
            type: 'success'
          })
          this.isEdit = false;
          this.dialogVisibleForAdd = false;
          this.addForm.username = '';
          this.addForm.id = '';
          this.addForm.password = '123456';
          this.getUser();
        } else {
          ElMessage({
            message: data.msg,
            type: 'error'
          })
        }
      })
    },
    update(row) {
      this.addForm = JSON.parse(JSON.stringify(row));
      this.isEdit = true;

      this.dialogVisibleForAdd = true;
    },
    remove(id) {
      ElMessageBox.confirm(
          '该操作不可撤销',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            this.$http({
              method: 'delete',
              url: '/user/' + id,
            }).then(res => {
              this.getUser();
              ElMessage({
                type: 'success',
                message: '删除成功',
              })
            })
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '删除已取消',
            })
          })
    },
    fileChange(files, fileList) {
      formData.append('file', files.raw)
      files = null;
      this.loading = true;
      this.$http({
        method: 'post',
        url: '/addUserBatch',
        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.getUser()
        } else {
          this.$notify({
            title: '文件解析失败',
            message: res.data.msg,
            type: 'error'
          });
        }
        formData = null;
        formData = new FormData();
        this.loading = false;
      })
    },
    download() {
      let fileName = 'userTemplate.xlsx';
      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('下载文件时发生错误！');
        }
      });
    },
  }
}
</script>

<style scoped>

</style>
