<template>
  <div class="referHome">
    <div class="rh_top flex">
      <i class="el-icon-arrow-left"></i>
      <div>第三次课程论文</div>
    </div>

    <el-form
      v-loading="loading"
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-position="top"
      class="readForm"
    >
      <div class="cont_title">
        <div class="line"></div>
        <div class="lf">
          <span>
            {{ stuWork.jiguanProvince
            }}{{
              stuWork.jiguanProvince == stuWork.jiguanCity
                ? ""
                : stuWork.jiguanCity
            }}{{ stuWork.school }}</span
          >
          <span>{{ stuWork.name }}</span>
          <span>提交的作业</span>
        </div>
        <div class="rt" v-if="type == 1">编号: {{ stuInfo.workNum }}</div>
      </div>
      <div class="cont_title_2">文字描述</div>
      <div class="cont_info">{{ $store.state.work_context }}</div>
      <div class="cont_title_2">相关附件</div>
      <div class="upload_box">
        <div
          v-if="stuFileList.length > 0"
          class="img_list"
          v-for="(item, index) in stuFileList"
          :key="index"
        >
          <div>
            <el-image :src="fileImg"></el-image>
            <div class="item_name">{{ item.name }}</div>
            <div class="item_remove" @click="downloadStuFile(item.url)">
              下载
            </div>
          </div>
        </div>
        <div v-if="stuFileList.length <= 0" class="img_list">
          <div>
            <div class="item_name">暂无相关附件</div>
          </div>
        </div>

        <div style="clear: both"></div>
      </div>
      <div class="cont_title">
        <div class="line"></div>
        评阅结果
      </div>
      <el-form-item label="导师评分" prop="score">
        <el-input
          v-model="formData.score"
          size="small"
          placeholder="请评分(输入0-100之内的整数)"
          @input="inputValue"
        />
      </el-form-item>
      <el-form-item label="导师评语" prop="teaCommment">
        <el-input
          type="textarea"
          v-model="formData.teaCommment"
          placeholder="请输入300字以内的评语"
          size="small"
          :maxlength="300"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="相关附件" prop="teacherUrl">
        <div class="fj_info">1、请上传1-10份相关附件;</div>
        <div class="fj_info">
          2、单个附件大小不超过100M,支持JPG、JPEG、PNG、docx、doc、pdf、mp4等格式;
        </div>

        <div class="upload_box">
          <div
            class="img_list"
            v-for="(item, index) in teaFileList"
            :key="index"
          >
            <div>
              <el-image :src="fileImg"></el-image>
              <div class="item_name">{{ item.name }}</div>
              <div class="item_remove" @click="handleRemove(item)">删除</div>
            </div>
          </div>

          <el-upload
            v-if="teaFileList.length < 10"
            ref="systemLogo"
            name="multipartFile"
            :action="imgAction"
            :file-list="teaFileList"
            :disabled="upLoading"
            list-type="picture-card"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-progress="handleProgress"
            :on-success="handleSuccess"
          >
            <i v-if="!upLoading" class="el-icon-plus avatar-uploader-icon"></i>
            <i
              v-if="upLoading"
              class="el-icon-loading avatar-uploader-icon"
            ></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item class="btn">
        <el-button type="primary" @click="confirm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//   import {getToken} from "@/utils/auth";
import Bus from "config/bus.js";
import {
  GetStuWork,
  SaveTheRead,
  GetAllReadInfo,
  SaveYiRead,
} from "r/index/homework";
import fileImg from "@/assets/img/homework/file_img.png";


export default {
  name: "ReadForm",
  props: {
    //   dialogVisibleFu: Boolean,
    campIdFu: [Number, String],
    stuInfoFu: [Object, String],
    typeFu: [Number, String],
  },
  data() {
    return {
      work_context: "", //简介
      fileImg: fileImg,
      loading: false,
      dialogVisible: this.dialogVisibleFu,
      type: this.typeFu, // 来源（1-未评阅 2-已评阅）
      campId: this.campIdFu,
      stuInfo: this.stuInfoFu, // 学生-信息
      stuWork: {}, // 学生-作业
      stuFileList: [], // 学生-相关附件
      teaFileList: [], // 老师-相关附件
      formData: {
        campId: null,
        stuWorkNum: null,
        uuid: null,
        score: null,
        teaCommment: null,
        teacherUrl: null,
      }, // 老师-评阅结果
      rules: {
        score: [
          {
            required: true,
            message: "请评分(输入0-100之内的整数)",
            trigger: "blur",
          },
        ],
      },
      upLoading: false, // 老师-上传loading
      // 上传图片请求头
      // headers: {
      //   Authorization: "Bearer " + getToken()
      // },
      imgAction:
        process.env.VUE_APP_BASE_API +
        "/modules-campsite/ld/UploadWorkForStudent",
    };
  },
  created() {
      console.log( this.$store.state.work_context)
    // this.work_context = this.$store.state.work_context;
  },
  methods: {
    open() {
      if (this.type == 1) {
        this.getStuWork();
      } else if (this.type == 2) {
        this.getYiStuWork();
      }
    },

    // 保存按钮
    confirm() {
      this.$refs["formRef"].validate((valid) => {
        if (!valid) return;
        if (this.type == 1) {
          this.notReadHandle();
        } else if (this.type == 2) {
          this.yiReadHandle();
        }
      });
    },
    // 下载学生附件
    downloadStuFile(url) {
      window.location.href = url;
    },
    // 导师评分0-100限制
    inputValue(value) {
      if (value.length > 1 && value.slice(0, 1) == 0) {
        return (this.formData.score = 0);
      } else if (value.length >= 3 && value > 100) {
        return (this.formData.score = 100);
      }
      this.formData.score = value.replace(/[^\d]/g, "");
    },
    // 已评阅-获取学生答案
    getYiStuWork() {
      GetAllReadInfo({
        campId: this.campId,
        stuWorkNum: this.stuInfo.stuWorkNum,
        uuid: this.stuInfo.uuid,
      })
        .then((response) => {
          console.log(response);
          if (response.code != 200) {
            return this.msgError(response.msg);
          }
          this.stuWork = response.data;
          this.formData.score = this.stuWork["score"];
          this.formData.teaCommment = this.stuWork["teacherCommment"];
          this.formData.teacherUrl = this.stuWork["teacherUrl"];

          let url = this.stuWork.stuEnclosureUrl;
          if (this.stuWork.stuEnclosureUrl) {
            let arr = url.split(",");
            arr.forEach((item) => {
              this.stuFileList.push({
                url: item,
                name: item.split("/work/")[1],
                status: "success",
              });
            });
          } else {
            this.stuFileList = [];
          }
          let urlT = this.stuWork.teacherUrl;
          if (this.stuWork.teacherUrl) {
            let arr = urlT.split(",");
            arr.forEach((item) => {
              this.teaFileList.push({
                url: item,
                name: item.split("/workforstudent/")[1],
                status: "success",
              });
            });
          } else {
            this.teaFileList = [];
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 已评阅-评阅
    //   yiReadHandle(){
    //     this.formData.campId = this.campId;
    //     this.formData.stuWorkNum = this.stuInfo.stuWorkNum;
    //     this.formData.uuid = this.stuInfo.uuid;
    //     SaveYiRead(this.formData)
    //       .then(response => {
    //         console.log(response);
    //         if (response.code != 200) {
    //           return this.msgError(response.msg);
    //         }
    //         this.msgSuccess(response.msg);
    //         this.cancelBtnTrue();
    //       })
    //       .catch(error => {
    //         console.log(error);
    //       });
    //   },
    // 未评阅-获取学生答案
    getStuWork() {
      GetStuWork({
        campId: this.campId,
        stuWorkNum: this.stuInfo.stuWorkNum,
        uuid: this.stuInfo.uuid,
      })
        .then((response) => {
          console.log(response);
          if (response.code != 200) {
            return this.msgError(response.msg);
          }
          this.stuWork = response.data;
          let url = this.stuWork.stuEnclosureUrl;
          if (this.stuWork.stuEnclosureUrl) {
            let arr = url.split(",");
            arr.forEach((item) => {
              this.stuFileList.push({
                url: item,
                name: item.split("/work/")[1],
                status: "success",
              });
            });
          } else {
            this.stuFileList = [];
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 未评阅-评阅
    notReadHandle() {
      this.formData.campId = this.campId;
      this.formData.stuWorkNum = this.stuInfo.stuWorkNum;
      this.formData.uuid = this.stuInfo.uuid;
      SaveTheRead(this.formData)
        .then((response) => {
          console.log(response);
          if (response.code != 200) {
            return this.msgError(response.msg);
          }
          this.msgSuccess(response.msg);
          this.cancelBtnTrue();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 成功确认取消,关闭弹框，修改父组件的值
    cancelBtnTrue() {
      this.stuWork = {};
      this.stuFileList = [];
      this.teaFileList = [];
      this.$refs["formRef"].resetFields();
      this.dialogVisible = false;
      this.$emit("closeDialog", this.dialogVisible, true);
    },
    // 取消,关闭弹框，修改父组件的值
    cancelBtn() {
      this.stuWork = {};
      this.stuFileList = [];
      this.teaFileList = [];
      this.dialogVisible = false;
      this.$emit("closeDialog", this.dialogVisible, false);
    },
    // 删除文件
    handleRemove(data) {
      this.teaFileList = this.teaFileList.filter((item) => {
        return item != data;
      });
      this.formData.teacherUrl = this.teaFileList
        .map((item) => {
          return item.url;
        })
        .join(",");
      console.log(this.teaFileList);
      console.log(this.formData.teacherUrl);
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      if (res.code != 200) {
        this.upLoading = false;
        return this.msgError(res.msg);
      }
      let length = this.teaFileList.length;
      this.teaFileList[length] = {
        status: "success",
        name: res.msg.split("/workforstudent/")[1],
        url: res.msg,
      };
      this.formData.teacherUrl = this.teaFileList
        .map((item) => {
          return item.url;
        })
        .join(",");
      this.upLoading = false;
      this.msgSuccess("上传成功");
    },
    handleProgress(event, file, fileList) {
      this.upLoading = true;
    },
    // 上传文件之前的钩子
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 <= 100;

      if (!isLt10M) {
        this.$message.error("上传的附件大小不能超过 100M!");
        return false;
      }
      return isLt10M;
    },
  },
  watch: {
    dialogVisibleFu() {
      this.dialogVisible = this.dialogVisibleFu;
    },
    campIdFu() {
      this.campId = this.campIdFu;
    },
    stuInfoFu() {
      this.stuInfo = this.stuInfoFu;
    },
    typeFu() {
      this.type = this.typeFuFu;
    },
  },
};
</script>

<style scoped lang="scss">
@import "a/scss/btn";
@import "a/scss/homework/refer";
</style>






