<!--  -->
<template>
  <div class='' v-loading="loading" element-loading-text="正在处理">
    <el-breadcrumb class="divi2" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>算法任务</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider class="divi"></el-divider>

    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-button v-if="isAuth('train:save')" type="primary" @click="addHandle()">新建任务</el-button>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.missName" placeholder="请输入任务名称" clearable
          @keyup.enter.native="pageIndex = 1;getDataList()"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="pageIndex = 1;getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-tag>筛选:</el-tag>
        <el-select v-model="classificationtag" clearable placeholder="类别" size="mini" style="width: 130px;"
          @change="pageIndex = 1;getDataList2()">
          <el-option v-for="data in classification" :key="data" :label="data" :value="data">
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item>
<!--        <el-button @click="algorithmTrainCompare()">任务对比</el-button>-->
      </el-form-item>


    </el-form>

    <el-table :data="dataList" 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="algorithmTrainingId" header-align="center" align="center" width="80" label="任务ID">
      </el-table-column> -->
      <el-table-column label="序号" header-align="center" align="center" width="80" type="index" :index='(index)=>{return (index+1) + (this.pageIndex-1)*this.pageSize}'> </el-table-column>

      <el-table-column prop="missName" header-align="center" align="center" label="任务名称"></el-table-column>
      <el-table-column prop="algFrameId" header-align="center" align="center" label="算法类别">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.algFrameId === -1" size="small">抗干扰算法</el-tag>
          <el-tag v-else size="small">干扰算法</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column prop="categoryName" header-align="center" align="center" label="分类"></el-table-column>-->
      <el-table-column prop="username" header-align="center" align="center" label="创建人"></el-table-column>
      <el-table-column prop="missStatus" header-align="center" align="center" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.missStatus === 0" size="small" type="danger">停止</el-tag>
          <el-tag v-else-if="scope.row.missStatus === 1" size="small">待开始</el-tag>
          <el-tag v-else-if="scope.row.missStatus === 2" size="small" type="success">运行中</el-tag>
          <el-tag v-else-if="scope.row.missStatus === 4" size="small" type="success">已发布</el-tag>
          <el-tag v-else-if="scope.row.missStatus === 5" size="small">已申请发布</el-tag>
          <el-tag v-else-if="scope.row.missStatus === 6" size="small" type="danger">申请被驳回</el-tag>
          <el-tag v-else-if="scope.row.missStatus === 7" size="small">暂停中</el-tag>
          <el-tag v-else size="small" type="success">已结束</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="missCreationTime" header-align="center" align="center" width="180" label="开始时间"
        :formatter="missCreationTimeFormat">
      </el-table-column>
      <el-table-column prop="missStopTime" header-align="center" align="center" width="180" label="停止时间"
        :formatter="missStopTimeFormat">
      </el-table-column>
      <el-table-column id="shua" prop="" header-align="center" align="center" width="300" label="用时"
        :formatter="timeUsedHandle">
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" width="180" label="备注">
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="300" label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('train:list')" type="text" size="small" :disabled="scope.row.missStatus==7?true:false"
          @click="watch(scope.row.algorithmTrainingId,scope.row.missStatus)">
            查看
          </el-button>

          <!-- <el-button type="text" size="small"
            @click="install(scope.row.algorithmTrainingId)">安装</el-button> -->

          <el-button v-if="isAuth('train:run')" type="text" size="small"
            @click="runtrain(scope.row.algorithmTrainingId,scope.row.algFrameId,scope.row.algorithmId)">{{ scope.row.hasRun !==null ? '再次运行' : '运行' }}</el-button>

          <el-button v-if="isAuth('train:stop')" type="text" size="small" :disabled="scope.row.missStatus==2?false:true"
            @click="pauseHandle(scope.row.algorithmTrainingId)">暂停</el-button>

          <el-button v-if="isAuth('train:rerun')" type="text" size="small" :disabled="scope.row.missStatus==7?false:true"
            @click="unpauseHandle(scope.row.algorithmTrainingId)">继续</el-button>

          <el-button v-if="isAuth('train:publish')" type="text" size="small" :disabled="scope.row.missStatus==3?false:true"
            @click="publish(scope.row.algorithmTrainingId)">发布</el-button>

          <el-button type="text" size="small" class="warningButton"
            @click="deleteMissHandle(scope.row.algorithmTrainingId)">删除</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="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <TrainAdd v-if="addVisible" ref="addS"></TrainAdd>
    <Publish v-if="publishVisible" ref="algPublish"></Publish>
    <SelectAlgPara v-if="selectAlgParaVisibel" ref="selectAlgPara"></SelectAlgPara>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
// import AddOrUpdate from "./dataset-add-or-update";
// import Watch from "./dataset-watch";
// import Add from "./dataset-add";

// import Add from "./train-add";
// import Add from "./train-add";
// import TrainAdd from './train-add.vue';
import TrainAdd from './train-add.vue';
import Publish from "./alg-publish.vue"
import SelectAlgPara from "./select-algpara.vue"
import { MessageBox } from 'element-ui'
import { Message } from "element-ui"
export default {
  //import引入的组件需要注入到对象中才能使用
  data() {
    return {
      loading:false,
      timer:null,
      dataForm: {
        missName: "",
      },
      // flag: 0,
      // tempList: [],
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      newWatchVisible: false,
      addVisible: false,
      classificationtag: "",
      missStatus: null,
      classification: [],
      publishVisible:false,
      selectAlgParaVisibel:false
    };
  },
  components: {
    TrainAdd,
    Publish,
    SelectAlgPara
  },

  activated() {
    this.getDataList();
    //定时器
    /* this.timer=window.setInterval(()=>{
      setTimeout(()=>{
        console.log("执行定时任务");
        this.getDataList();
      },0)
    },1000); */

  },
  //切换路由时，清除定时器
  beforeRouteLeave(to, from, next){
    next();
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  methods: {
    // startInterval() {
    //   setInterval(() => {

    //     if(this.flag % 2){
    //        this.dataList = [];
    //       console.log(this.tempList);
    //       console.log(this.dataList);
    //       console.log("ok");
    //     }else{
    //       this.dataList = this.tempList;
    //       console.log(this.tempList);
    //       // this.dataListLoading = true;
    //       console.log(this.dataList);
    //       console.log("no");
    //     }
    //     this.flag = this.flag + 1;
    //   }, 1000);
    // },

    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.classificationtag = '';
      this.missStatus = null;
      this.$http({
        url: this.$http.adornUrl("/category/select"),
        method: "get",
      }).then(({ data }) => {
        this.classification = this.unique(data.list);
      });

      this.$http({
        url: this.$http.adornUrl("/algstrain/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          missName: this.dataForm.missName,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
          this.statusunique = this.unique(data.page.list);
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    //筛选查询
    getDataList2() {
      this.dataListLoading = true;
      if(this.classificationtag===''){
        this.classificationtag=null;
      }
      this.$http({
        url: this.$http.adornUrl("/algstrain/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          missName: this.dataForm.missName,
          classificationtag: this.classificationtag,
          missStatus: this.missStatus
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    timeFn(d1) {
      //di作为一个变量传进来
      //如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
      var dateBegin = new Date(d1.replace(/-/g, "/")); //将-转化为/，使用new Date
      var dateEnd = new Date(); //获取当前时间
      var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
      var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
      var leave1 = dateDiff % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / (3600 * 1000)); //计算出小时数
      //计算相差分钟数
      var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / (60 * 1000)); //计算相差分钟数
      //计算相差秒数
      var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
      var seconds = Math.round(leave3 / 1000);
      console.log(
        " 相差 " +
          dayDiff +
          "天 " +
          hours +
          "小时 " +
          minutes +
          " 分钟" +
          seconds +
          " 秒"
      );
      console.log(
        dateDiff + "时间差的毫秒数",
        dayDiff + "计算出相差天数",
        leave1 + "计算天数后剩余的毫秒数",
        hours + "计算出小时数",
        minutes + "计算相差分钟数",
        seconds + "计算相差秒数"
      );
      return (
        dayDiff + "计算出相差天数",
        hours + "计算出小时数",
        minutes + "计算相差分钟数",
        seconds + "计算相差秒数"
      );
    },

    //通过开始时间计算用时
    timeUsedHandle(row, column) {
      if (row.missCreationTime === null || row.missStopTime === null) {
        return "-";
      } else {
        const missCreationTime = new Date(row.missCreationTime);
        const missStopTime = new Date(row.missStopTime);
        const timeDifference = missStopTime - missCreationTime; // 差值为毫秒
        if (!isNaN(timeDifference)) {
          const seconds = Math.floor((timeDifference / 1000) % 60);
          const minutes = Math.floor((timeDifference / (1000 * 60)) % 60);
          const hours = Math.floor((timeDifference / (1000 * 60 * 60)) % 24);
          const displayTime = `${hours}小时 ${minutes}分钟 ${seconds}秒`;
          return displayTime;
        } else {
          return "时间差计算出错";
        }
      }
    },
    missCreationTimeFormat(row, column){
      if (row.missCreationTime === null) {
        return "-";
      } else{
        return row.missCreationTime;
      }
    },
    missStopTimeFormat(row, column){
      if (row.missStopTime === null) {
        return "-";
      } else{
        return row.missStopTime;
      }
    },
    missStatusHandle(row, column) {
      if (row.missStatus === 0) {
        return "停止";
      } else {
        return "正在运行";
      }
    },
    //去重
    unique(arr) {
      var ss = [];
      for (var i = 0; i < arr.length; i++) {
        ss[i] = arr[i].categoryName;
      }
      return Array.from(new Set(ss));
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 查看
    watch(id,missStatus) {
      /* this.newWatchVisible = true;
      this.$nextTick(() => {
        this.$refs.newWatch.init(id);
      }); */
      this.$router.replace({ path: "/train-watch" ,query:{algorithmTrainingId:id,missStatus:missStatus}});

    },
    //保存tensorboard文件
    saveTensorboardFile(id){
      this.$http({
          url:this.$http.adornUrl('/algstrain/saveTensorboardFile'),
          method:'get',
          params:this.$http.adornParams({
            algorithmTrainingId:id
          }),
        }).then(({data})=>{


        });
    },
    //对比两个训练任务的tensorboard图像
    algorithmTrainCompare(){
        if(this.dataListSelections.length<2){
          Message.error('请选择两个算法任务进行对比');
          return;
        }
        this.loading=true;
        var algTrainIds=new Array();
        for(var i=0;i<this.dataListSelections.length;i++){
          algTrainIds[i]=this.dataListSelections[i].algorithmTrainingId;
        }
        console.log(algTrainIds);
        this.$http({
          url:this.$http.adornUrl('/algstrain/algorithmTrainCompare'),
          method:'post',
          data: this.$http.adornData(algTrainIds,false),
        }).then(({data})=>{
          if(data&&data.code===0){
              this.loading=false;
              this.$router.replace({ name: 'traincompare',query:{port:data.port,containerId:data.containerId} });
          }else{
              this.loading=false;
              Message.error('对比失败');
          }
        });
    },

    //安装所上传的依赖包----------------------仅做测试，后续合并到其他方法后，需删除该方法
    install(id){
      this.$http({
          url:this.$http.adornUrl('/algstrain/installWhl'),
          method:'get',
          params:this.$http.adornParams({
            algorithmTrainingId:id
          }),
        }).then(({data})=>{
          console.log("安装成功");
      });
    },

    // 运行任务
    runtrain(id,algFrameId,algorithmId) {
      /* if(algFrameId!=-1){
        this.$http({
            url:this.$http.adornUrl('/algstrain/changeMissStatus'),
            method:'get',
            params:this.$http.adornParams({
              algorithmTrainingId:id
            }),
          }).then(({data})=>{
            this.getDataList();

        });

        this.$http({
            url:this.$http.adornUrl('/algstrain/startTraining'),
            method:'get',
            params:this.$http.adornParams({
              algorithmTrainingId:id
            }),
          }).then(({data})=>{

        });
      }else{
        this.selectAlgParaVisibel=true;
          this.$nextTick(() => {
            this.$refs.selectAlgPara.init(id,algorithmId);
          });
      } */
      MessageBox.confirm(`是否运行该算法任务?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
            url:this.$http.adornUrl('/algstrain/changeMissStatus'),
            method:'get',
            params:this.$http.adornParams({
              algorithmTrainingId:id
            }),
          }).then(({data})=>{
            this.getDataList();
            console.log("this.dataList1111", this.dataList);
            // this.dataList.forEach(item=>{
            //   if (item.algorithmTrainingId === id) {
            //     this.$set(item, 'missStopTime', '-'); // 确保 Vue 能捕捉到这个变化
            //   }
            // })
            this.$http({
                url:this.$http.adornUrl('/algstrain/startTraining'),
                method:'get',
                params:this.$http.adornParams({
                  algorithmTrainingId:id
                }),
              }).then(({data})=>{
                if(data && data.code === 0){
                  Message({
                    type: 'success',
                    message: '运行成功',
                  });
                } else {
                  Message.error(data.msg);
                }
                this.getDataList();
            });
        });
      }).catch(() => {})






    },
    // 重新运行任务
    reruntrain(id) {},
    //算法发布
    publish(id){
      this.publishVisible=true;
      this.$nextTick(()=>{
        this.$refs.algPublish.init(id);
      });
    },

    // 这里处理新建任务
    addHandle() {
      // this.addVisible = true;
      this.$nextTick(() => {
        this.$router.replace({ path: "/mission-create" });
      });
    },
    //暂停训练任务
    pauseHandle(id){
      MessageBox.confirm('此操作将暂停该算法任务, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading=true;
          this.$http({
            url:this.$http.adornUrl('/algstrain/pauseMiss'),
            method:'get',
            params:this.$http.adornParams({
              algorithmTrainingId:id
            }),
          }).then(({data})=>{
            this.getDataList();
            Message({
              type: 'success',
              message: '暂停成功'
            });
            this.loading=false;
          });
        }).catch(() => {
          Message({
            type: 'info',
            message: '已取消暂停'
          });
        });
    },

    //恢复已暂停的训练任务
    unpauseHandle(id){
      MessageBox.confirm(`是否继续运行该算法任务?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
          this.$http({
            url:this.$http.adornUrl('/algstrain/unpauseMiss'),
            method:'get',
            params:this.$http.adornParams({
              algorithmTrainingId:id
            }),
          }).then(({data})=>{
            this.getDataList();
            Message({
              type: 'success',
              message: '已继续运行'
            });
            this.loading=false;
      });
      }).catch(() => {})



    },

    // 处理停止任务
    deleteHandle(id) {
      var deleteHandle = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.deleteHandle;
          });
      MessageBox.confirm(
        `确定对[id=${deleteHandle.join(",")}]进行[${
          id ? "停止" : "批量停止"
        }]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/algs/delete"),
            method: "post",
            data: this.$http.adornData(deleteHandle, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              Message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
              this.pageIndex = 1;
              getDataList();
            } else {
              Message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    //处理删除任务
    deleteMissHandle(id) {
      MessageBox.confirm('此操作将删除该算法任务, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading=true;
          this.$http({
            url:this.$http.adornUrl('/algstrain/deleteById'),
            method:'get',
            params:this.$http.adornParams({
              algorithmTrainingId:id
            }),
          }).then(({data})=>{
            this.getDataList();
            Message({
              type: 'success',
              message: '删除成功!'
            });
            this.loading=false;
        });


        }).catch(() => {
          Message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

  },
};
</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;
}
.warningButton{
  color: #F56C6C;
}
</style>
