<template>
  <el-dialog
    :title="'第' + titleName + '次课程论文'"
    :visible.sync="dialogVisible"
    width="650px"
    top="0"
    :before-close="cancelBtn"
    :close-on-click-modal="false"
    @open="open"
  >
    <div class="referHome">
      <el-form
        v-loading="loading"
        ref="formRef"
        :model="formData"
        label-position="top"
        class="readForm"
      >
        <!-- 老师布置的作业 -->
        <div class="cont_title">
          <div class="line"></div>
          <div class="lf">
            <span>作业要求</span>
          </div>
        </div>
        <div class="cont_title_2">作业内容</div>
        <div v-html="this.work_contexts" class="cont_info">}</div>
        <div class="cont_title_2">相关附件</div>
        <div class="upload_box">
          <div
            v-if="teaFileList.length > 0"
            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="downloadStuFile(item.url)">
                下载
              </div>
            </div>
          </div>
          <div v-if="teaFileList.length <= 0" class="img_list">
            <div>
              <div class="item_name">暂无相关附件</div>
            </div>
          </div>

          <div style="clear: both"></div>
        </div>
        <!-- 我的作业 -->
        <div v-if="this.student_status == 0 || this.student_status == 1">
          <div class="cont_title">
            <div class="line"></div>
            我的作业
          </div>
          <el-form-item
            label="文字描述(如超过300字，建议以附件形式上传)"
            prop="stu_answer"
          >
            <el-input
              type="textarea"
              v-model="formData.stu_answer"
              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 stuFileList"
                :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="stuFileList.length < 10"
                ref="systemLogo"
                name="multipartFile"
                action="#"
                :file-list="stuFileList"
                :disabled="isUploading || fileList.length >= 10"
                :limit="10"
                list-type="picture-card"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-progress="handleUploadProgress"
                :on-success="uploadSuccess"
                :http-request="uploadPicture"
              >
                <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>
        </div>
        <!-- 评阅结果 -->
        <div v-if="this.student_status == 2" style="height:350px">
          <div class="cont_title">
            <div class="line"></div>
            <div class="lf">
              <span>评阅结果</span>
            </div>
          </div>
          <div class="cont_title_2">导师评分</div>
          <div class="cont_info">{{ score }}</div>
          <div class="cont_title_2">作业内容</div>
          <div v-html="this.teacher_commment" class="cont_info">}</div>
          <div class="cont_title_2">相关附件</div>
          <div class="upload_box">
            <div
              v-if="tea_scoreFileList.length > 0"
              class="img_list"
              v-for="(item, index) in tea_scoreFileList"
              :key="index"
            >
              <div>
                <el-image :src="fileImg"></el-image>
                <div class="item_name">{{ item.name }}</div>
                <div class="item_remove" @click="downloadScoreFile(item.url)">
                  下载
                </div>
              </div>
            </div>
            <div v-if="tea_scoreFileList.length <= 0" class="img_list">
              <div>
                <div class="item_name">暂无相关附件</div>
              </div>
            </div>
          </div>
        </div>

        <el-form-item class="btn"  v-if="this.student_status == 0">
          <el-button type="primary" @click="confirm">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import Bus from "config/bus.js";
import {
  PostWorkStudentOss,
  delPic,
  getStudentWork,
  subStudentWork,
} from "r/index/homework";
import fileImg from "@/assets/img/homework/file_img.png";

export default {
  name: "ReadForm",
  props: {
    dialogVisibleFu: Boolean,
    work_contexts: [Number, String], //作业内容
    enclosure_urls: [Object, String], //老师作业地址
    work_nums: [Number],
    student_status: [Number], //作业状态
  },
  data() {
    return {
      titleName: "",
      isUploading: false, // 图片上传蒙层
      work_context: "", //简介
      fileImg: fileImg,
      loading: false,
      dialogVisible: this.dialogVisibleFu,
      dialogVisibleimage: false,
      stuWork: {}, // 学生-作业
      stuFileList: [], // 学生-相关附件
      teaFileList: [], // 老师-相关附件
      formData: {
        stu_work_num: "",
        stu_answer: "",
        stu_enclosure_url: "",
      }, // 老师-评阅结果
      upLoading: false, // 老师-上传loading
      fileList: [],
      stu_fileList: "",
      disabled: false, //限制输入框
      score: false, //老师评分
      teacher_commment: false, //老师评语
      tea_scoreFileList: [],
    };
  },
  created() {
    let code = this.$store.state.indexIdentity;
    let studentFile = window.localStorage.getItem(
      "student_file_" + window.localStorage.getItem("phone" + code) + code
    );
    if (studentFile && JSON.parse(studentFile).length > 0) {
      this.stuFileList = JSON.parse(studentFile);
    }
  },
  methods: {
    open() {
      this.titleName = this.work_nums;
      console.log(this.student_status);
      this.getTeachList();
      if (this.student_status == 0) {
      } else if (this.student_status == 1) {
        this.getStudentWork();
      } else if (this.student_status == 2) {
        this.getStudentWork();
      }
    },
    //老师作业展示
    getTeachList() {
      let url = this.enclosure_urls;
      console.log(this.enclosure_urls);
      if (this.enclosure_urls) {
        let arr = url.split(",");
        arr.forEach((item) => {
          this.teaFileList.push({
            url: item,
            name: item.split("/work/")[1],
            status: "success",
          });
        });
      } else {
        this.stuFileList = [];
      }
    },

    // 下载老师附件
    downloadStuFile(url) {
      this.download(
        "http://api.campcenter.cn/web/download/downloadTeacherWork",
        {
          enclosure_url: url,
          identity: this.$store.state.indexIdentity,
        },
        ""
      );
      // downloadTeacherWork({ enclosure_url:url }).then((res) => {
      //   console.log(res, "res");
      //   if (res.code != 200) {
      //     return this.$message.error(res.data.message);
      //   }
      //   this.$message.success(res.data.message);
      // });
      // window.location.href = url;
    },
    // 下载老师评分结果
    downloadScoreFile(url) {
      this.download(
        "http://api.campcenter.cn/web/download/downloadTeacherWork",
        {
          enclosure_url: url,
          identity: this.$store.state.indexIdentity,
        },
        ""
      );
    },
    // 学生作业回显
    getStudentWork() {
      let stu_work_num = this.work_nums;
      getStudentWork({ stu_work_num: stu_work_num }).then((res) => {
        console.log(res);
        if (res.data.code != 200) {
          return this.$message.error(res.data.message);
        }
        this.$message.success(res.data.message);
        // console.log(res.data.stu_answer);
        this.formData.stu_answer = res.data.data.stu_answer;
        let gotfileList = res.data.data.stu_enclosure_url_arr;
        this.stuFileList = gotfileList.map((item) => {
          return {
            name: item.split("/work/")[1],
            url: item,
          };
        });
        this.score = res.data.data.score; //老师评分
        this.teacher_commment = res.data.data.teacher_commment; //老师评语
        let scoreFileList = res.data.data.teacher_url;
        let arr = scoreFileList.split(",");
        console.log(arr, "arr");
        this.tea_scoreFileList = arr.map((item) => {
          return {
            name: item.split("workforstudent/")[1],
            url: item,
          };
        });
      });
    },
    // 保存按钮
    confirm() {
      this.$refs["formRef"].validate((valid) => {
        if (!valid) return;
        if (this.student_status == 0) {
          // 未完成
          this.notReadHandle();
        } else if (this.student_status == 1) {
          console.log(11111);
          // 已完成
          this.yiReadHandle();
        }
      });
    },

    // 未完成
    notReadHandle() {
      this.formData.stu_work_num = this.work_nums;
      this.formData.stu_enclosure_url = this.stu_fileList;
      subStudentWork(this.formData)
        .then((response) => {
          console.log(response);
          if (response.data.code != 200) {
            return this.$message.error(response.data.message);
          }
          this.$message.success(response.data.message);
          this.cancelBtnTrue();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 待评阅
    yiReadHandle() {
      let code = this.$store.state.indexIdentity;
      this.formData.stu_work_num = this.work_nums;
      this.formData.stu_enclosure_url = window.localStorage.getItem(
        "student_file_" + window.localStorage.getItem("phone" + code) + code
      );
      subStudentWork(this.formData)
        .then((response) => {
          console.log(response);
          if (response.data.code != 200) {
            return this.$message.error(response.data.message);
          }
          this.$message.success(response.data.message);
          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);
    },
    //上传前
    beforeAvatarUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.info("上传图片大小不能超过 10MB!");
      }
      return isLt10M;
    },

    // handlePictureCardPreview(file) {
    //   console.log(file, "11111111");
    //   this.resultPicture = file.url;
    //   this.dialogVisibleimage = true;
    // },
    // 文件上传中处理
    handleUploadProgress(event, file, fileList) {
      // console.log(fileList);
      this.isUploading = true;
      if (this.stuFileList.lenge < 10) {
        return this.$message.info("chaochushuliamng");
      }
    },
    uploadSuccess(res, file, fileList) {
      // console.log(res, "res");
      console.log(file, "file");
      // console.log(fileList, "fileList");
      this.referForm.achievementPath = res;
      this.stuFileList = {
        name: file.name,
        url: res,
      };
      this.$refs["imgUrl"].clearFiles(); //上传成功之后清除历史记录
    },
    uploadPicture(params) {
      console.log("已经准备好上传图片", params);
      this.file = params.file;
      console.log(this.file, "1111");
      let raw = params.file;
      let image = {
        name: raw.name,
        size: raw.size,
        type: raw.type,
      };
      this.getOssConfigs(image, params.file);
    },
    async getOssConfigs(image, file) {
      // let code = this.$store.state.indexIdentity;
      // let stu_work_num = window.localStorage.getItem("stu_work_num" + code);
      // console.log(
      //   window.localStorage.getItem("stu_work_num" + code),
      //   "stu_work_num"
      // );
      let obj = {
        url: "",
        savefile: "",
      };
      await PostWorkStudentOss({
        image: image,
        stu_work_num: this.work_nums,
      })
        .then((res) => {
          console.log(res, "开始上传图片");
          if (res.data.code === 200) {
            let oss_url = res.data.config.host;
            let filename = res.data.config.file;
            let formData = new FormData();
            formData.append("OSSAccessKeyId", res.data.config.accessid);
            formData.append("policy", res.data.config.policy);
            formData.append("signature", res.data.config.signature);
            formData.append("filename", res.data.config.file);
            formData.append("key", res.data.config.savefile);
            formData.append("callback", res.data.config.callback);
            formData.append("success_action_status", 200);
            formData.append("file", file);
            // console.log(formData);
            this.upload(oss_url, formData)
              .then((ress) => {
                console.log(ress, "ress");
                if (ress.data.code != 200) {
                  console.log(ress, "ress");
                  return this.$message.error(ress.data.message);
                }
                this.resultPicture = filename + "?t=" + Date.parse(new Date());
                this.$forceUpdate();
                this.$message.success("上传成功");
                obj = {
                  url: ress.data.picture_path,
                  savefile: res.data.config.savefile,
                };
                this.fileList.push(obj);
                console.log(this.fileList);

                // let stu_obj={
                //   url: ress.data.picture_path,
                // }
                // this.stu_fileList.push(stu_obj);
                //  let arrNew = [];
                this.stu_fileList = this.fileList
                  .map((item) => {
                    return item.url;
                  })
                  .join(",");
                console.log(this.stu_fileList);
                let code = this.$store.state.indexIdentity;
                window.localStorage.setItem(
                  "student_file_" +
                    +window.localStorage.getItem("phone" + code) +
                    code,
                  JSON.stringify(this.fileList)
                );
              })
              .catch((err) => {
                this.$message.error(err);
              });
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((err) => {
          // console.log(err);
        });
    },
    // 下载证明资料图片
    handleDownload(file) {
      // console.log(file,'file22');
      window.location.href = file.url;
    },
    //删除图片
    handleRemove(file) {
      console.log(file, "file");
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let getfile = file.url;
          // console.log(savefile.match(/^(?:[^\/]|\/\/)*/),'222222')；//获取域名
          let str = getfile.split(
            "https://campiste.oss-cn-beijing.aliyuncs.com/"
          ); //https://yingdi-achievement.oss-cn-beijing.aliyuncs.com/进行分割，
          console.log(str, "str");
          let savefile = str[1];
          // console.log(savefile, "savefile");
          let stu_work_num = this.work_nums;
          delPic({ object: savefile, stu_work_num: stu_work_num }).then(
            (res) => {
              console.log(res, "delpic");
              if (res.data.code != 200) {
                return this.$message.error(res.data.message);
              }
              this.stuFileList.forEach((item, idx) => {
                // console.log(item.url == file.url);
                if (item.url == file.url) {
                  this.stuFileList.splice(idx, 1);
                  let code = this.$store.state.indexIdentity;
                  window.localStorage.setItem(
                    "student_file_" +
                      window.localStorage.getItem("phone" + code) +
                      code,
                    JSON.stringify(this.stuFileList)
                  );
                }
              });

              // console.log(this.fileList);
              this.$message.success(res.data.message);
            }
          );
        })
        .catch((err) => {
          console.log(err, "err");
          this.$message({
            type: "info",
            message: "取消删除",
          });
        });
    },
  },

  watch: {
    dialogVisibleFu() {
      this.dialogVisible = this.dialogVisibleFu;
    },
  },
};
</script>

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






