<!--  -->
<template>
  <div class=''>
    <el-breadcrumb class="divi2" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/alg-train'}">算法训练</el-breadcrumb-item>
      <el-breadcrumb-item>查看训练任务</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider class="divi"></el-divider>
    

    <el-tabs v-model="activeName" @tab-click="handleClick">

      <el-tab-pane label="日志" name="first">

        <div class="codemirrorContainer"
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)">


          <codemirror
            ref="cm"
            v-model="output"
            :options="cmOptions"
          ></codemirror>
        
        </div>
        


      </el-tab-pane>

      <el-tab-pane label="算法监控" name="second">
        <iframe class="iframe" v-bind:src="url" scrolling="no" frameborder="0">

        </iframe>
        
        <!-- <img class="iframe" src="./tensorboard.png"> -->
        
      </el-tab-pane>

      <el-tab-pane label="算法代码" name="third">
        <el-table :data="pythonFiles" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
          style="width: 100%;">
          <el-table-column type="selection" header-align="center" align="center" width="50">
          </el-table-column>
          <el-table-column prop="filename" header-align="center" align="center" label="文件名称">
          </el-table-column>
          
          <el-table-column prop="filesize" header-align="center" align="center" label="文件大小">
          </el-table-column>

          <el-table-column prop="lastModifiedTime" header-align="center" align="center" label="修改时间">
          </el-table-column>
          
          <el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
            <template slot-scope="scope">
              <el-button v-if="isAuth('version:edit')" type="text" size="small" 
                @click="watchFile(scope.row.filename)">查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="pythonFilesTotalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </el-tab-pane>


      <el-tab-pane label="数据集" name="forth">
        <el-table :data="datasetFiles" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
          style="width: 100%;">
          <el-table-column type="selection" header-align="center" align="center" width="50">
          </el-table-column>
          <el-table-column prop="filename" header-align="center" align="center" label="文件名称">
          </el-table-column>
          
          <el-table-column prop="filesize" header-align="center" align="center" label="文件大小">
          </el-table-column>

          <el-table-column prop="lastModifiedTime" header-align="center" align="center" label="修改时间">
          </el-table-column>
          
          <el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
            <template slot-scope="scope">
              <el-button v-if="isAuth('version:edit')" type="text" size="small" 
                @click="downloadDataset(scope.row.filename)">下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="datasetFilesTotalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    <TrainFileWatch v-if="trainFileWatchVisible" ref="trainFileWatch"></TrainFileWatch>
  </div>
</template>

<script>
  import TrainFileWatch from "./train-file-watch.vue";

  // 全局引入vue-codemirror
  import {codemirror} from 'vue-codemirror';
  // 引入css文件
  import 'codemirror/lib/codemirror.css'
  // 引入主题 可以从 codemirror/theme/ 下引入多个
  import 'codemirror/theme/idea.css'
  import 'codemirror/theme/nord.css'
  // 引入语言模式 可以从 codemirror/mode/ 下引入多个
  import 'codemirror/mode/sql/sql.js';
  import 'codemirror/mode/python/python.js'
  import 'codemirror/mode/javascript/javascript.js'
  import { Message } from "element-ui"



  // 高亮行功能
  import 'codemirror/addon/selection/active-line'
  import 'codemirror/addon/selection/selection-pointer'

  // 调整scrollbar样式功能
  import 'codemirror/addon/scroll/simplescrollbars.css'
  import 'codemirror/addon/scroll/simplescrollbars'

  // 自动括号匹配功能
  import 'codemirror/addon/edit/matchbrackets'
  import 'codemirror/addon/edit/closebrackets'

  // 全屏功能 由于项目复杂，自带的全屏功能一般不好使
  import 'codemirror/addon/display/fullscreen.css'
  import 'codemirror/addon/display/fullscreen'

  // 显示自动刷新
  import 'codemirror/addon/display/autorefresh'

  // 多语言支持？
  import 'codemirror/addon/mode/overlay'
  import 'codemirror/addon/mode/multiplex'


  // 代码段折叠功能
  import 'codemirror/addon/fold/foldcode'
  import 'codemirror/addon/fold/foldgutter'
  import 'codemirror/addon/fold/foldgutter.css'

  import 'codemirror/addon/fold/brace-fold.js'
  import 'codemirror/addon/fold/comment-fold.js'
  import 'codemirror/addon/fold/xml-fold.js';
  import 'codemirror/addon/fold/indent-fold.js';
  import 'codemirror/addon/fold/markdown-fold.js';
  import 'codemirror/addon/fold/comment-fold.js';

  // merge功能
  import 'codemirror/addon/merge/merge.css'
  import 'codemirror/addon/merge/merge'
  // google DiffMatchPatch
  import DiffMatchPatch from 'diff-match-patch'
  // DiffMatchPatch config with global
  window.diff_match_patch = DiffMatchPatch;
  window.DIFF_DELETE = -1;
  window.DIFF_INSERT = 1;
  window.DIFF_EQUAL = 0;

export default {
  name:'Simple',
  components:{
    codemirror,
    TrainFileWatch
  },
  data() {
    return {
      trainFileWatchVisible:false,
      dataList: [],
      pythonFiles:[],
      datasetFiles:[],
      pageIndex: 1,
      pageSize: 10,
      pythonFilesTotalPage: 0,
      datasetFilesTotalPage: 0,

      algorithmNameToVersion: null,
      verisionToFile:null,
      loading:true,
      timer:null,
      activeName: "first",
      algorithmTrainingId:null,
      missStatus:null,
      output:"",
      url:"",
      cmOptions: {
          // 语言及语法模式
          //mode: 'text/x-python',
          // 主题
          theme: 'nord',
          readOnly:'nocursor',
          // 显示行数
          line: true,
          //lineNumbers: true,
          // 软换行
          lineWrapping: true,
          // tab宽度
          tabSize: 4,
          autoCloseBrackets: true, // 自动闭合符号
          styleActiveLine: true, // 显示选中行的样式
          lint: true,
          // 高亮行功能
          styleActiveLine: true,
          // 调整scrollbar样式功能
          scrollbarStyle: 'overlay',
          // 自动括号匹配功能
          matchBrackets: true
        }
    };
  },
  activated() {
    let algorithmTrainingId=this.$route.query.algorithmTrainingId;
    let missStatus=this.$route.query.missStatus;
    this.init(algorithmTrainingId,missStatus);
    //如果状态不是待开始或者暂停中，就去轮询访问日志
    if(missStatus!=1&&missStatus!=7){
      this.timer=window.setInterval(()=>{
      setTimeout(()=>{
        console.log("执行定时任务");
        this.getOutput();
      },0)
    },1000);
    }
    
  }, 
  methods: {
      init(id,missStatus){
          this.loading=true;
          this.activeName="first";
          this.algorithmTrainingId=id;
          this.missStatus=missStatus;
          this.output="";
          this.pythonFiles=[];
          this.datasetFiles=[];
          if(missStatus!=1)
            this.getOutput();
          else{
            this.output="该训练任务未运行";
            this.loading=false;
          };
        //根据algorithmTrainingId获得algId及versionId
        this.$http({
          url:this.$http.adornUrl('/algstrain/getAlgIdVersionId'),
          method:'get',
          params:this.$http.adornParams({
            algorithmTrainingId:this.algorithmTrainingId
          }),
        }).then(({data})=>{
          this.algorithmNameToVersion=data.algorithmNameToVersion;
          this.verisionToFile=data.verisionToFile;
          this.getDataList();
        });
        //this.getDataList();
    },
    
    redirectHandle() {
      this.$router.replace({ path: "/alg-algs" });
    },
    getOutput(){
      this.$http({
          url:this.$http.adornUrl('/algstrain/getOutput'),
          method:'get',
          params:this.$http.adornParams({
            algorithmTrainingId:this.algorithmTrainingId
          }),
        }).then(({data})=>{
          this.$nextTick(()=>{
              this.output=data.output;
              this.loading=false;
            });
        });
    },
    
    handleClick(tab, event) {
        console.log(tab, event);
        if(tab.name == 'second'){
        	console.log("切换到算法监控")
          this.$http({
            url: this.$http.adornUrl("/algstrain/info/" + this.algorithmTrainingId),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.url=data.algTrain.ipAddress;

            }
          });
        }
    },

    // 获取代码文件列表
    getDataList() {
        this.dataListLoading = true;
        this.$http({
          url: this.$http.adornUrl("/algstrain/listFiles/"),
          method: "get",
          params: this.$http.adornParams({
            page: this.pageIndex,
            limit: this.pageSize,
            algorithmNameToVersion:this.algorithmNameToVersion,
            verisionToFile:this.verisionToFile
          }),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.pythonFiles = data.pythonFiles;
            this.datasetFiles = data.datasetFiles;
            this.pythonFilesTotalPage = data.pythonFiles.length;
          } else {
            this.pythonFiles = [];
            this.datasetFiles = [];
            this.pythonFilesTotalPage = 0;
            this.datasetFilesTotalPage = 0;
          }
          this.dataListLoading = false;
        });
    },

    //查看代码文件
    watchFile(fileName){
      this.trainFileWatchVisible=true;
      this.$nextTick(() => {
        this.$refs.trainFileWatch.init(this.algorithmNameToVersion,this.verisionToFile,fileName);
      });
    },
    //下载数据集
    downloadDataset(filename){
      this.$http({
          url:this.$http.adornUrl('/dataset/downloadDataset'),
          method:'get',
          params:this.$http.adornParams({
            datasetName:filename
          }),
        }).then(({data})=>{
          if(data&&data.code===0){
              window.location.href=data.downloadUrl;
          }else{
              Message.error('下载失败');
          }
        });
    },
    
  },
  
  mounted(){
    
    this.$refs.cm.codemirror.setSize("auto", (document.documentElement.clientHeight - 200) + "px");
    this.$nextTick(() => {
    window.addEventListener('resize', () => {
        //监听浏览器窗口大小改变
        //浏览器变化执行动作
        this.$refs.cm.codemirror.setSize("auto", (document.documentElement.clientHeight - 200) + "px")
      });
    });
    
    
  },
  //切换路由时，清楚定时器
  beforeRouteLeave(to, from, next){
    next();
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },

};
</script>
<style scoped>
.divi {
  display: block;
  height: 1px;
  width: 100%;
  margin: 24px 0;
  background-color: #dcdfe6;
  position: relative;
}
.divi2 {
  display: block;
  height: 1px;
  width: 100%;
  position: relative;
}
.sele {
  border: 1px solid #409eff;
  border-radius: 5px;
  box-sizing: border-box;
  padding: 5px 0px;
  margin: 10px;
}
.iframe{
  width: 64%;
  height: 618px;
  margin-left: 18%;
}


</style>
