<template>
  <el-container>
    <el-main v-loading="loading" class="el-main-padding">
      <commonFormVue :form="form" :getExamCondition="getExamCondition">
        <el-row v-show="showAllCondition">
          <el-col :span="6">
            <el-form-item label="完成状态">
              <el-select
                v-if="form.examType == '' || form.examType == 'ONLINE'"
                class="form_search_width"
                size="small"
                v-model="form.finished"
                clearable
                placeholder="全部"
              >
                <el-option value="1" label="已完成"></el-option>
                <el-option value="0" label="未完成"></el-option>
              </el-select>
              <el-select
                v-if="form.examType == 'OFFLINE'"
                class="form_search_width"
                size="small"
                v-model="form.finished"
                clearable
                placeholder="全部"
              >
                <el-option value="0" label="未抽题"></el-option>
                <el-option value="1" label="已抽题"></el-option>
                <el-option value="2" label="已上传"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采集人">
              <el-input
                class="form_search_width"
                size="small"
                v-model="form.infoCollector"
                placeholder="采集人"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </commonFormVue>
      <el-col :span="24">
        <el-button
          @click="search('clickSelectBtn')"
          size="small"
          type="primary"
          icon="el-icon-search"
          >查询</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-more"
          v-if="!showAllCondition"
          @click="showMoreCondition"
          >高级查询</el-button
        >
        <el-button
          size="small"
          type="primary"
          v-if="showAllCondition"
          @click="showSimpleCondition"
          >简单查询</el-button
        >
        <el-button
          size="small"
          icon="el-icon-refresh"
          @click="resetForm"
          class="margin-bottom-10"
          >重置</el-button
        >
      </el-col>
      <el-row>
        <el-col
          :span="24"
          v-show="currentPagePrivileges.EXAM_PARTICULARS_EXPORT"
        >
          <div class="block-seperator"></div>
          <span>操作：</span>
          <commonExportVue
            :form="form"
            :exportUrl="exportUrl"
            :exportFileName="exportFileName"
          ></commonExportVue>
        </el-col>
      </el-row>
      <el-row class="margin-top-10">
        <el-col :span="24">
          <el-table
            v-loading="tableLoading"
            element-loading-text="数据加载中"
            ref="multipleTable"
            @selection-change="handleSelectionChange"
            :data="tableData"
            border
          >
            <el-table-column
              sortable
              label="学习中心"
              prop="orgName"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="姓名"
              prop="studentName"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="身份证号"
              prop="identityNumber"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="学号"
              prop="studentCode"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="课程"
              prop="courseName"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="课程层次"
              prop="courseLevel"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="专业"
              prop="specialtyName"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="已考次数"
              prop="normalExamTimes"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="学生电话"
              prop="phone"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="年级"
              prop="grade"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="采集人"
              prop="infoCollector"
              width="120"
            ></el-table-column>
            <el-table-column
              sortable
              label="完成状态"
              prop="finishedStatus"
              width="120"
            ></el-table-column>
            <!-- <el-table-column sortable label="完成状态" width="120">
              <template slot-scope="scope">
                <span> {{ scope.row.finishedStatus }} </span>
              </template>
            </el-table-column>-->
            <el-table-column fixed="right" label="操作" width="120">
              <template slot-scope="scope">
                <el-row class="operateRow">
                  <el-col :span="24">
                    <el-button
                      plain
                      type="primary"
                      size="mini"
                      icon="el-icon-view"
                      @click="previewPaper(scope.row.examStudentId)"
                      v-if="scope.row.examType == 'OFFLINE'"
                      >查看考题</el-button
                    >
                  </el-col>
                </el-row>
                <el-row class="operateRow">
                  <el-col :span="24">
                    <el-button
                      plain
                      type="primary"
                      size="mini"
                      icon="el-icon-download"
                      @click="exportPaper(scope.row.examStudentId)"
                      v-if="scope.row.examType == 'OFFLINE'"
                      >下载考题</el-button
                    >
                  </el-col>
                </el-row>
                <el-row class="operateRow">
                  <el-col :span="24">
                    <el-button
                      plain
                      type="primary"
                      size="mini"
                      icon="el-icon-upload2"
                      @click="openUploadAnswerDialog(scope.row.examStudentId)"
                      v-if="
                        scope.row.examType == 'OFFLINE' &&
                          scope.row.canUploadAttachment
                      "
                      >上传作答</el-button
                    >
                  </el-col>
                </el-row>
                <el-row class="operateRow">
                  <el-col :span="24">
                    <el-button
                      plain
                      type="primary"
                      size="mini"
                      icon="el-icon-download"
                      @click="downloadAnswer(scope.row.offlineFileUrl)"
                      v-if="
                        scope.row.examType == 'OFFLINE' &&
                          scope.row.offlineFileUrl
                      "
                      >下载作答</el-button
                    >
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
          <div class="page pull-right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="form.pageNo"
              :page-sizes="[10, 20, 50, 100, 200, 300]"
              :page-size="form.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            ></el-pagination>
          </div>
        </el-col>
      </el-row>
      <div>
        <el-dialog
          title="上传作答"
          v-loading="uploadAnswerDialogLoading"
          :visible.sync="uploadAnswerDialogVisible"
          @closed="cleanOfflineFile"
        >
          <el-form>
            <el-form-item label="选择文件">
              <input
                type="file"
                accept="application/pdf, application/zip"
                id="importFile"
                ref="offlineFileInput"
                @change="uploadAnswerChange"
                v-bind:class="{ offline_file: offlineAnswerFile }"
              />
              <div>温馨提示:仅支持pdf和zip文件,文件大小请不要超过30M!</div>
            </el-form-item>
            <div class="dialog-footer">
              <el-button @click="uploadAnswerDialogVisible = false"
                >取 消</el-button
              >
              <el-button
                :disabled="!offlineAnswerFile"
                type="primary"
                @click="doUploadAnswer"
                >确 定</el-button
              >
            </div>
          </el-form>
        </el-dialog>
      </div>
    </el-main>
  </el-container>
</template>
<script>
import { mapState } from "vuex";
import commonFormVue from "../component/commonForm.vue";
import commonExportVue from "../component/commonExport.vue";
import pagePrivilege from "../mixin/pagePrivilege.js";
export default {
  components: { commonFormVue, commonExportVue },
  mixins: [pagePrivilege],
  data() {
    return {
      loading: false,
      uploadAnswerDialogLoading: false,
      uploadAnswerDialogVisible: false,
      total: 0,
      tableLoading: false,
      showAllCondition: false,
      form: {
        examRecordDataId: null,
        hasStranger: null,
        courseId: null,
        courseLevel: null,
        examId: null,
        examRecordId: null,
        faceSuccessPercentLower: null,
        faceSuccessPercentUpper: null,
        livenessSuccessPercentLower: null,
        livenessSuccessPercentUpper: null,
        identityNumber: null,
        orgId: null,
        studentCode: null,
        studentName: null,
        isWarn: null,
        pageNo: 1,
        pageSize: 10,
        examType: ""
      },
      getExamCondition: {
        params: {
          name: "",
          examTypes: "ONLINE#OFFLINE"
        },
        filterCondition: ""
      },
      tableData: [],
      exportUrl: "/api/ecs_oe_admin/exam/student/examScheduling/list/export",
      exportFileName: "考试进度详情",
      currentOfflineExamRecordDataId: "",
      offlineAnswerFile: "",
      currentPagePrivileges: {
        EXAM_PARTICULARS_EXPORT: false //导出
      }
    };
  },
  computed: {
    ...mapState({ user: state => state.user })
  },
  methods: {
    resetForm() {
      this.form = {
        examRecordDataId: null,
        hasStranger: null,
        courseId: null,
        courseLevel: null,
        examId: null,
        examRecordId: null,
        faceSuccessPercentLower: null,
        faceSuccessPercentUpper: null,
        livenessSuccessPercentLower: null,
        livenessSuccessPercentUpper: null,
        identityNumber: null,
        orgId: null,
        studentCode: null,
        studentName: null,
        isWarn: null,
        pageNo: 1,
        pageSize: 10,
        examType: ""
      };
    },
    showMoreCondition() {
      this.showAllCondition = true;
    },
    showSimpleCondition() {
      this.$notify({
        title: "提示",
        message: "高级查询条件值已重置",
        type: "info",
        duration: 2000
      });
      this.resetForm();
      this.showAllCondition = false;
    },
    search(type) {
      if (!this.form.examId) {
        this.$notify({
          title: "警告",
          message: "请选择考试批次",
          type: "warning",
          duration: 2000
        });
        return false;
      }
      if (type && type == "clickSelectBtn") {
        this.form.pageNo = 1;
      }
      this.tableLoading = true;
      this.$http
        .post("/api/ecs_oe_admin/exam/student/examScheduling/list", this.form)
        .then(response => {
          if (response.data) {
            var dataList = response.data.content;
            this.tableData = dataList;
            this.total = response.data.totalElements;
          } else {
            this.tableData = [];
          }
          this.tableLoading = false;
        });
    },
    selectable(row) {
      return row.isWarn;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**
     * pagesize改变时触发
     */
    handleSizeChange(val) {
      this.form.pageSize = val;
      this.search();
    },
    /**
     * 当前页改变时触发
     */
    handleCurrentChange() {
      this.search();
    },
    previewPaper(examStudentId) {
      this.$http
        .get("/api/ecs_oe_admin/exam/record/select/byExamStudentId", {
          params: { examStudentId: examStudentId }
        })
        .then(response => {
          if (response.data) {
            var examRecordList = response.data;
            if (examRecordList && examRecordList.length > 0) {
              window.open(
                "/admin/preview_paper/" + examRecordList[0].basePaperId
              );
            } else {
              this.$notify({
                title: "提示",
                message: "该考生未参加考试",
                type: "error",
                duration: 2000
              });
            }
          }
        });
    },
    exportPaper(examStudentId) {
      this.loading = true;
      var currentUser = this.user;
      this.$http
        .get("/api/ecs_oe_admin/exam/record/select/byExamStudentId", {
          params: { examStudentId: examStudentId }
        })
        .then(response => {
          if (response.data) {
            var examRecordList = response.data;
            if (examRecordList && examRecordList.length > 0) {
              var basePaperId = examRecordList[0].basePaperId;
              var rootOrgName = currentUser.rootOrgName;
              this.$http
                .get(
                  "/api/ecs_ques/paper/export/" +
                    basePaperId +
                    "/PAPER/" +
                    rootOrgName +
                    "/" +
                    basePaperId +
                    "/offLine",
                  {
                    responseType: "arraybuffer",
                    filename: "utf-8"
                  }
                )
                .then(response => {
                  if (response.data && response.data.byteLength > 0) {
                    var blob = new Blob([response.data], {
                      type: "application/zip"
                    });
                    var url = URL.createObjectURL(blob);
                    var fileName = response.headers["content-disposition"]
                      .split(";")[1]
                      .replace("filename=", "");
                    var a = document.createElement("a");
                    a.href = url;
                    a.download = decodeURI(fileName);
                    a.target = "_blank";
                    a.click();
                    URL.revokeObjectURL(url);
                  } else {
                    this.$notify({
                      title: "提示",
                      message: "无相关文件",
                      type: "error",
                      duration: 2000
                    });
                  }
                  this.loading = false;
                })
                .catch(() => {
                  this.loading = false;
                });
            } else {
              this.loading = false;
              this.$notify({
                title: "提示",
                message: "该考生未参加考试",
                type: "error",
                duration: 2000
              });
            }
          }
        });
    },
    openUploadAnswerDialog(examStudentId) {
      this.$http
        .get("/api/ecs_oe_admin/exam/record/data/findByExamStudentId", {
          params: { examStudentId: examStudentId }
        })
        .then(response => {
          var examRecordDataList = response.data;
          if (examRecordDataList.length == 0) {
            this.$notify({
              title: "提示",
              message: "该考生未参加考试",
              type: "error",
              duration: 2000
            });
          } else {
            this.uploadAnswerDialogVisible = true;
            this.currentOfflineExamStudentId = examStudentId;
            this.currentOfflineExamRecordDataId = examRecordDataList[0].id;
          }
        });
    },
    uploadAnswerChange(event) {
      if (event.target.files.length > 0) {
        this.offlineAnswerFile = event.target.files[0];
      } else {
        this.offlineAnswerFile = "";
      }
    },
    doUploadAnswer() {
      var index = this.offlineAnswerFile.name.lastIndexOf(".");
      var fileNameLength = this.offlineAnswerFile.name.length;
      var fileSuffix = this.offlineAnswerFile.name
        .substring(index + 1, fileNameLength)
        .toUpperCase();
      this.$http
        .get(
          "/api/ecs_exam_work/exam/property/" +
            this.form.examId +
            "/OFFLINE_UPLOAD_FILE_TYPE"
        )
        .then(response => {
          var allowfileSuffixs = response.data;
          if (!allowfileSuffixs || allowfileSuffixs.length == 0) {
            this.$notify({
              title: "提示",
              message: "当前考试设置不允许上传附件",
              type: "error",
              duration: 2000
            });
            return false;
          }
          if (allowfileSuffixs.toString().indexOf(fileSuffix) < 0) {
            this.$notify({
              title: "提示",
              message:
                "当前考试允许上传文件格式为:" + allowfileSuffixs.toString(),
              type: "error",
              duration: 2000
            });
            return false;
          }
          this.uploadAnswerDialogLoading = true;
          let config = {
            headers: { "Content-Type": "multipart/form-data" }
          };
          let param = new FormData();
          param.append("file", this.offlineAnswerFile);
          param.append("examRecordDataId", this.currentOfflineExamRecordDataId);
          this.$http
            .post("/api/ecs_oe_student/offlineExam/submitPaper", param, config)
            .then(() => {
              this.$notify({
                title: "提示",
                message: "上传成功",
                type: "success",
                duration: 2000
              });
              this.uploadAnswerDialogVisible = false;
              this.uploadAnswerDialogLoading = false;
              this.$refs.offlineFileInput.value = "";
              this.offlineAnswerFile = "";
              this.search();
            })
            .catch(() => {
              this.$notify({
                title: "提示",
                message: "上传失败",
                type: "error",
                duration: 2000
              });
              this.uploadAnswerDialogLoading = false;
              this.$refs.offlineFileInput.value = "";
              this.offlineAnswerFile = "";
            });
        });
    },
    cleanOfflineFile() {
      this.$refs.offlineFileInput.value = "";
      this.offlineAnswerFile = "";
    },
    downloadAnswer(offlineFileUrl) {
      window.open(offlineFileUrl);
    }
  },
  created() {}
};
</script>
<style scoped>
.offline_file {
  color: blue;
}
</style>
<style scoped src="../style/common.css"></style>
