<template>
  <div class="diary">
    <div
      style="background-color: #fff;width: 100%;height: 100%;box-sizing: border-box; padding: 15px;"
    >
      <!-- 分类与导出 -->
      <div class="top">
        <div class="oneType">
          <div
            v-for="(i, index) in VeidooList"
            :key="index + 'a'"
            :class="Veidoo == i.id ? 'onTypeTxt' : 'onTypeTxt2'"
            @click="changeType(i)"
          >
            {{ i.name }}
            <div
              class="line"
              :style="{ display: Veidoo == i.id ? 'block' : 'none' }"
            ></div>
          </div>
        </div>
        <div class="wordBtn" @click="judgeExport">
          导出Excel
        </div>
        <div class="twoType">
          <div
            v-for="(i, index) in VeidooListChild"
            :key="index + 'b'"
            :class="VeidooChild == i.id ? 'twoTypeTxt' : 'twoTypeTxt2'"
            @click="changeTypeChild(i)"
          >
            {{ i.name }}
          </div>
        </div>
      </div>
      <div class="selectSty">
        <div style="margin-right: 10px;">时间筛选</div>
        <el-select v-model="termId" placeholder="请选择">
          <el-option
            label="全部"
            @click.native="changeTerm('')"
            value=""
          ></el-option>
          <el-option
            v-for="item in termList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            @click.native="changeTerm(item.id)"
          >
          </el-option>
        </el-select>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        header-align="center"
        :header-cell-style="{
          background: '#E0EAFB',
          color: 'rgba(0, 0, 0, 0.90)'
        }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          align="center"
          label="全选"
          :show-overflow-tooltip="true"
          width="55"
        >
        </el-table-column>
        <el-table-column
          prop="create_at"
          label="创建时间"
          align="center"
          width="120"
        >
          <!-- <template slot-scope="scope">{{ scope.row.date }}</template> -->
        </el-table-column>
        <el-table-column
          prop="recordTit"
          label="观察内容"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="place"
          label="观察地点"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="tname"
          label="维度"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="recordContent"
          label="内容"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="175px"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div class="evaluate">
              <div
                class="TableBtn"
                style="color: #3681FC;"
                @click="lookRecord(scope.row)"
              >
                查看
              </div>
              <div
                class="TableBtn"
                style="color: #3681FC;"
                @click="updateCred(scope.row)"
              >
                修改
              </div>
              <div
                class="TableBtn"
                style="color: #EE3E3E;"
                @click="delRecord(scope.row)"
              >
                删除
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @current-change="handleCurrentChange"
        background
        :page-size="8"
        layout="prev, pager, next"
        :total="total"
        class="pagination"
      >
      </el-pagination>
    </div>
    <div v-if="isPop" @click="closePop" class="shade"></div>
    <popbox
      ref="refPop"
      v-if="isPop"
      :judgeNum="judgeNum"
      :recordDataCopy="recordData"
      :termList="termList"
      :weiList="weiList"
      :studentList="studentList"
      @selectData="selectData"
      @closePop="closePop"
    ></popbox>
  </div>
</template>

<script>
import popbox from "./component/popbox";
export default {
  components: {
    popbox
  },
  data() {
    return {
      // 筛选数据
      VeidooList: [],
      VeidooListChild: [],
      // 默认选择项
      // VeidooValue:{},
      // 默认选择项
      termValue: "",
      // 学期数据
      termList: [],

      // 要提交的筛选数据项
      Veidoo: "",
      VeidooChild: "",
      termId: "",
      page: 1, //当前页数，默认为第一页

      // 本页多少条数
      total: 0,

      tableData: [],
      multipleSelection: [],

      // 组件信息数据
      isPop: false,
      recordData: {},
      recordDataCopy: {},
      weiList: [],
      studentList: [],
      judgeNum: 0
    };
  },
  methods: {
    closePop() {
      this.isPop = false;
      // console.log('关了');
      // this.$refs.refPop.fuClick(this.recordData);
    },

    // 切换页
    handleCurrentChange(val) {
      //当页数发生改变的时候调用获取列表数据请求
      // console.log(`当前页: ${val}`);
      this.Page = val;
      this.selectData();
    },
    // 获取数据
    getData() {
      // 获取筛选框数据
      let params = {
        uid: this.$route.query.userid,
        cid: this.$route.query.cid,
        org: this.$route.query.org,
        cu: ""
      };
      this.ajax
        .get(this.$store.state.api + "selectSETable", params)
        .then(res => {
          this.isLoading = false;
          var ftype = res.data[1]; //公共父级分类
          var stype = res.data[2]; //公共子级分类
          var sctype = res.data[3]; //该学校子级分类
          var fctype = res.data[4]; //该学校父级分类
          var fotype = res.data[5]; //组织父级分类
          var sotype = res.data[6]; //组织子级分类
          var allfType = [];
          var allsType = [];
          if (fotype.length == 0 && sotype.length == 0) {
            if (fctype.length == 0 && sctype.length == 0) {
              for (var i = 0; i < ftype.length; i++) {
                allfType.push(ftype[i]);
              }
              for (var i = 0; i < stype.length; i++) {
                allsType.push(stype[[i]]);
              }
            } else {
              for (var i = 0; i < fctype.length; i++) {
                allfType.push(fctype[i]);
              }
              for (var i = 0; i < sctype.length; i++) {
                allsType.push(sctype[[i]]);
              }
            }
          } else {
            for (var i = 0; i < fotype.length; i++) {
              allfType.push(fotype[i]);
            }
            for (var i = 0; i < sotype.length; i++) {
              allsType.push(sctysotypepe[[i]]);
            }
          }

          allfType.forEach((e, index) => {
            allfType[index][e.id] = [];
          });

          // 大数组套小数组循环，进行push操作，最后手动添加艺术
          allfType.forEach((e, w) => {
            allsType.forEach((k, index) => {
              if (e.id == k.pid) {
                // console.log("e.id", ftype[w][e.id]);
                allfType[w][e.id].push(k);
              }
            });
          });
          this.VeidooList = allfType;

          // 渲染完数据后立即查询一次默认筛选项
          this.changeType(this.VeidooList[0]);

          // 学期数据
          this.ajax
            .get(this.$store.state.api + "selectTerm", {})
            .then(res => {
              this.isLoading = false;
              console.log("学期数据", res.data[0]);
              this.termList = res.data[0];
              this.termList.forEach(e => {
                if (e.defaultC == 1) {
                  this.termId = e.id;
                  // this.termValue = e.name;
                }
              });

              // 调用获取数据方法
              this.selectData();
            })
            .catch(err => {
              this.isLoading = false;
              console.error(err);
            });
          // console.log("ftype1", ftype);
        })
        .catch(err => {
          this.isLoading = false;
          console.error(err);
        });

      // 获取纬度筛选框
      const data = {
        oid: this.$route.query.org,
        cla: 0
      };

      this.ajax.get(this.$store.state.api + "selectVeiDoo", data).then(res => {
        // console.log(res);
        this.weiList = res.data[0];
        console.log("this.weiList", res);
      });
      // 获取班学生列表
      const data2 = {
        cid: this.$route.query.cid,
        uid: this.$route.query.suid
      };
      this.ajax
        .get(this.$store.state.api + "selectManyClassStudent", data2)
        .then(res => {
          // console.log(res);
          this.studentList = res.data[0];
          console.log("this.studentList", res);
        });
    },
    // 选择导出哪些记录
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    // 点击大筛选项
    changeType(e) {
      // console.log(e[e.id]);
      // 点击大筛选项，清除小筛选项
      this.VeidooChild = "";

      this.Veidoo = e.id;
      this.VeidooListChild = e[e.id];
      this.selectData();
    },
    // 点击小选项
    changeTypeChild(e) {
      // 重复点击取消选择
      if (this.VeidooChild == e.id) {
        this.VeidooChild = "";
      } else {
        this.VeidooChild = e.id;
      }
      this.selectData();
    },
    // 点击学期
    changeTerm(e) {
      console.log(e);
      this.termId = e;
      this.selectData();
    },
    // 获取筛选数据
    selectData() {
      let data = {
        uid: this.$route.query.suid,
        cid: this.$route.query.cid,
        cu: this.Veidoo,
        cn: this.VeidooChild,
        cm: this.termId,
        page: this.page,
        lim: 8
      };
      // return console.log("selectData", data);
      this.ajax
        .get(this.$store.state.api + "selectVeidooType", data)
        .then(res => {
          this.isLoading = false;
          this.tableData = res.data[0];
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          console.log(" 获取筛选数据", res);
        });
    },
    // 修改记录
    updateCred(e) {
      this.judgeNum = 1;
      this.isPop = true;
      if (!Array.isArray(e.type)) {
        if (!e.type) {
          e.type = [];
        } else {
          e.type = e.type.split(",");
        }
      }
      if (!Array.isArray(e.contact)) {
        if (!e.contact) {
          e.contact = [];
        } else {
          e.contact = e.contact.split(",");
        }
      }
      if (!Array.isArray(e.recordImg)) {
        if (!e.recordImg) {
          e.recordImg = [];
        } else {
          e.recordImg = e.recordImg.split(",");
        }
      }
      this.recordData = e;
    },
    // 判断导出数据
    judgeExport() {
      if (this.multipleSelection.length) {
        this.exportExcel();
      } else {
        console.log(2);
      }
    },
    // exportExcelTwo() {
    //   let data = {
    //     uid: this.$route.query.suid,
    //     cid: this.$route.query.cid,
    //     cu: this.Veidoo,
    //     cn: this.VeidooChild,
    //     cm: this.termId,
    //     page: this.page,
    //     lim: 8
    //   };
    //   // return console.log("selectData", data);
    //   this.ajax
    //     .get(this.$store.state.api + "selectVeidooType", data)
    //     .then(res => {
    //       this.isLoading = false;
    //       this.tableData = res.data[0];
    //       this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
    //       console.log(" 获取筛选数据", res);
    //     });
    // },
    exportExcel() {
      // var res = res.data[0];
      var res = this.multipleSelection;

      //如果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].create_at;
        _json["班级"] = res[i].className;
        _json["记录时间"] = res[i].recordDate;
        // _json["用户名"] = res[i].studentName;
        // _json["用户名"] = res[i].studentName;
        _json["观察地点"] = res[i].place;
        _json["观察内容"] = res[i].recordTit;
        _json["内容"] = res[i].recordContent;

        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"
      });
    },
    // 删除记录
    delRecord(e) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          this.ajax
            .post(this.$store.state.api + "updateRecord", [{ rid: e.rid }])
            .then(res => {
              console.log(res);
              this.selectData();

              this.$message({
                type: "success",
                message: "已删除"
              });
              // this.isLoading = false; updateRecord
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
      // return console.log(e);
    },
    lookRecord(e) {
      this.judgeNum = 0;
      console.log("eeeeeeeeeeeeeeeeeee", e);
      this.isPop = true;
      if (!Array.isArray(e.type)) {
        if (!e.type) {
          e.type = [];
        } else {
          e.type = e.type.split(",");
        }
      }
      if (!Array.isArray(e.contact)) {
        if (!e.contact) {
          e.contact = [];
        } else {
          e.contact = e.contact.split(",");
        }
      }
      if (!Array.isArray(e.recordImg)) {
        if (!e.recordImg) {
          e.recordImg = [];
        } else {
          e.recordImg = e.recordImg.split(",");
        }
      }
      this.recordData = e;
    }
  },
  created() {
    this.getData();
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.selectData();
    // });
  }
};
</script>

<style scoped>
.shade {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 3;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}
/* .el-pager li{
  background-color: #fff !important;
  border: 1px solid #DCDCDC !important;
}
.el-pager li:nth-child(1){
  background-color: #fff !important;
  border: none !important;
} */
.el-table__cell {
  text-align: center !important;
}
.diary {
  box-sizing: border-box;
  padding: 15px;
  height: 100%;
}
.top {
  width: 100%;
  display: flex;
  position: relative;
  justify-content: space-between;
  align-items: flex-end;
}
.oneType {
  display: flex;
  justify-content: flex-start;
  /* flex-direction: column; */
}
.onTypeTxt {
  cursor: pointer;
  display: flex;
  font-size: 16px;
  position: relative;
  align-items: center;
  justify-content: center;
  padding: 16px;
  color: rgba(54, 129, 252, 1);
}
.onTypeTxt2 {
  cursor: pointer;
  display: flex;
  font-size: 16px;
  position: relative;
  align-items: center;
  justify-content: center;
  padding: 16px;
  color: rgba(0, 0, 0, 0.9);
}
.line {
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translate(-50%, 0);
  height: 3px;
  background-color: #3681fc;
  width: 50%;
}
.wordBtn {
  cursor: pointer;
  background-color: #3681fc;
  color: #fff;
  width: 100px;
  height: 34px;
  border-radius: 3px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.twoType {
  position: absolute;
  display: flex;
  top: 120%;
  left: 0;
}
.twoTypeTxt {
  cursor: pointer;
  box-sizing: border-box;
  min-width: 76px;
  padding: 0 10px;
  height: 34px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: #fff;
  background-color: #3681fc;
  border-radius: 3px;
  border: 1px solid #e7e7e7;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}
.twoTypeTxt2 {
  cursor: pointer;
  box-sizing: border-box;
  min-width: 76px;
  padding: 0 10px;
  height: 34px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: #000;
  border-radius: 3px;
  border: 1px solid #e7e7e7;
  border-radius: 3px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}
.selectSty {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  /* margin-top: 60px; */
  margin: 80px 10px 40px 0;
}
.evaluate {
  text-align: center;
  font-family: "Microsoft YaHei";
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 22px; /* 157.143% */
  display: flex;
  justify-content: space-around;
}
.TableBtn {
  cursor: pointer;
}
.pagination {
  margin-top: 20px;
  float: right;
}
</style>
