<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="studentName">
        <el-input v-model="queryParams.studentName" placeholder="请输入姓名" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="身份证号码" label-width="100px" prop="idCard">
        <el-input v-model="queryParams.idCard" placeholder="请输入身份证号码" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="测试项目" prop="project">
        <el-input v-model="queryParams.project" placeholder="请输入测试项目" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:relation:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:relation:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload" size="mini" v-if="status == '2'" @click="handleUpload"
                   v-hasPermi="['system:relation:remove']">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['system:relation:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="publish" v-if="status == '2'"
                   v-hasPermi="['system:exam:add']">发布
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="relationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="55" align="center"/>
      <el-table-column label="头像" align="center" min-width="100" prop="photo">
        <template slot-scope="scope">
          <ListImage :image-url="isEmptyAvatar(scope.row.photo, scope.row.sex)"></ListImage>
        </template>
      </el-table-column>
      <el-table-column label="身份证号码" align="center" prop="idCard" min-width="180"/>
      <el-table-column label="姓名" align="center" min-width="88" prop="studentName"/>
      <el-table-column label="学籍号" align="center" min-width="180" prop="studentNumber"/>
      <el-table-column label="初中学校" key="juniorSchool" min-width="130" align="center" prop="schoolName"/>
      <el-table-column label="测试项目" align="type" prop="project" min-width="100">
      </el-table-column>
      <el-table-column label="性别" align="center" prop="sex" min-width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="准考证号" align="center" prop="examNumber" min-width="180"/>
      <el-table-column label="分组" align="center" min-width="100" prop="inGroup"/>
      <el-table-column label="考试日期" align="center" prop="examDate" min-width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.examDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试时间" align="center" min-width="100" prop="examTime"/>
      <el-table-column label="考试地点" align="center" min-width="150" prop="examAddress"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="status == '2'" @click="handleUpdate(scope.row)">
            修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
                     v-if="status == '3'||status == '4'">查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px">
      <el-row :gutter="30">
        <el-col :span="9">
          <!-- 个人信息 -->
          <div style="font-size: 20px;text-align: center"><b>报名信息</b></div>
          <br/><br/>
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="姓名:" prop="studentName">
              <el-input v-model="form.studentName" placeholder="请输入学生姓名" readOnly/>
            </el-form-item>
            <el-form-item label="性别:">
              <el-select ref="sexSelect" v-model="form.sex" style="width: 100%" placeholder="请选择学生性别" disabled>
                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                           :value="dict.value">
                  {{ dict.label }}
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="测试项目:" prop="project">
              <el-input v-model="form.project" placeholder="请选择测试项目" readOnly/>
            </el-form-item>
            <el-form-item label="身份证号:" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" readOnly/>
            </el-form-item>
            <el-form-item label="学籍号:" prop="studentNumber">
              <el-input v-model="form.studentNumber" placeholder="请输入学籍号" readOnly/>
            </el-form-item>
            <el-form-item label="初中学校:" prop="schoolName">
              <el-input v-model="form.schoolName" placeholder="请输入初中学校" readOnly/>
            </el-form-item>
            <el-form-item label="身高:" prop="height">
              <el-input v-model="form.height" placeholder="请输入身高" readOnly>
                <template slot="suffix">CM</template>
              </el-input>
            </el-form-item>
            <el-form-item label="体重:" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入体重" readOnly>
                <template slot="suffix">KG</template>
              </el-input>
            </el-form-item>
            <el-form-item label="联系方式1:" prop="telephone1">
              <el-input v-model="form.telephone1" placeholder="请输入联系方式" readOnly/>
            </el-form-item>
            <el-form-item label="联系方式2:" prop="telephone2">
              <el-input v-model="form.telephone2" placeholder="请输入联系方式" readOnly/>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <!-- 照片 -->
          <el-form ref="form" :model="form" :rules="rules" label-width="0px">
            <br/><br/><br/><br/>
            <el-form-item>
              <el-image :src="isEmptyAvatar(form.photo, form.sex)" fit="fill"
                        style=" display: block; margin: auto; width: 200px; height: 200px;" alt="学生照片加载失败"/>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="9">
          <!-- 分配考场信息 -->
          <div style="font-size: 20px;text-align: center"><b>考场信息</b></div>
          <br/><br/>
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="准考证号" prop="examNumber">
              <el-input v-model="form.examNumber" :readOnly="isHandle"/>
            </el-form-item>
            <el-form-item label="分组" prop="inGroup">
              <el-input v-model="form.inGroup" :readOnly="isHandle"/>
            </el-form-item>
            <el-form-item label="考试日期" prop="examDate">
              <el-date-picker :disabled="isHandle" style="width: 100%" v-model="form.examDate" type="date"
                              placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="考试时间" prop="examTime">
              <el-time-select :disabled="isHandle" style="width: 100%" v-model="form.examTime" :picker-options="{
                start: '08:30',
                step: '00:15',
                end: '18:30'
              }" placeholder="选择时间">
              </el-time-select>
            </el-form-item>
            <el-form-item label="考试地点" prop="examAddress">
              <el-input v-model="form.examAddress" :readOnly="isHandle"/>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer">
        <el-button v-show="!isHandle" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">{{ isHandle ? '退 出' : '取 消' }}</el-button>
      </div>

    </el-dialog>
    <!--导入文件对话框 -->
    <el-dialog :title="title" :visible.sync="uploadOpen" width="520px" append-to-body inline @close="cancel">
      <el-form ref="uploadForm" :model="form" :rules="rules" label-width="70px">
        <el-form-item label="文 件：" prop="dataUrl">
          <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                     :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                     :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <!--<div class="el-upload__tip" slot="tip">-->
              <!--  <el-checkbox v-model="upload.updateSupport"/>-->
              <!--  是否更新已经存在的用户数据-->
              <!--</div>-->
              <span>仅允许导入xls、xlsx格式文件。</span>
              <!-- <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                @click="importTemplate">下载模板
              </el-link> -->
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAddressInfo,
  delRelation,
  addRelation,
  handleEdit,
  addressEnd,
  addressList,
  listProject
} from "@/api/smartSchool/examinationManage";
import {getToken} from "@/utils/auth";
import {Gender, Nations} from "@/enums/common";

export default {
  name: "Relation",
  dicts: ['professional_category', 'sys_user_sex', 'registration_status'],
  props: ['examId'],
  data() {
    return {
      baseUrl: [process.env.VUE_APP_BASE_API],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 测试项目
      // projectList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      relationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      //考试状态
      status: null,
      open: false,
      // 是否修改
      isHandle: false,
      // 导入对话框
      uploadOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        examId: null,
        studentId: null,
        auditStatus: null,
        matchStatus: null,
        infoIdCard: null,
        projectIdList: null,
        submit: null,
        examNumber: null,
        inGroup: null,
        examDate: null,
        examTime: null,
        examAddress: null,
        score: null,
        result: null,
        passScore: null,
        step: null
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（学生导入）
        open: false,
        // 是否禁用上传
        //  isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + `/artExam/importAddressData/${this.examId}`,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        examTime: [
          {required: true, message: "考试时间不能为空", trigger: "blur"}
        ],
        examDate: [
          {required: true, message: "考试日期不能为空", trigger: "blur"}
        ],
        inGroup: [
          {required: true, message: "分组不能为空", trigger: "blur"}
        ],
        examNumber: [
          {required: true, message: "准考证号不能为空", trigger: "blur"}
        ],
        examAddress: [
          {required: true, message: "考试地点不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    // this.getList();
    // this.getTestList();

  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      addressList(this.examId, this.queryParams).then(response => {
        this.relationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.uploadOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        examId: null,
        studentId: null,
        auditStatus: "0",
        matchStatus: "0",
        infoIdCard: null,
        submit: null,
        examNumber: null,
        inGroup: null,
        examDate: null,
        examTime: null,
        examAddress: null,
        score: null,
        result: null,
        passScore: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        step: null
      };
      this.resetForm("form");
    },
    // 获取状态
    getStatus(statu) {
      this.getList();
      this.status = statu
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isHandle = false
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isHandle = false
      this.reset();
      const id = row.id || this.ids
      getAddressInfo(id).then(response => {
        this.form = response.data;
        this.imageUrl = this.isEmptyAvatar(this.form.photo, this.form.sex);
        this.open = true;
        this.title = "修改";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      this.isHandle = true
      const id = row.id || this.ids
      getAddressInfo(id).then(response => {
        this.form = response.data;
        this.imageUrl = this.isEmptyAvatar(this.form.photo, this.form.sex);
        this.open = true;
        this.title = "考试信息查看";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            handleEdit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRelation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function () {
        return delRelation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 判断学生头像是否为空 */
    isEmptyAvatar(imageUrl, sex) {
      if (!imageUrl) {
        let url = null;
        if (Gender.MALE === sex) {
          url = require('@/assets/images/boy.png');
        } else {
          url = require('@/assets/images/girl.png');
        }
        return url
      } else
        return this.baseUrl + imageUrl;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(`/artExam/exportAddress/${this.examId}`, {
        ...this.queryParams
      }, `考场分配${Date.now()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleUpload(row) {
      this.reset();
      this.title = "导入"
      this.uploadOpen = true
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      // console.log(event, file, fileList);
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadOpen = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {dangerouslyUseHTMLString: true})
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 下载模板
    // importTemplate() {
    //   this.download(
    //     "/eduArtStudent/importTemplate",
    //     {},
    //     `导入教育局信息内模板_${new Date().getTime()}.xlsx`
    //   );
    // },
    publish() {
      const examId = this.examId
      this.$confirm('是否确认发布?').then(function () {
        return addressEnd(examId)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("发布成功");
        this.$emit("sendStatus")
      }).catch(() => {
      });
      // addressEnd(this.form).then(response => {
      //   this.$modal.msgSuccess("发布成功");
      // });
    },
  }
};
</script>
<style scoped>
.fullbg {
  background-color: rgb(201, 201, 201);
  left: 0;
  opacity: 0.2;
  position: absolute;
  top: 0;
  z-index: 1;
  filter: alpha(opacity=50);
  width: 1000px;
  height: 800px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-form-item {
  margin-bottom: 10px;
}

</style>
