<template>
  <div class="r_box">
    <div class="r_cbox">
      <span>学生姓名</span>
      <el-select
        multiple
        collapse-tags
        class="r_select"
        v-model="uname"
        placeholder="全部"
        filterable
      >
        <el-option
          v-for="item in userAarray"
          :key="item.userid"
          :label="item.username"
          :value="item.userid"
        >
        </el-option>
      </el-select>
    </div>
    <div class="r_cbox">
      <span>选择阶段</span>
      <el-select
        class="r_select"
        v-model="chap"
        multiple
        collapse-tags
        placeholder="全部"
        @change="changeChap"
      >
        <el-option
          v-for="(item, index) in dyList"
          :key="index"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </div>
    <div class="r_cbox">
      <span>任务内容</span>
      <el-select
        class="r_select"
        v-model="task"
        multiple
        collapse-tags
        placeholder="全部"
      >
        <el-option-group
          v-for="(group, index) in dyAarray"
          :key="index"
          :label="group.name"
        >
          <el-option
            v-for="(item, index2) in group.taskList"
            :key="index + '-' + index2"
            :label="item.name"
            :value="group.id + '-' + item.id"
          >
          </el-option>
        </el-option-group>
      </el-select>
    </div>
    <div class="btn_box">
      <el-button class="btn btnClassGM" type="primary" @click="confirm">确定</el-button>
    </div>
  </div>
</template>

<script>
import htmlDocx from "html-docx-js/dist/html-docx";
import saveAs from "file-saver";
export default {
  props: ["cid"],
  data() {
    return {
      uname: [],
      chap: [],
      task: [],
      dyAarray: [],
      dyList: [],
      userAarray: [],
      imgList: [],
      askList: [],
      questList: [],
      wordList: [],
      course: {},
    };
  },
  methods: {
    getCourseDetail() {
      let params = {
        cid: this.cid,
      };
      this.ajax
        .get(this.$store.state.api + "getCourseWorksReport", params)
        .then((res) => {
          this.course = res.data[0][0];
          var dyJSON = JSON.parse(res.data[0][0].chapters);
          let dyList = [];
          for (var i = 0; i < dyJSON.length; i++) {
            dyList.push({ name: dyJSON[i].dyName, id: i, taskList: [] });
            var a = dyJSON[i].chapterInfo[0].taskJson;
            for (var j = 0; j < a.length; j++) {
              dyList[i].taskList.push({ name: a[j].task, id: j });
            }
          }
          this.dyList = dyList;
          this.userAarray = res.data[1];
          console.log(res.data[0][1]);
          this.imgList = res.data[2];
          this.askList = res.data[3];
          this.questList = res.data[4];
          this.wordList = res.data[5];
        })
        .catch((err) => {
          console.error(err);
        });
    },
    confirm() {
      var _uname = [];
      var _userA = this.userAarray;
      var _chap = JSON.parse(JSON.stringify(this.chap));
      var _task = this.task;
      if (this.uname.length) {
        for (var i = 0; i < _userA.length; i++) {
          if (this.uname.join(",").indexOf(_userA[i].userid) != -1) {
            _uname.push(_userA[i]);
          }
        }
      } else {
        for (var i = 0; i < _userA.length; i++) {
          _uname.push(_userA[i]);
        }
      }

      if (!_chap.length) {
        for (var i = 0; i < this.dyList.length; i++) {
          _chap.push(this.dyList[i].id);
        }
      }

      let imgList = this.imgList;
      let askList = this.askList;
      let questList = this.questList;
      let wordList = this.wordList;

      let workArray = [];

      // json{
      //       img: [],
      //       askList: [],
      //       questList: {},
      //       wordList: [],
      //       chapName: "",
      //       taskName: "",
      //       username:""
      //     }

      for (let i = 0; i < _uname.length; i++) {
        for (let chapI = 0; chapI < _chap.length; chapI++) {
          if (_task.length) {
            for (let taskI = 0; taskI < _task.length; taskI++) {
              let _tI = _task[taskI].split("-");
              if (_tI[0] == _chap[chapI]) {
                let _workjson = {
                  img: [],
                  askList: [],
                  questList: [],
                  wordList: [],
                  chapName:
                    "第" +
                    (parseInt(_chap[chapI]) + 1) +
                    "阶段 " +
                    this.dyList[_chap[chapI]].name,
                  taskName:
                    "任务" +
                    (parseInt(_tI[1]) + 1) +
                    this.dyList[_chap[chapI]].taskList[_tI[1]].name,
                  username: _uname[i].username,
                };
                // imgList;askList;questList;wordList;
                for (let a = 0; a < imgList.length; a++) {
                  if (
                    imgList[a].stage == _chap[chapI] &&
                    imgList[a].task == _tI[1] &&
                    imgList[a].userid == _uname[i].userid
                  ) {
                    _workjson.img.push({ src: imgList[a].content });
                  }
                }
                for (let b = 0; b < askList.length; b++) {
                  if (
                    askList[b].stage == _chap[chapI] &&
                    askList[b].task == _tI[1] &&
                    askList[b].userid == _uname[i].userid
                  ) {
                    const element = askList[b];
                    let a1 = JSON.parse(element.content)[0];
                    let b1 = a1.anwer.split(",");
                    let c1 = [];
                    for (var j1 = 0; j1 < b1.length; j1++) {
                      c1.push(parseInt(b1[j1]));
                    }
                    a1.askJson.radio = c1;
                    a1.askJson.time = element.time;
                    _workjson.askList.push(a1.askJson);
                  }
                }
                for (let c = 0; c < questList.length; c++) {
                  if (
                    questList[c].stage == _chap[chapI] &&
                    questList[c].task == _tI[1] &&
                    questList[c].userid == _uname[i].userid
                  ) {
                    const element = questList[c];
                    _workjson.questList.push(JSON.parse(element.content)[0]);
                  }
                }
                for (let d = 0; d < wordList.length; d++) {
                  if (
                    wordList[d].stage == _chap[chapI] &&
                    wordList[d].task == _tI[1] &&
                    wordList[d].userid == _uname[i].userid
                  ) {
                    const element = wordList[d];
                    _workjson.wordList.push(element.content);
                  }
                }
                workArray.push(_workjson);
              }
            }
          } else {
            for (
              let taskI = 0;
              taskI < this.dyList[_chap[chapI]].taskList.length;
              taskI++
            ) {
              let _tI = [
                _chap[chapI],
                this.dyList[_chap[chapI]].taskList[taskI].id,
              ];
              if (_tI[0] == _chap[chapI]) {
                let _workjson = {
                  img: [],
                  askList: [],
                  questList: [],
                  wordList: [],
                  chapName:
                    "第" +
                    (parseInt(_chap[chapI]) + 1) +
                    "阶段 " +
                    this.dyList[_chap[chapI]].name,
                  taskName:
                    "任务" +
                    (parseInt(_tI[1]) + 1) +
                    this.dyList[_chap[chapI]].taskList[_tI[1]].name,
                  username: _uname[i].username,
                };
                // imgList;askList;questList;wordList;
                for (let a = 0; a < imgList.length; a++) {
                  if (
                    imgList[a].stage == _chap[chapI] &&
                    imgList[a].task == _tI[1] &&
                    imgList[a].userid == _uname[i].userid
                  ) {
                    _workjson.img.push({ src: imgList[a].content });
                  }
                }
                for (let b = 0; b < askList.length; b++) {
                  if (
                    askList[b].stage == _chap[chapI] &&
                    askList[b].task == _tI[1] &&
                    askList[b].userid == _uname[i].userid
                  ) {
                    const element = askList[b];
                    let a1 = JSON.parse(element.content)[0];
                    let b1 = a1.anwer.split(",");
                    let c1 = [];
                    for (var j1 = 0; j1 < b1.length; j1++) {
                      c1.push(parseInt(b1[j1]));
                    }
                    a1.askJson.radio = c1;
                    a1.askJson.time = element.time;
                    _workjson.askList.push(a1.askJson);
                  }
                }
                for (let c = 0; c < questList.length; c++) {
                  if (
                    questList[c].stage == _chap[chapI] &&
                    questList[c].task == _tI[1] &&
                    questList[c].userid == _uname[i].userid
                  ) {
                    const element = questList[c];
                    _workjson.questList.push(JSON.parse(element.content)[0]);
                  }
                }
                for (let d = 0; d < wordList.length; d++) {
                  if (
                    wordList[d].stage == _chap[chapI] &&
                    wordList[d].task == _tI[1] &&
                    wordList[d].userid == _uname[i].userid
                  ) {
                    const element = wordList[d];
                    _workjson.wordList.push(element.content);
                  }
                }
                workArray.push(_workjson);
              }
            }
          }
        }
      }
      var _course = `<h1>${this.course.title}</h1>`;
      let html = "";
      for (let i = 0; i < workArray.length; i++) {
        let _html = this.setHtml(workArray[i]);
        html += _html;
      }

      this.generate(_course + html);
      console.log(workArray);
    },
    setHtml(workJson) {
      var _title =
      // style='display:flex;align-items:center'
        "<div >" +
        "<h2>" +
        workJson.chapName +
        "-" +
        workJson.username;
      ("</h2>");
      ("</div>");
      var _subtitle = "<h3>" + workJson.taskName + "</h3>";
      var _img = "";
      if (workJson.img.length > 0) {
        for (var i = 0; i < workJson.img.length; i++) {
          // _img+=`<div style="margin-top:10px"><div>图片${
          //   i + 1
          // }:<a href='${ workJson.img[i].src}'>${ workJson.img[i].src}</a></div>`
          _img += `<div style="margin-top:10px"><div>图片${
            i + 1
          }</div><img style="max-width:500px" src="${
            workJson.img[i].src
          }"/></div>`;
        }
      }

      var _ask = "";
      if (workJson.askList.length > 0) {
        var _ask = "<h3>问卷调查</h3>";
        for (var i = 0; i < workJson.askList.length; i++) {
          var _div = document.createElement("div");
          _div.innerHTML = `<h4>问卷标题:${workJson.askList[i].askTitle}</h4>`;
          for (var j = 0; j < workJson.askList[i].askJson.length; j++) {
            var _div2 = document.createElement("div");
            _div2.innerHTML = `<h5>第${j + 1}题:${
              workJson.askList[i].askJson[j].askstitle
            }  选择:${workJson.askList[i].radio[j] + 1}</h5> `;
            var _div3 = document.createElement("div");
            for (
              var z = 0;
              z < workJson.askList[i].askJson[j].checkList.length;
              z++
            ) {
              _div3.innerHTML += `<span style="margin-right:5px">${z + 1}.${
                workJson.askList[i].askJson[j].checkList[z]
              }</span>`;
            }
            _div2.innerHTML += `<div>${_div3.innerHTML}</div>`;
            _div.innerHTML += `<div>${_div2.innerHTML}</div>`;
          }
          _ask += `<div>${_div.innerHTML}</div>`;
        }
      }

      var _answer = "";
      if (workJson.questList.length > 0) {
        var _answer = "<h3>问答</h3>";
        for (var i = 0; i < workJson.questList.length; i++) {
          var _div = document.createElement("div");
          _div.innerHTML = `<h4>问答：${workJson.questList[i].answerTitle}</h4>`;
          _div.innerHTML += `<div>${workJson.questList[i].answer}</div>`;
          _answer += `<div>${_div.innerHTML}</div>`;
        }
      }

      var _link = "";
      if (workJson.wordList.length > 0) {
        for (var i = 0; i < workJson.wordList.length; i++) {
          _link += `<div style="margin-top:10px"><a href='${workJson.wordList[i]}'>${workJson.wordList[i]}</a></div>`;
        }
      }

      if (
        !workJson.img.length &&
        !workJson.askList.length &&
        !workJson.questList.length &&
        !workJson.wordList.length
      ) {
        return "";
      }
      return _title + _subtitle + _img + _ask + _answer + _link;
    },
    async generate(a) {
      // 将html文件中需要用到的数据挂载到store上
      this.$store.commit("update", ["report", a]);
      console.log(this.$store.state.report);
      const content = `<!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>报告</title>
      </head>
      <body>
      ${this.$store.state.report}
      </body>
      </html>`;
      // debugger
      //生成报告
      const link = document.createElement("a");
      // link.download = "报告.html"; // 文件名
      let dname = this.course.title+'-'
      var _uname = [];
      var _userA = this.userAarray;
      if (this.uname.length) {
        for (var i = 0; i < _userA.length; i++) {
          if (this.uname.join(",").indexOf(_userA[i].userid) != -1) {
            _uname.push(_userA[i].username);
          }
        }
        dname+=_uname.join('、')+'.html'
      } else {
        dname+='全部学生.html'
      }
      link.download = dname; // 文件名
      link.style.display = "none";
      // 创建文件流
      // 创建bolb实例时，内容一定要放在[]中
      const blob = new Blob([content], {
        type: "text/plain;charset='utf-8'",
      });
      link.href = window.URL.createObjectURL(blob);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      // saveAs(
      //   htmlDocx.asBlob(content, {
      //     orientation: "landscape", //跨域设置
      //   }),
      //   //文件名
      //   "报告.doc"
      // );
    },
    changeChap() {
      let _dyList = this.dyList;
      this.dyAarray = [];
      this.task = [];
      for (var i = 0; i < _dyList.length; i++) {
        if (this.chap.indexOf(_dyList[i].id) != -1) {
          this.dyAarray.push(_dyList[i]);
        }
      }
    },
  },
  watch: {
    cid(newValue, oldValue) {
      this.getCourseDetail();
    },
  },
  mounted() {
    this.getCourseDetail();
  },
};
</script>

<style scoped>
.r_box {
}
.r_cbox {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}
.r_cbox span {
  margin-right: 20px;
}

.r_box .r_select {
  width: 400px;
}

.btn_box {
  margin: 40px 0 0 0;
  width: 100%;
  display: flex;
  justify-content: center;
}
.btn_box .btn {
  width: 60%;
  /* background: rgb(14, 114, 230); */
}

.r_cbox >>> .el-select .el-input.is-focus .el-input__inner {
  border-color: #5c549f;
}
.r_cbox.student_search >>> .el-select .el-input__inner:focus {
  border-color: #5c549f;
}

.el-select-dropdown__item.selected {
  color: #5c549f !important;
}

</style>