<template>
  <div class="cd_body">
    <div class="pb_content_body" style="
                      background: #fff;
                      padding: 0px 25px;
                      box-sizing: border-box;
                      border-radius: 5px;
                      width: 95%;
                    ">
      <div class="pb_head">
        <span>项目数据看板</span>
        <div style="display: flex;align-items: center;">
          <!-- <el-button type="primary" size="small" @click="exportHtml" style="margin-right: 10px;">导出html</el-button> -->
          <el-button type="primary" size="small" @click="exportExcel" style="margin-right: 10px;">导出Excel</el-button>
          <el-switch v-model="mode" active-text="详情模式" inactive-text="简易模式" @change="changeMode">
          </el-switch>
        </div>
      </div>
      <div class="student_head">
        <div class="head_left">
          <span>筛选：</span>
          <el-select v-model="choose" @change="isLoading = true, getData()" style="margin-right: 10px;">
            <el-option label="默认排序" value=""> </el-option>
            <el-option label="学校名称" value="school"> </el-option>
            <el-option label="任务数量" value="task"> </el-option>
            <el-option label="评审结果" value="score"> </el-option>
            <!-- <el-option label="评价" value="eval"> </el-option> -->
            <el-option label="工具" value="tool"> </el-option>
            <el-option label="字数" value="font"> </el-option>
          </el-select>

          <el-select v-model="ttype" @change="page = 1, isLoading = true, getData()">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="item in courseTypeId" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>

          <el-input v-model="search" class="student_input" placeholder="请输入教师名称或学校名称" @input="getData"></el-input>
        </div>
      </div>
    </div>
    <div class="cd_table">
      <el-table ref="table" :data="tableData" border :fit="true" v-loading="isLoading" style="width: 100%"
        :header-cell-style="{ background: '#f1f1f1', fontSize: '17px' }" :row-class-name="tableRowClassName" class="table"
        :height="tableHeight" :key="mode">
        <el-table-column label="序号" prop="number" width="70px" align="center">
        </el-table-column>
        <el-table-column label="项目" width="150px" align="center">
          <template slot-scope="scope">
            <div style="max-height: 180px; overflow: auto">
              <div v-for="(item, index) in scope.row.course" :key="index" class="cd_course" @click="jump(item.courseId)">
                <el-tooltip :content="item.title">
                  <span>{{ item.title }}</span>
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="typename" width="130px" align="center">
        </el-table-column>
        <el-table-column label="学校" prop="school" width="100px" align="center">
        </el-table-column>
        <el-table-column label="负责人" prop="username" width="80px" align="center">
        </el-table-column>
        <el-table-column label="协同人员" prop="cteacher" width="100px" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.cteacher ? scope.row.cteacher : '—' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="ctime" width="85px" align="center">
        </el-table-column>
        <el-table-column label="更新时间" prop="time" width="85px" align="center">
        </el-table-column>
        <el-table-column label="总计" width="85px" align="center">
          <template slot-scope="scope">
            <div class="cd_d_span">
              <div>
                <div>
                  <span>{{ scope.row.jdz.taskC }}</span><span>任务</span>
                </div>
                <div>
                  <span>{{ scope.row.jdz.toolC }}</span><span>工具</span>
                </div>
                <!-- <div>
                  <span>{{ scope.row.jdz.evalC }}</span
                  ><span>评价</span>
                </div> -->
                <div>
                  <span>{{ scope.row.jdz.fontC }}</span><span>字</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="阶段1" v-if="mode" width="85px" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.jd1">
              <div class="cd_d_span">
                <div>
                  <span>{{ scope.row.jd1.taskC }}</span><span>任务</span>
                </div>
                <div>
                  <span>{{ scope.row.jd1.toolC }}</span><span>工具</span>
                </div>
                <!-- <div>
                  <span>{{ scope.row.jd1.evalC }}</span
                  ><span>评价</span>
                </div> -->
                <div>
                  <span>{{ scope.row.jd1.fontC }}</span><span>字</span>
                </div>
              </div>
            </div>
            <div v-else>—</div>
          </template>
        </el-table-column>
        <el-table-column label="阶段2" v-if="mode" width="85px" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.jd2">
              <div class="cd_d_span">
                <div>
                  <span>{{ scope.row.jd2.taskC }}</span><span>任务</span>
                </div>
                <div>
                  <span>{{ scope.row.jd2.toolC }}</span><span>工具</span>
                </div>
                <!-- <div>
                  <span>{{ scope.row.jd2.evalC }}</span
                  ><span>评价</span>
                </div> -->
                <div>
                  <span>{{ scope.row.jd2.fontC }}</span><span>字</span>
                </div>
              </div>
            </div>
            <div v-else>—</div>
          </template>
        </el-table-column>
        <el-table-column label="阶段3" v-if="mode" width="85px" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.jd3">
              <div class="cd_d_span">
                <div>
                  <span>{{ scope.row.jd3.taskC }}</span><span>任务</span>
                </div>
                <div>
                  <span>{{ scope.row.jd3.toolC }}</span><span>工具</span>
                </div>
                <!-- <div>
                  <span>{{ scope.row.jd3.evalC }}</span
                  ><span>评价</span>
                </div> -->
                <div>
                  <span>{{ scope.row.jd3.fontC }}</span><span>字</span>
                </div>
              </div>
            </div>
            <div v-else>—</div>
          </template>
        </el-table-column>
        <el-table-column label="阶段4" v-if="mode" width="85px" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.jd4">
              <div class="cd_d_span">
                <div>
                  <span>{{ scope.row.jd4.taskC }}</span><span>任务</span>
                </div>
                <div>
                  <span>{{ scope.row.jd4.toolC }}</span><span>工具</span>
                </div>
                <!-- <div>
                  <span>{{ scope.row.jd4.evalC }}</span
                  ><span>评价</span>
                </div> -->
                <div>
                  <span>{{ scope.row.jd4.fontC }}</span><span>字</span>
                </div>
              </div>
            </div>
            <div v-else>—</div>
          </template>
        </el-table-column>
        <el-table-column label="阶段5" v-if="mode" width="85px" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.jd5">
              <div class="cd_d_span">
                <div>
                  <span>{{ scope.row.jd5.taskC }}</span><span>任务</span>
                </div>
                <div>
                  <span>{{ scope.row.jd5.toolC }}</span><span>工具</span>
                </div>
                <!-- <div>
                  <span>{{ scope.row.jd5.evalC }}</span
                  ><span>评价</span>
                </div> -->
                <div>
                  <span>{{ scope.row.jd5.fontC }}</span><span>字</span>
                </div>
              </div>
            </div>
            <div v-else>—</div>
          </template>
        </el-table-column>
        <el-table-column label="阶段6" v-if="mode" width="85px" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.jd6">
              <div class="cd_d_span">
                <div>
                  <span>{{ scope.row.jd6.taskC }}</span><span>任务</span>
                </div>
                <div>
                  <span>{{ scope.row.jd6.toolC }}</span><span>工具</span>
                </div>
                <!-- <div>
                  <span>{{ scope.row.jd6.evalC }}</span
                  ><span>评价</span>
                </div> -->
                <div>
                  <span>{{ scope.row.jd6.fontC }}</span><span>字</span>
                </div>
              </div>
            </div>
            <div v-else>—</div>
          </template>
        </el-table-column>
        <el-table-column label="项目简介" v-if="!mode" min-width="80px" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.brief" class="tooltip">
              <el-tooltip :content="scope.row.brief" class="my-tooltip-class" popper-class="text_tooltip">
                <span>{{ scope.row.brief }}</span>
              </el-tooltip>
            </div>
            <div v-else>
              —
            </div>
          </template>
        </el-table-column>
        <el-table-column label="项目所处阶段" prop="lastTask" width="130px" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.lastTask ? scope.row.lastTask : '—' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="评审状态" width="80px" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.score ? '已评分' : '未评分' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="评审结果" prop="score" width="80px" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.score }}分</div>
          </template>
        </el-table-column>
        <el-table-column label="评审类型" prop="psType" width="80px" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.psType == '1' ? '造型结构' : scope.row.psType == '2' ? '开源硬件' : scope.row.psType == '3' ? '软件设计'
              : scope.row.psType == '4' ? '总分' : '—' }}</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180px" align="center">
          <template slot-scope="scope">
            <!-- <div
              @click="getAll(scope.row)"
            >
              查看全部
            </div> -->
            <el-button type="primary" size="small" @click="jump2(scope.row.course[0].courseId)">评审</el-button>
            <el-button type="primary" size="small" @click="setMan(scope.row)">导出</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="student_page">
        <el-pagination background layout="prev, pager, next, sizes" :page-size="pageSize" :page-sizes="[10, 50, 100, 200]"
          :total="total" v-if="page && tableData.length" style="padding: 0px" @current-change="handleCurrentChange"
          @size-change="handleSizeChange"></el-pagination>
      </div>
    </div>
    <el-dialog title="查看" :visible.sync="dialogVisible" :append-to-body="true" width="620px" :before-close="handleClose"
      class="dialog_diy">
      <div v-if="dataArray.length">
        <div class="cd_d_box">
          <span>教师：</span><span>{{ data.username }}</span>
        </div>
        <div class="cd_d_box">
          <span>学校：</span><span>{{ data.school }}</span>
        </div>
        <div class="cd_d_jd">
          <div v-for="(item, index) in dataArray" :key="index" class="cd_d_jd_box">
            <div class="cd_d_jd_name">{{ "阶段" + (index + 1) }}</div>
            <div class="cd_d_jd_content cd_d_span">
              <div>
                <span>{{ data[item].taskC }}</span><span>任务</span>
              </div>
              <div>
                <span>{{ data[item].toolC }}</span><span>工具</span>
              </div>
              <!-- <div>
                <span>{{ data[item].evalC }}</span
                ><span>评价</span>
              </div> -->
              <div>
                <span>{{ data[item].fontC }}</span><span>字</span>
              </div>
            </div>
          </div>
          <div class="cd_d_jd_box">
            <div class="cd_d_jd_name">总计</div>
            <div class="cd_d_jd_content cd_d_span" style="background: #d4d4d4">
              <div>
                <span>{{ data["jdz"].taskC }}</span><span>任务</span>
              </div>
              <div>
                <span>{{ data["jdz"].toolC }}</span><span>工具</span>
              </div>
              <!-- <div>
                <span>{{ data["jdz"].evalC }}</span
                ><span>评价</span>
              </div> -->
              <div>
                <span>{{ data["jdz"].fontC }}</span><span>字</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      isLoading: false,
      org: this.$route.query.org,
      oid: this.$route.query.oid,
      timer: null,
      dialogVisible: false,
      data: {},
      dataArray: [],
      choose: "",
      search: "",
      mode: false,
      courseTypeId: [],
      ttype: "",
      total: 0,
      page: 1,
      pageSize: 100,
      tableHeight: "500px",
    };
  },
  methods: {
    jump(cid) {
      window.parent.postMessage({ cid: cid, screenType: "3s" }, "*");
    },
    jump2(cid) {
      window.parent.postMessage({ cid: cid, screenType: "3s2" }, "*");
    },
    handleClose(done) {
      done();
    },
    tableRowClassName({ row, rowIndex }) {
      if ((rowIndex + 1) % 2 === 0) {
        return "even_row";
      } else {
        return "";
      }
    },
    toText(content) {
      if (content == '' && !content) return ''
      var str = content
      str = str.replace(/<xml>[\s\S]*?<\/xml>/ig, '')
      str = str.replace(/<style>[\s\S]*?<\/style>/ig, '')
      str = str.replace(/<\/?[^>]*>/g, '')
      str = str.replace(/[ | ]*\n/g, '\n')
      str = str.replace(/&nbsp;/ig, '')
      // console.log('****', content)
      // console.log('****', str)
      return str
    },
    getData() {
      let params = {
        org: this.org,
        oid: this.oid,
        type: this.ttype,
        page: this.page,
        pageSize: this.pageSize
        // this.org
      };
      this.ajax
        .get(this.$store.state.api + "selectCaseS2", params)
        .then((res) => {
          this.isLoading = false;
          let _res = res.data[0];
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          // let _res2 = res.data[1];
          for (var i = 0; i < _res.length; i++) {
            let taskC = 0;
            let toolC = 0;
            let evalC = 0;
            let fontC = 0;
            let course = [];
            // for (var j = 0; j < _res2.length; j++) {
            // if (_res[i].userid == _res2[j].userid) {
            course.push({
              title: _res[i].title,
              courseId: _res[i].courseId,
            });
            var _chapter = JSON.parse(_res[i].chapters);
            for (var k = 0; k < _chapter.length; k++) {
              let taskC2 = 0;
              let toolC2 = 0;
              let evalC2 = 0;
              let fontC2 = 0;
              fontC2 += _chapter[k].dyName.length;
              taskC2 = _chapter[k].chapterInfo[0].taskJson.length;
              let _tasks = _chapter[k].chapterInfo[0].taskJson;
              for (var task = 0; task < _tasks.length; task++) {
                if (_tasks[task].eList) {
                  evalC2 += _tasks[task].eList.length;
                }
                console.log(_tasks[task].toolArray , i);
                if (_tasks[task].toolArray && _tasks[task].toolArray.length > 0) {
                  toolC2 += _tasks[task].toolArray.length;
                }
                fontC2 += _tasks[task].task.length;
                fontC2 += this.toText(_tasks[task].taskDetail).length;
                let _tools = _tasks[task].toolArray ? _tasks[task].toolArray : [];
                for (var tool = 0; tool < _tools.length; tool++) {
                  fontC2 += _tools[tool].toolDetail.length;
                }
              }
              if (_res[i]["jd" + (k + 1)]) {
                _res[i]["jd" + (k + 1)].taskC += taskC2;
                _res[i]["jd" + (k + 1)].toolC += toolC2;
                _res[i]["jd" + (k + 1)].evalC += evalC2;
                _res[i]["jd" + (k + 1)].fontC += fontC2;
              } else {
                _res[i]["jd" + (k + 1)] = {};
                _res[i]["jd" + (k + 1)].taskC = taskC2;
                _res[i]["jd" + (k + 1)].toolC = toolC2;
                _res[i]["jd" + (k + 1)].evalC = evalC2;
                _res[i]["jd" + (k + 1)].fontC = fontC2;
              }
              taskC += taskC2;
              toolC += toolC2;
              evalC += evalC2;
              fontC += fontC2;
              // }
              // }
              _res[i]["jdz"] = {};
              _res[i]["jdz"].taskC = taskC;
              _res[i]["jdz"].toolC = toolC;
              _res[i]["jdz"].evalC = evalC;
              _res[i]["jdz"].fontC = fontC;
              _res[i].course = course;
            }
            for (var tk = _chapter.length - 1; tk >= 0; tk--) {
              let _tasks = _chapter[tk].chapterInfo[0].taskJson;
              for (var ttask = _tasks.length - 1; ttask >= 0; ttask--) {
                let _tools = _tasks[ttask].toolArray ? _tasks[ttask].toolArray : [];
                if (_tools.length) {
                  _res[i].lastTask = `第${tk + 1}阶段任务${ttask + 1}步骤${_tools.length}`
                  break;
                } else {
                  continue;
                }
              }
              if (_res[i].lastTask) {
                break;
              }
            }
            if (_res[i].score) {
              var psJson = JSON.parse(_res[i].score)
              if (_res[i].psType == '1') {
                _res[i].score = psJson.cxx + psJson.yssm + psJson.jsygn + psJson.kxdy +
                  psJson.zpwcd
              } else if (_res[i].psType == '2') {
                _res[i].score = psJson.cxx + psJson.yssm + psJson.jsygn + psJson.kxdd +
                  psJson.zpwcd
              } else if (_res[i].psType == '3') {
                _res[i].score = psJson.cxx + psJson.yssm + psJson.jsygn + psJson.kxdd +
                  psJson.zpwcd
              } else if (_res[i].psType == '4') {
                _res[i].score = psJson.z
              }


            } else {
              _res[i].score = 0
            }
          }
          if (this.search) {
            _res = _res.filter((a) => {
              return (
                a.school.indexOf(this.search) != -1 ||
                a.username.indexOf(this.search) != -1
              );
            });
          }
          if (this.choose == "school") {
            let array = _res.sort(function (a, b) {
              return a.school.localeCompare(b.school);
            });
            this.tableData = array.filter((item, index) => {
              item.number = index + 1
              return item;
            });;
          } else if (this.choose == "task") {
            let array = _res.sort(function (a, b) {
              //   return a.jdz.taskC - b.jdz.taskC;
              return b.jdz.taskC - a.jdz.taskC;
            });
            this.tableData = array.filter((item, index) => {
              item.number = index + 1
              return item;
            });;
          } else if (this.choose == "score") {
            let array = _res.sort(function (a, b) {
              return b.score - a.score;
            });
            console.log(array);
            this.tableData = array.filter((item, index) => {
              item.number = index + 1
              return item;
            });;
          } else if (this.choose == "font") {
            let array = _res.sort(function (a, b) {
              //   return a.jdz.fontC - b.jdz.fontC;
              return b.jdz.fontC - a.jdz.fontC;
            });
            this.tableData = array.filter((item, index) => {
              item.number = index + 1
              return item;
            });;
          } else if (this.choose == "eval") {
            let array = _res.sort(function (a, b) {
              //   return a.jdz.fontC - b.jdz.fontC;
              return b.jdz.evalC - a.jdz.evalC;
            });
            this.tableData = array.filter((item, index) => {
              item.number = index + 1
              return item;
            });;
          } else if (this.choose == "tool") {
            let array = _res.sort(function (a, b) {
              //   return a.jdz.fontC - b.jdz.fontC;
              return b.jdz.toolC - a.jdz.toolC;
            });
            this.tableData = array.filter((item, index) => {
              item.number = index + 1
              return item;
            });
          } else {
            this.tableData = _res.filter((item, index) => {
              item.number = index + 1
              return item;
            });;
          }
        })
        .catch((err) => {
          this.isLoading = false;
          console.error(err);
        });
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.isLoading = true
      this.getData();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.page = 1;
      this.isLoading = true
      this.getData();
    },
    selectAllType() {
      let params = {
        org: this.org && this.org != "" ? this.org : "",
        oid: this.oid && this.oid != "" ? this.oid : "",
      };
      this.ajax
        .get(this.$store.state.api + "selectAllTypeS", params)
        .then((res) => {
          let _courseTypeId = [];
          if (res.data[2].length == 0 && res.data[3].length == 0) {
            for (var j = 0; j < res.data[1].length; j++) {
              if (res.data[1][j].pid == "34629ce3-d02f-11ec-8c78-005056b86db5" || res.data[1][j].pid == "2f8beae3-d030-11ec-8c78-005056b86db5") {
                _courseTypeId.push(res.data[1][j]); // 去除公共分类
              }
            }
          } else {
            if (res.data[2].length > 0) {
              for (var j = 0; j < res.data[2].length; j++) {
                _courseTypeId.push(res.data[2][j]); // 去除公共分类
              }
            }
            if (res.data[3].length > 0) {
              for (var j = 0; j < res.data[3].length; j++) {
                _courseTypeId.push(res.data[3][j]); // 去除公共分类
              }
            }
          }
          this.courseTypeId = _courseTypeId;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    getAll(res) {
      this.data = res;
      let a = Object.keys(res);
      a = a.filter((el) => {
        return el.indexOf("jd") != -1 && el != "jdz";
      });
      this.dataArray = a;
      this.dialogVisible = true;
    },
    changeMode() {
      this.tableHeight =
        window.innerHeight - this.$refs.table.$el.offsetTop - 50;
      if (this.tableHeight <= 530) {
        this.tableHeight = 530;
      }
    },
    exportExcel() {
      if (!this.tableData.length) {
        this.$message.error('请等待加载数据')
        return;
      }

      var res = this.tableData;
      //如果value的json字段的key值和想要的headers值不一致时，可做如下更改
      //将和下面的Object.fromEntries结合，将json字段的key值改变为要求的excel的header值
      var array = [];
      for (var i = 0; i < res.length; i++) {
        var _json = {};
        _json["序号"] = res[i].number;
        _json["负责人"] = res[i].username;
        _json["项目"] = res[i].course[0].title;
        _json["分类"] = res[i].typename;
        _json["学校"] = res[i].school;
        _json["协同人员"] = res[i].cteacher ? res[i].cteacher : '—';
        _json["创建时间"] = res[i].ctime;
        _json["更新时间"] = res[i].time;
        _json["总计"] = `${res[i].jdz.taskC}任务 ${res[i].jdz.toolC}工具 ${res[i].jdz.fontC}字数`;
        if (this.mode) {
          _json["阶段1"] = res[i].jd1 ? res[i].brief : '—';
          _json["阶段2"] = res[i].jd2 ? res[i].brief : '—';
          _json["阶段3"] = res[i].jd3 ? res[i].brief : '—';
          _json["阶段4"] = res[i].jd4 ? res[i].brief : '—';
          _json["阶段5"] = res[i].jd5 ? res[i].brief : '—';
          _json["阶段6"] = res[i].jd6 ? res[i].brief : '—';
        } else {
          _json["项目简介"] = res[i].brief ? res[i].brief : '—';
        }
        _json["项目所处阶段"] = res[i].lastTask ? res[i].lastTask : '—';
        _json["评审状态"] = res[i].score ? '已评分' : '未评分';
        _json["评审结果"] = res[i].score + '分';
        _json["评审类型"] = res[i].psType == '1' ? '造型结构' : res[i].psType == '2' ? '开源硬件' : res[i].psType == '3' ? '软件设计' : res[i].psType == '4' ? '总分' : '—';
        array.push(_json);
      }

      var XLSX = require("xlsx");
      const workbook = XLSX.utils.book_new(); //创建一个新的工作簿对象
      let ws = XLSX.utils.json_to_sheet(array); //将json对象数组转化成工作表
      // ws["!cols"] = [
      //   //设置每一列的宽度
      //   { wch: 50 },
      //   { wch: 50 },
      //   { wch: 50 },
      // ];
      XLSX.utils.book_append_sheet(workbook, ws, "sheet1"); //把sheet添加到workbook里，第三个参数是sheet名
      XLSX.writeFile(workbook, "项目数据导出.xlsx");
      // const wopts = { bookType: "xlsx", bookSST: false, type: "array" };//写入的样式bookType:输出的文件类型，type：输出的数据类型，bookSST: 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
      // const wbout = XLSX.write(workbook, wopts);// 浏览器端和node共有的API,实际上node可以直接使用xlsx.writeFile来写入文件,但是浏览器没有该API
      // FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }), `${title} demo.xlsx`);//保存文件
      this.$message({
        message: "导出成功",
        type: "success",
      });
    },
    async exportHtml() {
      let res = this.tableData;
      for (let i = 0; i < res.length; i++) {
        await this.setMan(res[i])
      }
    },
    exportCourse(course, Man) {
      // 项目名称、项目创建人、协同人员、创建时间、修改时间、所属赛道、所属主题、项目详情简介；项目阶段数量、项目任务数量、项目进展
      // if possible 项目所处阶段、各阶段负责人/任务周期/协同者/任务描述/项目方案
      let _course = `<h1>${course.course[0].title}</h1>`
      let _people = `<h2>负责人：${course.username}</h2>`
      let _cteacher = `<h3>协同人员：${course.cteacher ? course.cteacher : '—'}</h3>`
      let _time = `<h2>创建时间：${course.ctime} 修改时间：${course.time}</h2>`
      let _type = `<h2>分类：${course.typename}</h2>`
      let _detail = `<h2>项目详情：${course.brief}</h2>`
      let _jdZ = `<h2>项目阶段数量：${course.chapters.length} 项目任务任数量：${course.jdz.taskC}</h2>`
      let _lasttask = ''
      if (course.lastTask) {
        _lasttask = `<h2>项目所处阶段：${course.lastTask}</h2>`
      }

      let _chapter = course.chapters
      let chapterHTML = ''
      for (var i = 0; i < _chapter.length; i++) {
        chapterHTML += `<h2 style="border-top: 1px solid #ddd;padding: 10px 0 0 0;">第${i + 1}阶段-${_chapter[i].dyName}</h2>`
        let taskJson = _chapter[i].chapterInfo[0].taskJson
        for (var j = 0; j < taskJson.length; j++) {
          chapterHTML += `<h3>任务${j + 1}-${taskJson[j].task}</h3>`
          if (taskJson[j].time && taskJson[j].time.length) {
            chapterHTML += `<p>任务周期：${this.timeB(taskJson[j].time[0])}至${this.timeB(taskJson[j].time[1])}</p>`
          }
          if (taskJson[j].people) {
            chapterHTML += `<p>负责人：${this.getMan(Man, taskJson[j].people)}</p>`
          }
          if (taskJson[j].tcMember && taskJson[j].tcMember.length) {
            let tcMember = []
            for (var tc = 0; tc < taskJson[j].tcMember.length; tc++) {
              tcMember.push(this.getMan(Man, taskJson[j].tcMember[tc]))
            }
            chapterHTML += `<p>协同者：${tcMember.join(",")}</p>`
          }
          chapterHTML += `<div>任务描述</div>`
          chapterHTML += `<div>${taskJson[j].taskDetail}</div>`
          let _tool = taskJson[j].toolArray ? taskJson[j].toolArray : []
          for (var tool = 0; tool < _tool.length; tool++) {
            if (_tool[tool].tool == 1) {
              chapterHTML += `<h4>步骤${tool + 1}:电子白板</h4>`
            } else if (_tool[tool].tool == 3) {
              chapterHTML += `<h4>步骤${tool + 1}:思维导图</h4>`
            } else if (_tool[tool].tool == 6) {
              chapterHTML += `<h4>步骤${tool + 1}:协同文档</h4>`
            } else if (_tool[tool].tool == 15) {
              chapterHTML += `<h4>步骤${tool + 1}:问答工具</h4>`
            } else if (_tool[tool].tool == 53) {
              chapterHTML += `<h4>步骤${tool + 1}:文件上传</h4>`
            } else if (_tool[tool].tool == 54) {
              chapterHTML += `<h4>步骤${tool + 1}:拍照</h4>`
            } else if (_tool[tool].tool == 55) {
              chapterHTML += `<h4>步骤${tool + 1}:压缩文件</h4>`
            } else if (_tool[tool].tool == 56) {
              chapterHTML += `<h4>步骤${tool + 1}:投票</h4>`
            } else if (_tool[tool].tool == 48) {
              chapterHTML += `<h4>步骤${tool + 1}:表格</h4>`
            } else if (_tool[tool].tool == 52) {
              chapterHTML += `<h4>步骤${tool + 1}:文档</h4>`
            } else if (_tool[tool].tool == 51) {
              chapterHTML += `<h4>步骤${tool + 1}:资源库</h4>`
            } else if (_tool[tool].tool == 56) {
              chapterHTML += `<h4>步骤${tool + 1}:投票</h4>`
            } else if (_tool[tool].tool == 57) {
              chapterHTML += `<h4>步骤${tool + 1}:CocoPi</h4>`
            }

            if (_tool[tool].tool == 51) {
              if (_tool[tool].toolData.length) {
                for (var ti = 0; ti < _tool[tool].toolData.length; ti++) {
                  let _td = _tool[tool].toolData[ti]
                  if (_td.type == 2) {
                    chapterHTML += `<div><span>视频链接：</span><a href='${_td.url}'>${_td.name}</a></div>`
                  } else if (_td.type == 3) {
                    chapterHTML += `<div><span>文档链接：</span><a href='${_td.url}'>${_td.name}</a></div>`
                  } else if (_td.type == 6) {
                    chapterHTML += `<div>图文标题：${_td.name}</div>`
                    chapterHTML += `<div class="cont"><span>图文内容：</span>${_td.url}</div>`
                  } else if (_td.type == 8) {
                    chapterHTML += `<div><span>链接：</span><a href='${_td.src}'>${_td.title}</a></div>`
                  }
                }
              }
            } else {
              if (_tool[tool].toolPhoto.length) {
                for (var worki = 0; worki < _tool[tool].toolPhoto.length; worki++) {
                  let photo = _tool[tool].toolPhoto[worki]
                  if (photo.type == 1) {
                    chapterHTML += `<div><img style="max-width:500px" src="${photo.content}"/></div>`
                  } else if (photo.type == 10) {
                    chapterHTML += `<div class="cont">${JSON.parse(photo.content)}</div>`
                  } else if (photo.type == 4) {
                    chapterHTML += `<div><span>文档链接：</span><a href='${photo.content}'>${photo.content}</a></div>`
                  } else if (photo.type == 5) {
                    chapterHTML += `<div><span>视频链接：</span><a href='${photo.content}'>${photo.content}</a></div>`
                  } else if (photo.type == 12) {
                    chapterHTML += `<div class="cont">${JSON.parse(photo.content)}</div>`
                  } else if (photo.type == 14) {
                    var _ask = "";
                    var _div = document.createElement("div");
                    _div.innerHTML = `<h4>标题:${_tool[tool].askJson.askTitle}</h4>`;
                    for (
                      var j = 0;
                      j < _tool[tool].askJson.askJson.length;
                      j++
                    ) {
                      let answer = JSON.parse(photo.content)
                      var _div2 = document.createElement("div");
                      _div2.innerHTML = `<h5>第${j + 1}题:${_tool[tool].askJson.askJson[j].askstitle
                        }  选择:${answer &&
                          answer.length > 0
                          ? answer[j]
                          : 1
                        }</h5> `;
                      var _div3 = document.createElement("div");
                      for (
                        var z = 0;
                        z <
                        _tool[tool].askJson.askJson[j].checkList
                          .length;
                        z++
                      ) {
                        _div3.innerHTML += `<span style="margin-right:5px">${z + 1}.${_tool[tool].askJson.askJson[j].checkList[z]
                          }</span>`;
                      }
                      _div2.innerHTML += `<div>${_div3.innerHTML}</div>`;
                      _div.innerHTML += `<div>${_div2.innerHTML}</div>`;
                    }
                    _ask += `<div>${_div.innerHTML}</div>`;
                    chapterHTML += _ask
                  } else if (photo.type == 13) {
                    chapterHTML += `<div><span>文件链接：</span><a href='${photo.content}'>${photo.content}</a></div>`
                  }
                  // <img v-if="photo.type == 1" :src="photo.content" @click="previewImg(photo.content)" />
                  //         <img v-if="photo.type == 10" :src="word" @click="openTable(photo.content)" />
                  //         <img v-if="photo.type == 4" :src="word" @click="openFile(photo.content)" />
                  //         <img v-if="photo.type == 5" :src="video" @click="openVideo(photo.content)" />
                  //         <img v-if="photo.type == 12" :src="word" @click="openText(photo.content)" />
                  //         <img v-if="photo.type == 14" :src="word" @click="
                  //           openAsk(photo.content, taskCount, toolIndex)
                  //         " />
                  //         <img v-if="photo.type == 13" :src="zip" @click="downloadFile(photo.content)" />
                }
              }
            }

            if (_tool[tool].toolDetail) {
              chapterHTML += `<div>工具描述</div>`
              chapterHTML += `<div>${_tool[tool].toolDetail}</div>`
            }
          }
        }
      }

      var _html = _course + _people + _cteacher + _time + _type + _detail + _jdZ + _lasttask + chapterHTML;
      this.generate(course, _html);
    },
    getMan(manAarray, people) {
      let _people = "";
      if (manAarray.length) {
        for (var i = 0; i < manAarray.length; i++) {
          if (manAarray[i].userid == people) {
            _people = manAarray[i].name;
            break;
          }
        }
      }
      return _people ? _people : "";
    },
    async setMan(ccourse) {
      let course = JSON.parse(JSON.stringify(ccourse));
      this.ManAarray = [];
      let array = course.course_teacher.split(",")
      if (array.indexOf(course.userid) == -1) {
        array.push(course.userid);
      }
      let params = {
        uid: array.join(","),
      };
      const res = await this.ajax.get(this.$store.state.api + "getAllUserById", params)
      let params2 = {
        cid: course.courseId,
      }
      const res2 = await this.ajax.get(this.$store.state.api + "select_student_course_detail", params2)
      let unitJson = JSON.parse(course.chapters);
      let works = res2.data[2];
      for (var i = 0; i < unitJson.length; i++) {
        let task = unitJson[i].chapterInfo[0].taskJson;
        for (var j = 0; j < task.length; j++) {
          var tool = task[j].toolArray ? task[j].toolArray : [];
          for (var z = 0; z < tool.length; z++) {
            let _tool = tool[z];
            _tool.toolPhoto = [];
            _tool.people = [];
            for (var k = 0; k < works.length; k++) {
              let _work = works[k];
              if (
                _work.stage == i &&
                _work.task == j &&
                _work.tool == z &&
                _work.atool == _tool.tool
              ) {
                if (_tool.tool == 48 || _tool.tool == 52) {
                  _tool.toolPhoto[0] = _work;
                  if (_tool.people.indexOf(_work.username) == -1) {
                    _tool.people.push(_work.username);
                  }
                } else {
                  _tool.toolPhoto.push(_work);
                }
              }
            }
          }
        }
      }
      course.chapters = unitJson
      this.exportCourse(course, res.data[0])
    },
    async generate(a, html) {
      // 将html文件中需要用到的数据挂载到store上
      this.$store.commit("update", ["report", html]);
      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>
          <style>
          .cont{
            word-break: break-all;
          }
          .cont table {
              border-top: 1px solid #ccc;
              border-left: 1px solid #ccc;
            }

            .cont table td,
            .cont table th {
              border-bottom: 1px solid #ccc;
              border-right: 1px solid #ccc;
              /* padding: 20px 5px; */
              padding: 5px 10px;
              max-width: 0px;
              height: 30px;
              vertical-align: baseline;
            }

            .cont table th {
              border-bottom: 2px solid #ccc;
              text-align: center;
            }

            /* blockquote 样式 */
            .cont blockquote {
              display: block;
              border-left: 8px solid #d0e5f2;
              padding: 5px 10px;
              margin: 10px 0;
              line-height: 1.4;
              font-size: 100%;
              background-color: #f1f1f1;
            }

            /* code 样式 */
            .cont code {
              display: inline-block;
              *display: inline;
              *zoom: 1;
              background-color: #f1f1f1;
              border-radius: 3px;
              padding: 3px 5px;
              margin: 0 3px;
            }

            .cont pre code {
              display: block;
            }

            /* ul ol 样式 */
            .cont ul,
            .cont ol {
              margin: 10px 0 10px 20px;
            }

          </style>
      </head>
      <body>
      ${this.$store.state.report}
      </body>
      </html>`;
      // debugger
      // 生成报告
      const link = document.createElement("a");
      let dname = a.course[0].title + "-" + a.username + ".html";
      // link.download = "报告.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"
      // );
    },
    timeB(timeA) {
      var time = new Date(timeA);
      time.setTime(time.getTime());
      var s2 = time.getFullYear() + "-" + ((time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) : (time.getMonth() + 1)) + "-"
        + ((time.getDate()) < 10 ? '0' + (time.getDate()) : (time.getDate()));
      return time.getFullYear() ? s2 : '无'
    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
  },
  mounted() {
    this.$nextTick(function () {
      this.tableHeight =
        window.innerHeight - this.$refs.table.$el.offsetTop - 50;
      if (this.tableHeight <= 530) {
        this.tableHeight = 530;
      }
      // 监听窗口大小变化
      let self = this;
      window.onresize = function () {
        self.tableHeight =
          window.innerHeight - self.$refs.table.$el.offsetTop - 50;
        if (self.tableHeight <= 530) {
          self.tableHeight = 530;
        }
      };
    });
    this.isLoading = true;
    this.getData();
    this.selectAllType();
    this.timer = setInterval(() => {
      this.getData();
    }, 60000);
  },
};
</script>

<style scoped>
.student_input {
  width: 190px;
  font-size: 13px;
  padding: 0 10px;
}

.cd_body {
  height: 100%;
  width: 100%;
}

.pb_head {
  margin: 0 !important;
  width: 100% !important;
  display: flex;
  justify-content: space-between;
}

.student_head {
  margin-top: 10px;
  padding-bottom: 10px;
  display: flex;
  justify-content: space-between;
}

.head_left {
  display: flex;
  align-items: center;
}

.cd_title span {
  font-size: 25px;
  font-weight: 700;
}

.cd_table {
  width: 95%;
  margin: 0 auto;
  padding: 0 0 10px;
}

.el-table>>>.even_row {
  background-color: #f1f1f1 !important;
}

.dialog_diy>>>.el-dialog {
  background: #fafafa;
}

.dialog_diy>>>.el-dialog__header {
  background: #3d67bc !important;
  padding: 15px 20px;
}

.dialog_diy>>>.el-dialog__title {
  color: #fff;
}

.dialog_diy>>>.el-dialog__headerbtn {
  top: 19px;
}

.dialog_diy>>>.el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.dialog_diy>>>.el-dialog__headerbtn .el-dialog__close:hover {
  color: #fff;
}

.cd_d_box {
  font-size: 16px;
}

.cd_d_box+.cd_d_box {
  margin-top: 10px;
}

.cd_d_jd {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.cd_d_jd_box {
  width: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* background: #eee; */
  border-radius: 5px;
  margin: 10px 15px 0 0;
}

.cd_d_jd_box {}

.cd_d_jd_content {
  width: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #eee;
  border-radius: 5px;
  padding: 5px 0;
}

.cd_d_jd_content div+div {
  margin-top: 5px;
}

.cd_d_jd_content div span+span {
  margin-left: 5px;
}

.cd_d_jd_name {
  margin-bottom: 5px;
  color: #184ebd;
}

.cd_d_span div:nth-child(1) span:nth-child(1) {
  color: #3887fe;
}

.cd_d_span div:nth-child(2) span:nth-child(1) {
  color: #fe3987;
}

.cd_d_span div:nth-child(3) span:nth-child(1) {
  color: #10bb6e;
}

.cd_d_span div:nth-child(4) span:nth-child(1) {
  color: #3887fe;
}

.cd_d_span div span:nth-child(1) {
  margin-right: 5px;
}

.cd_course {
  cursor: pointer;
  width: 100%;
  display: flex;
}

.cd_course span {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.table>>>.cell {
  padding: 0px 3px !important;
}

.student_page {
  width: 100%;
  margin: 20px auto;
}

/* .table >>> .el-table .cell, .table >>> .el-table--border td:first-child .cell, .table >>> .el-table--border th:first-child .cell{
  padding: 0 3px;
} */

.tooltip>>>.my-tooltip-class {
  display: -webkit-box;
  overflow: hidden;
  white-space: normal !important;
  text-overflow: ellipsis;
  word-wrap: break-word;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical
}
</style>