<template>
  <div>
    <div class="flex header" :class="{hh: $config.isHh}">
      <img v-if="$config.isHh" src="../assets/img/logo-hh.png" alt="" class="logo">
      <p v-else>{{$config.title}}</p>
      <div class="bt">
        <el-button type="primary" @click="back()">退出实验</el-button>
      </div>
    </div>

    <div class="flex center">
      <p v-if="$config.isHh" style="font-size: 18px">{{$config.title}}</p>
      <p>编程语言</p>
      <el-input placeholder="请输入内容" v-model="value" :disabled="true"></el-input>
    </div>

    <div class="tab">
      <el-tabs v-model="workbench1" type="card">
        <el-tab-pane
          v-for="item in workbench"
          :key="item.judgmentPointsId"
          :label="item.judgmentPointsName"
          :value="item.judgmentPointsId"
        >
          <codemirror
            :key="codeKey"
            :projectId.sync="projectId"
            :code.sync="item.code.code"
            :workbench1="item.judgmentPointsId"
            :codeid.sync="item.code.codeId"
          ></codemirror>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div class="menu">
      <testPanel
        @tell="getQueryIndex"
        @recoveryCode="recoveryCode"
        ref="mainindex"
        :autoStart="autoStart"
        :sendSync="sendSync"
        :defaultVal="defaultVal"
        @getDataFromChild="getDataFromChild"
        :codeId="codeId"
        :workbench.sync="workbench"
        :key="codeId"
      ></testPanel>
    </div>
  </div>
</template>

<script>
import testPanel from "../components/TestPanel";
import codemirror from "../components/codemirror";
import { log } from "util";
//返回格式化时间，传参例如："yyyy-MM-dd hh:mm:ss"
function formatDate(fmt,date) {
  var date = date ? date : new Date()
  var o = { 
    "M+" : date.getMonth()+1,                 //月份 
    "d+" : date.getDate(),                    //日 
    "h+" : date.getHours(),                   //小时 
    "m+" : date.getMinutes(),                 //分 
    "s+" : date.getSeconds(),                 //秒 
    "q+" : Math.floor((date.getMonth()+3)/3), //季度 
    "S"  : date.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) {
          fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  }
  for(var k in o) {
      if(new RegExp("("+ k +")").test(fmt)){
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
      }
  }
  return fmt; 
}
export default {
  data() {
    return {
      // 编译器
      isShow: false,
      projectPermissions: 0, //项目权限(0、练习 1、考核 2、竞赛)
      ops: {
        vuescroll: {},
        scrollPanel: {},
        rail: {
          keepShow: true
        },
        bar: {
          hoverStyle: true,
          onlyShowBarOnScroll: false, //是否只有滚动的时候才显示滚动条
          background: "red", //滚动条颜色
          opacity: 0.5, //滚动条透明度
          "overflow-x": "hidden"
        }
      },
      judgmentPointsId: "",
      codeId: 0,
      value: "Python",
      workbench1: "", //选中后绑定的对象
      workbench: [],
      editableTabs: [],
      tabIndex: 2,
      name: "",
      judgmentPointsIds: [],
      autoStart: true,
      sendSync: true,
      entryTime: formatDate('yyyy-MM-dd hh:mm:ss'),
      assessmentId: '',
      defaultVal: sessionStorage.getItem("timer")
        ? parseInt(sessionStorage.getItem("timer"))
        : 0,
      codeKey: 1,
    };
  },
  components: {
    codemirror,
    testPanel
  },
  beforeDestroy(){
    let data = {
      studentId: this.studentId,
      startTime: this.entryTime,
      endTime: formatDate('yyyy-MM-dd hh:mm:ss'),
      projectId: this.projectId
    }
    this.$post(this.api.saveEvaluation,data).then(res => {})
    this.leavePage()
  },
  mounted() {
    this.autoLogout()
    this.assessmentId = this.getCookie("assessmentId");
    if (window.history && window.history.pushState) {
      // 向历史记录中插入了当前页
      history.pushState(null, null, document.URL);
      window.addEventListener("popstate", this.goBack, false);
    }
  },
  destroyed() {
    window.removeEventListener("popstate", this.goBack, false);
  },
  methods: {
    leavePage(){
      if(!this.$refs.mainindex.isSubmit && !this.assessmentId && this.workbench.length){
        let workbench = this.workbench
        if(workbench.some(n => n.code.code)){
          let codeCache = {
            systemId: this.$config.systemId,
            projectId: this.projectId,
            workbench1: this.workbench1,
            workbench
          }
          localStorage.setItem('codeCache',JSON.stringify(codeCache))
        }
      }
    },
    autoLogout(){
      let lastTime = new Date().getTime()
      let logout = false
      document.onmousedown = () => {
        lastTime = new Date().getTime()
      }
      setInterval(() => {
        if((new Date().getTime() - lastTime) > this.$config.autoLogoutTime){
            logout || this.$message.error('用户登录过期，请重新登录')
            logout = true
            setTimeout(this.back,1500)
        }
      },1000)
    },
    goBack() {
      this.leavePage()
      history.back()
    },
    getDataFromChild(data) {
      sessionStorage.setItem("timer", parseInt(data));
    },
    recoveryCode(workbench){
      this.workbench = workbench
      this.codeKey++
      this.workbench1 = '0'
    },
    reload(){
      this.$refs.mainindex.reload()
    },
    back() {
      this.leavePage()
      if(this.projectPermissions){
        // 返回到考核列表
        if (this.$config.isBeta) { // 判断是否是职站测试服
          location.href = `http://120.78.198.231/#/ass/list`
        }
        location.href = `${this.$config.host}#/dashboard#2`
      }else{
        // 返回到实验台
        if (this.$config.isBeta) {
          location.href = `http://120.78.198.231/#/station/list`
        }
        location.href = `${this.$config.host}#/dashboard#1`
      }
      this.$refs.mainindex.getClearTime();
    },
    //工作台展示
    getQueryIndex(value1, projectPermissions,workBench) {
      //父子组件传值
      this.projectId = value1;
      this.projectPermissions = projectPermissions;
      this.studentId = this.getCookie("studentId");
      this.$get(this.api.ProjectId, {
        projectId: this.projectId,
        studentId: this.studentId
        // studentId: 54
      })
        .then(res => {
          if(workBench.length){
            this.workbench = workBench
          }else{
            this.workbench = res.message;
            this.workbench.map(item => {
              if (item.code.codeId == 0) {
                item.code.codeId = "";
              }
              if (this.projectPermissions == "0") {
                item.code.codeId = "";
                item.code.code = "";
              }
            });
          }
          this.assessmentId && (this.codeId = this.workbench[0].code.codeId)
        })
        .catch(err => {
          console.log(err);
        });
    },

    getCookie(cookie_name) {
      //获取cookie中指定key的value
      var allcookies = document.cookie; //索引长度，开始索引的位置
      var cookie_pos = allcookies.indexOf(cookie_name); // 如果找到了索引，就代表cookie存在,否则不存在

      if (cookie_pos != -1) {
        // 把cookie_pos放在值的开始，只要给值加1即可
        //计算取cookie值得开始索引，加的1为“=”
        cookie_pos = cookie_pos + cookie_name.length + 1; //计算取cookie值得结束索引
        var cookie_end = allcookies.indexOf(";", cookie_pos);

        if (cookie_end == -1) {
          cookie_end = allcookies.length;
        } //得到想要的cookie的值
        var value = unescape(allcookies.substring(cookie_pos, cookie_end));
      }
      return value;
    }
  }
};
</script>

<style lang="scss" scoped>
.menu {
  position: relative;
  z-index: 1000;
}
.code-right {
  /* height: 800px; */
  width: 230px;
  background: #1b1b1b;
  display: inline-block;
}
//创建工作台
::v-deep .el-form-item {
  margin-bottom: 0px;
}
::v-deep .el-dialog--center {
  width: 400px;
}
::v-deep .el-dialog__headerbtn .el-icon-close:before {
  padding: 3px;
  background-color: #fdca17;
  border-radius: 50%;
  color: #ffffff;
}
.select1 ::v-deep .el-input__icon {
  line-height: 40px;
}
.select1 {
  margin: 0;
}

//tabs
.tab ::v-deep .el-tabs__header {
  margin-bottom: 0;
}
.tab ::v-deep .el-tabs__item.is-active {
  color: #333;
  background-color: #fdca17;
}
.tab ::v-deep .el-icon-circle-plus-outline:before {
  font-size: 16px;
}

.tab {
  height: 50px;
  line-height: 50px;
}
// tabs边框样式
::v-deep .el-tabs--card > .el-tabs__header {
  border-bottom: none;
}
::v-deep .el-tabs--card > .el-tabs__header .el-tabs__nav {
  border: none;
}
::v-deep .el-tabs--card > .el-tabs__header .el-tabs__item {
  border-left: none;
  border-bottom: none;
}
// 编程语言

.center p {
  font-size: 16px;
  margin-left: 15px;
  margin-right: 15px;
}
.center {
  height: 60px;
  line-height: 60px;
}
.center ::v-deep .el-input {
  width: 10%;
}
.center ::v-deep .el-input.is-disabled .el-input__inner {
  // border-color: #fdca17;
  border-radius: 30px;
}
//头部
.bt ::v-deep .el-button + .el-button {
  margin-left: 0;
}
.bt ::v-deep .el-button--primary,
.el-button--primary:focus,
.el-button--primary:hover,
.el-button--primary:active {
  color: #202020;
  border: none;
  background-color: #fdca17;
}
.bt ::v-deep .el-button {
  border-radius: 0;
  border: none;
}

.header p {
  font-size: 16px;
  font-weight: 700;
  color: rgba(51, 51, 51, 1);
  margin-left: 18px;
}
.header {
  background-color: #f8f8f8;
  justify-content: space-between;
  height: 40px;
  line-height: 40px;
  &.hh{
    padding: 10px 0;
    line-height: normal;
  }
  .logo{
    width: 200px;
    margin-left: 10px;
  }
}
//公共类
p {
  margin: 0;
}
.flex {
  display: flex;
}
// 滚动条的宽度
::v-deep ::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 6px; // 纵向滚动条 必写
}
// 滚动条的滑块
::v-deep ::-webkit-scrollbar-thumb {
  background-color: #fdca17;
  border-radius: 3px;
  -webkit-box-shadow: inset 0 0 5px #dddddd;
}
::v-deep ::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px #dddddd;
  border-radius: 0;
  background: #dddddd;
}
//改变placeholder的样式
::v-deep input::-webkit-input-placeholder {
  color: #333;
}
::v-deep input::-moz-input-placeholder {
  color: #333;
}
::v-deep input::-ms-input-placeholder {
  color: #333;
}
//下拉框的icon
::v-deep .el-input__icon {
  line-height: 60px;
}
//下拉框
::v-deep .el-select__caret:before {
  content: "\e78f";
  font-size: 16px;
  padding: 3px;
  background-color: #fdca17;
  border-radius: 50%;
  color: #ffffff;
}
::v-deep .el-input--suffix .el-input__inner {
  color: #333;
  font-size: 14px;
  border-radius: 30px;
  border: none;
  background-color: #f5f5f5;
  margin-left: 10px;
}
</style>