<template>
  <div class="diary">
    <div class="diary-content">
      <!-- 分类与导出 -->
      <div class="top" :style="{ marginBottom: !ftypeId ? 0 : 60 + 'px' }">
        <div class="oneType">
          <div class="all_choose" style="margin: 0;">
            <div
              @click="clickFtypeId('')"
              :class="ftypeId == '' ? 'onTypeTxt' : 'onTypeTxt2'"
              style="position: relative;"
            >
              <span>全部</span>
              <!-- <div
                class="line"
                :style="{ display: ftypeId == '' ? 'block' : 'none' }"
              ></div> -->
            </div>
          </div>
          <div
            class="all_choose"
            v-for="(item, index) in VeidooList"
            :key="index"
            :style="{ margin: !VeidooJson[item.id].length && 0 }"
          >
            <!-- 大分类 -->
            <div
              v-if="VeidooJson[item.id].length"
              @click="clickFtypeId(item.id)"
              :class="ftypeId == item.id ? 'onTypeTxt' : 'onTypeTxt2'"
              style="position: relative"
            >
              <span>{{ item.name }}</span>
              <!-- <div
                class="line"
                :style="{ display: ftypeId == item.id ? 'block' : 'none' }"
              ></div> -->
            </div>
            <!-- 子分类 -->
            <div class="typeCss" v-if="VeidooJson[item.id].length">
              <div
                v-for="(item1, index1) in VeidooJson[item.id]"
                v-if="item1.pid == ftypeId"
                :key="index + '-' + index1"
                :label="item1.id"
              >
                <div
                  class="cName"
                  @click="clickStypeId(item1.id)"
                  :class="stypeId == item1.id ? 'twoTypeTxt' : 'twoTypeTxt2'"
                >
                  {{ item1.name }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style="display: flex;">
          <div class="wordBtn" @click="addRecord">添加记录</div>
          <div class="wordBtn" @click="judgeExport">导出Excel</div>
        </div>
      </div>

      <div class="selectSty">
        <div style="margin-right: 10px">学期</div>
        <el-select v-model="termId" placeholder="请选择" @change="getData">
          <el-option label="所有学期" value=""></el-option>
          <el-option
            v-for="item in termList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        v-loading="isLoading"
        header-align="center"
        :header-cell-style="{
          background: '#E0EAFB',
          color: 'rgba(0, 0, 0, 0.90)'
        }"
        @selection-change="handleSelectionChange"
      >
        <!-- @select="gouRecord" -->
        <!-- @select-all="selectAllRecord" -->
        <el-table-column
          type="selection"
          align="center"
          label="全选"
          width="55"
        >
        </el-table-column>
        <el-table-column
          prop="create_at"
          label="创建时间"
          align="center"
          width="150"
        >
          <!-- <template slot-scope="scope">{{ scope.row.date }}</template> -->
        </el-table-column>
        <el-table-column
          prop="recordTit"
          label="观察内容"
          align="center"
          width="170"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="place"
          label="观察地点"
          align="center"
          width="120"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="tname"
          label="维度"
          align="center"
          width="260"
          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="185px">
          <template slot-scope="scope">
            <div class="evaluate">
              <div
                class="TableBtn"
                style="color: #3681fc"
                @click="updateCred(scope.row, 0)"
              >
                查看
              </div>
              <div
                class="TableBtn"
                style="color: #3681fc"
                @click="updateCred(scope.row, 1)"
              >
                修改
              </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="10"
        layout="prev, pager, next"
        :total="total"
        class="pagination"
      >
      </el-pagination>
    </div>
    <!-- <div v-if="isPop" @click="closePop" class="shade"></div> -->

    <!-- v-if="isPop" -->

    <el-dialog
      :title="judgeNum == 1 ? '修改' : judgeNum == 2 ? '添加' : '查看'"
      :visible.sync="isPop"
      :append-to-body="true"
      width="700px"
      :destroy-on-close="true"
      :close-on-click-modal="true"
      :before-close="closePop"
      class="dialog_diy"
    >
      <popbox
        ref="refPop"
        :judgeNum="judgeNum"
        :recordDataCopy="recordData"
        :sUserId="userid"
        :termList="termList"
        :weiList="weiList"
        :studentList="studentListCopy"
        @closePop="closePop"
        @getData="getData"
        @updatePanelB="updatePanelB"
      ></popbox>
    </el-dialog>

    <!-- <el-dialog
      title="添加"
      :visible.sync="AddIsPop"
      :append-to-body="true"
      width="700px"
      :destroy-on-close="true"
      :close-on-click-modal="true"
      :before-close="closePop"
      class="dialog_diy"
    >
    添加新纪录
     
    </el-dialog> -->
  </div>
</template>

<script>
import popbox from "./component/popbox";
export default {
  components: {
    popbox
  },
  props: {
    userid: {
      type: String
    },
    oid: {
      type: String
    },
    org: {
      type: String
    },
    cid: {
      type: String
    }
  },
  data() {
    return {
      // 筛选数据
      VeidooList: [],
      VeidooJson: {},
      VeidooListChild: [],
      isLoading: true,
      classid: "",

      // 当前时间
      visitTime: "",
      // 学生详情信息
      info: {},
      // 默认选择项
      // VeidooValue:{},
      // 默认选择项
      termValue: "",
      // 学期数据
      termList: [],

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

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

      tableData: [],
      multipleSelection: [],

      // 组件信息数据
      isPop: false,
      // 添加记录弹窗
      AddIsPop: false,
      // 查看，修改弹窗数据
      recordData: {},
      // recordDataCopy: {},
      // 维度数据
      weiList: [],
      // 班级学生数据（包括多个班）
      studentList: [],
      studentListCopy: [],

      // 判断显示查看，修改
      judgeNum: 0,

      ftypeId: "",
      stypeId: ""
    };
  },
  // watch: {
  //   total(newVal, oldVal) {
  //     this.$emit("updatePanelA", newVal);
  //   }
  // },
  methods: {
    // 大分类点击
    clickFtypeId(e) {
      this.ftypeId = e;
      this.stypeId = "";
      this.page = 1;
      this.total = 0;
      this.getData();
    },
    clickStypeId(e) {
      // console.log("点击小分类", e);
      if (this.stypeId === e) {
        this.stypeId = "";
      } else {
        this.stypeId = e;
      }
      this.getData();
    },
    closePop() {
      this.isPop = false;
      this.AddIsPop = false;
    },

    // 切换页
    handleCurrentChange(val) {
      //当页数发生改变的时候调用获取列表数据请求
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.getData();
    },
    //获取分类
    getVeidooType() {
      let params = {
        org: this.org,
        oid: this.oid
      };
      this.ajax
        .get(this.$store.state.api + "selectSTEType", params)
        .then(res => {
          var ftype = res.data[0]; //公共父级分类
          var stype = res.data[1]; //公共子级分类
          var sctype = res.data[2]; //该学校子级分类
          var fctype = res.data[3]; //该学校父级分类
          var fotype = res.data[4]; //组织父级分类
          var sotype = res.data[5]; //组织子级分类
          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]]);
            }
          }
          this.ftypeId = "";
          this.sftypeId = "";
          this.page = 1;
          var VeidooJson = {};
          for (var i = 0; i < allfType.length; i++) {
            if (!VeidooJson[allfType[i].id]) {
              VeidooJson[allfType[i].id] = [];
            }
            for (var j = 0; j < allsType.length; j++) {
              if (allfType[i].id == allsType[j].pid) {
                VeidooJson[allfType[i].id].push(allsType[j]); // 去除公共分类
              }
            }
          }

          this.VeidooList = allfType;
          this.VeidooJson = VeidooJson;
          this.$forceUpdate();
          this.getData();

          // console.log("小分类", this.VeidooJson, "大分类", this.VeidooList);
        })
        .catch(err => {
          this.isLoading = false;
          console.error(err);
        });
    },
    // 获取数据
    getData() {
      this.isLoading = true;

      let params = {
        uid: this.userid,
        cid: this.cid,
        cu: this.ftypeId,
        cn: this.stypeId,
        cm: this.termId,
        page: this.page
      };
      // console.log(params);
      this.ajax
        .get(this.$store.state.api + "selectVeidooType", params)
        .then(res => {
          this.isLoading = false;
          this.tableData = res.data[0];
          console.log("this.tableData", this.tableData);
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          // console.log(" 获取筛选数据", res.data[0]);
        })
        .catch(err => {
          this.isLoading = false;
          console.error(err);
        });
    },
    // 选择导出哪些记录
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(this.multipleSelection);
    },
    // gouRecord(val){
    //   this.multipleSelection = val;
    //   console.log(this.multipleSelection);
    // },
    // selectAllRecord(val) {
    //   this.multipleSelection = val;
    //   console.log(this.multipleSelection);
    // },
    // 获取学生详情，为了添加记录用
    // getStuDetail(){
    //   let params = {
    //     uid: this.userid
    //   };
    //   this.ajax
    //     .get(this.$store.state.api + "selectSDetail", params)
    //     .then(res => {
    //       this.info = res.data[0][0];
    //       console.log("this.info ", this.info);
    //       // 用于存储归类后的数据的对象
    //     })
    //     .catch(err => {
    //       console.error(err);
    //     });
    // },
    // 添加新纪录
    addRecord() {
      this.getPresentDate();
      this.judgeNum = 2;
      this.recordData = {
        classId: this.info.classid,
        className: this.info.cname,
        contact: [],
        place: "",
        recordContent: "",
        recordDate: this.visitTime,
        recordImg: [],
        recordTit: "",
        semName: "",
        studentName: this.info.username,
        term: this.termValue,
        tname: "",
        type: ""
      };
      this.studentListCopy = [];
      // 去除自己的名字。不能自己关联自己
      this.studentListCopy = this.studentList.filter(i => {
        return i.id !== this.info.userid;
      });
     
      // this.AddIsPop = true;
      this.isPop = true;
    },
    // 获取当前时间
    getPresentDate() {
      const currentTime = new Date();
      const year = currentTime.getFullYear();
      let month = currentTime.getMonth() + 1; // 月份从0开始，因此需要加1
      month = (month < 10 ? "0" : "") + month;
      let day = currentTime.getDate();
      day = (day < 10 ? "0" : "") + day;

      let hours = currentTime.getHours();
      hours = (hours < 10 ? "0" : "") + hours;

      let minutes = currentTime.getMinutes();
      minutes = (minutes < 10 ? "0" : "") + minutes;

      // console.log(year, month, day, hours, minutes);
      this.visitTime = `${year}-${month}-${day} ${hours}:${minutes}`;
      // console.log(this.visitTime)
    },
    // 修改与查看记录
    updateCred(e, t) {
      // console.log("eeeeeeeeeeee", e);
      this.judgeNum = t;
      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.studentListCopy = [];
      this.recordData = e;
      // 去除自己的名字。不能自己关联自己
      this.studentListCopy = this.studentList.filter(i => {
        return i.id !== e.sid;
      });
      // this.studentList = res[0].filter(i => {
      //   return i.id !== allData.sid;
      // });
      // console.log("recordData", this.recordData);
      this.$forceUpdate();
      this.isPop = true;
    },
    // 获取纬度列表
    getWeiList() {
      // 获取纬度筛选框
      const data = {
        oid: this.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);
      });
    },
    // 获取学生详情，主要获取他的班级id,然后查询他的关联列表同学
    getStudentDetail() {
      const data2 = {
        uid: this.userid
      };
      // console.log("获取班学生列表", data2);
      this.ajax
        .get(this.$store.state.api + "selectStudentDetail", data2)
        .then(res => {
          // console.log('学生详情',res.data[0][0]);
          this.info = res.data[0][0];
          this.classid = res.data[0][0].classid;
          this.getClassStudent();

          // console.log("this.studentList", res);
        });
    },
    // 获取班学生列表
    getClassStudent() {
      const data2 = {
        cid: this.classid,
        uid: this.userid
      };
      // console.log("获取班学生列表", data2);
      this.ajax
        .get(this.$store.state.api + "selectManyClassStudent", data2)
        .then(res => {
          // console.log(res);
          this.studentList = res.data[0];
          // console.log("this.studentList", res);
        });
    },
    getYear() {
      this.isLoading = true;
      this.ajax
        .get(this.$store.state.api + "selectTerm")
        .then(res => {
          this.isLoading = false;
          var yearJuri = res.data[0];
          for (var i = 0; i < yearJuri.length; i++) {
            if (yearJuri[i].defaultC == 1) {
              this.year = yearJuri[i].id;
            }
          }
          this.termList = yearJuri;
          this.termList.forEach(i => {
            if (i.defaultC === 1) {
              this.termValue = i.id;
            }
          });
          // console.log('termList',this.termList);
        })
        .catch(err => {
          this.isLoading = false;
          console.error(err);
        });
    },
    // 判断导出数据
    judgeExport() {
      // return console.log('导出数据',this.multipleSelection);

      if (this.multipleSelection.length) {
        this.$confirm("是否导出Excel?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        })
          .then(() => {
            this.exportExcel();
          })
          .catch(() => {});
      } else {
        this.$message({ message: "请先选择要导出的数据", type: "warning" });
        return;
      }
    },

    exportExcel() {
      // var res = res.data[0];
      var res = this.multipleSelection;
      // console.log("this.termList", this.termList);
      let termName = "";
      this.termList.forEach(e => {
        if (e.id == this.termId) {
          termName = e.name;
        }
      });

      // console.log('导出数据',res);
      //如果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].studentName;
        _json["班级"] = res[i].className;
        _json["记录时间"] = res[i].recordDate;
        _json["学期"] = res[i].semName;
        _json["关联"] = res[i].constus;
        _json["维度"] = res[i].tname;
        _json["观察地点"] = res[i].place;
        _json["观察内容"] = res[i].recordTit;
        _json["内容"] = res[i].recordContent;
        // _json["创建时间"] = res[i].create_at;

        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: 20 },
        { wch: 30 },
        { wch: 30 },
        { wch: 30 },
        { wch: 30 },
        { wch: 30 },
        { wch: 30 },
        { wch: 30 },
        { wch: 30 }
      ];
      if (!termName) {
        termName = "所有学期";
      }
      XLSX.utils.book_append_sheet(workbook, ws, "sheet1"); //把sheet添加到workbook里，第三个参数是sheet名
      XLSX.writeFile(workbook, this.info.name + termName + "观察记录.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"
      });
    },
    updatePanelB(e) {
      // console.log('出嘎',e);
      this.$emit("updatePanelA", e);
    },
    // 删除记录
    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.getData();
              this.$emit("updatePanelA", e);

              this.$message({
                type: "success",
                message: "已删除"
              });
              // this.isLoading = false; updateRecord
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
      // return console.log(e);
    }
  },
  created() {
    this.getWeiList();
    this.getStudentDetail();

    // 获取学生详情，为了添加记录用
    // this.getStuDetail()
    this.getYear();
    this.getVeidooType();
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.selectData();
    // });
  }
};
</script>

<style scoped>
.dialog_diy {
  box-sizing: border-box;
  /* padding: 0 10px 10px 10px; */
}
.dialog_diy >>> .el-dialog {
  /* height: 100%; */
  margin: 10vh auto !important;
}

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

.dialog_diy >>> .el-dialog__body {
  height: calc(100% - 124px);
  box-sizing: border-box;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: space-between;
  /* padding: 0px; */
}

.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;
}

.dialog_diy >>> .el-dialog__body,
.dialog_diy >>> .el-dialog__footer {
  background: #fafafa;
}

.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%;
}
.diary > .diary-content {
  background-color: #fff;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  overflow: auto;
}
.top {
  width: 100%;
  display: flex;
  position: relative;
  justify-content: space-between;
  align-items: flex-end;
}
.oneType {
  position: relative;
  display: flex;
  justify-content: flex-start;
  /* flex-direction: column; */
}
.typeCss {
  position: absolute;
  top: 120%;
  left: 0;
  display: flex;
}

.onTypeTxt,
.onTypeTxt2 {
  cursor: pointer;
  display: flex;
  font-size: 16px;
  position: relative;
  align-items: center;
  justify-content: center;
  margin-right: 30px;
  color: rgba(0, 0, 0, 0.9);
}

.onTypeTxt {
  padding-bottom: 10px;
  border-bottom: 3px solid #3681fc;
  color: rgba(54, 129, 252, 1);
}
.line {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
  bottom: 0;
  height: 3px;
  /* background-color: #3681fc; */
  width: 70%;
}
.wordBtn {
  cursor: pointer;
  background-color: #3681fc;
  color: #fff;
  width: 100px;
  height: 34px;
  border-radius: 3px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 15px;
}
.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: 10px 10px 30px 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 {
  padding: 30px 0;
  float: right;
}
</style>
