<template>
  <div class="mod-config">
    <el-dialog
      title="镜像制作日志"
      :visible.sync="imagesLogVisible"
      width="30%"
      >
      <div style = "white-space: pre-wrap">{{imagesLog}}</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="imagesLogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-form :inline="true">
      <el-form-item>
        <el-form-item>
          <el-input
            v-model="search"
            placeholder="按照算法名称搜索"
            @keyup.enter.native="searchDataList()"
            clearable
          ></el-input>
        </el-form-item>
        <el-button @click="searchDataList()">查询</el-button>

        
      </el-form-item>
    </el-form>

    <el-table
      :data="dataList.slice((pageIndex - 1) * pageSize, pageIndex * pageSize)"
      border
      v-loading="dataListLoading"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="algorithmId"
        header-align="center"
        align="center"
        label="算法id"
      >
      </el-table-column>
      <el-table-column
        prop="algorithmName"
        header-align="center"
        align="center"
        label="算法名称"
      >
      </el-table-column>
      <el-table-column
        prop="category"
        header-align="center"
        align="center"
        label="分类"
        filter-placement="bottom-end"
        column-key="category"
        style=""
        :filter-multiple="false"
        :filter-method="filterCategory"
        :filters="classification"
      >
      </el-table-column>
      <el-table-column
        prop="creator"
        header-align="center"
        align="center"
        label="创建人"
      >
      </el-table-column>
      <el-table-column
        prop="form"
        header-align="center"
        align="center"
        label="形式"
      >
      </el-table-column>
      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        label="描述信息"
      >
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="300"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            v-if="scope.row.form=='智能算法'"
            :loading="scope.row.state == 0 ? false : true"
            :disabled="scope.row.remark == '已发布' ? true : false"
            @click="
              publishAlgorithm(scope.row.algorithmName, scope.row.algorithmId)
            "
            :formatter="constructMessage(scope.row.constructMessage,scope.row.algorithmId)"
            >{{ scope.row.loadingText }}</el-button
          >

          <el-button
            type="primary"
            size="small"
            v-if="scope.row.form=='传统算法'"
            :loading="scope.row.state == 0 ? false : true"
            :disabled="scope.row.remark == '已发布' ? true : false"
            @click="
              publishTraAlgorithm(scope.row.algorithmName, scope.row.algorithmId)
            "
            :formatter="constructMessage(scope.row.constructMessage,scope.row.algorithmId)"
            >{{ scope.row.loadingText }}</el-button
          >

          <!-- <el-button type="danger" size="small" @click="isPublish()"
            >删除</el-button
          > -->
          <el-button type="success" size="small" @click="watchImagesLog(scope.row.algorithmId)"
            :disabled="scope.row.remark == '已发布' ? false : true"
            >查看日志</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="this.$store.state.settings.pageSizeList"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
  </div>
</template>

<script>
import AddOrUpdate from "./algorithm-add-or-update";
export default {
  data() {
    return {
      imagesLogVisible:false,
      imagesLog:"",
      // 搜索框的字段
      search: "",
      classification: [
        { text: "水文", value: "水文" },
        { text: "清洁", value: "清洁" },
        { text: "安全", value: "安全" },
        { text: "采矿", value: "采矿" },
        { text: "智能", value: "智能" },
        { text: "防冲", value: "防冲" },
      ],
      dataList: [],
      pageIndex: 1,
      pageSize: this.$store.state.settings.pageSize,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      param:{
        Input:{
          ParameterInput:[],
          FileInput:[]
        },
        Output:{
          ParameterOutput:[],
          FileOutput:[]
        }
      },
      paramInput:{
        paraname:"",
        paratype:"",
        paradesc:""
      },
      paramOutput:{
        paraname:"",
        paratype:"",
        paradesc:"",
        valuefrom:""
      },
      websocket:null
    };
  },
  components: {
    AddOrUpdate,
  },
  activated() {
    this.getDataList();
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/minioAlgorithm/getAlgorithmList"),
        method: "get",
        params: this.$http.adornParams({
          search:this.search
        }),
      }).then(({ data }) => {
        console.log("data", data);
        if (data.length) {
          this.dataList = data.map((element) => {
            element["state"] = 0;
            element["loadingText"] = "发布";
            return element;
          });
          this.totalPage = this.dataList.length;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
    },
    // 筛选
    filterCategory(value, row, column) {
      console.log("value", value);
      console.log("row", row);
      console.log("column", column);
      return row.category == value;
    },
    //查询搜索框
    searchDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/minioAlgorithm/selectByName"),
        method: "get",
        params: this.$http.adornParams({
          algName:this.search
        }),
      }).then(({ data }) => {
        console.log("data", data);
        if (data.length) {
          this.dataList = data.map((element) => {
            element["state"] = 0;
            element["loadingText"] = "发布";
            return element;
          });
          this.totalPage = this.dataList.length;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
      /*
      this.getDataList();
       this.dataList = this.dataList.filter(
        (data) =>
          !this.search ||
          data.algorithmName.toLowerCase().includes(this.search.toLowerCase())
      );
      this.totalPage = this.dataList.length; */
    },
    //查询镜像制作日志
    watchImagesLog(id){
      this.$http({
          url: this.$http.adornUrl("/kubeSphere/imagesLog"),
          method: "post",
          data: {
            modelId:id
          },
          timeout: 300000,
        })
        .then(({ data }) => {
            console.log(data.imagesLog);
            this.imagesLog=data.imagesLog;
            this.imagesLogVisible=true;
          })
    },
    // 发布算法
    publishAlgorithm(name, id) {
      this.$confirm(`是否对算法${name}进行发布？该算法需已指定主运行文件且算法名称不可包含中文及大写英文字母`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let index = this.dataList.findIndex((item) => {
          return item.algorithmId == id;
        });
        this.dataList[index].state = 1;
        this.dataList[index].loadingText = "算法下载中";
        this.handleLog(index);
        this.$http({
          url: this.$http.adornUrl("/kubeSphere/algorithmPublished"),
          method: "post",
          data: {
            algorithmName: name,
          },
          timeout: 300000,
        })
          .then(({ data }) => {
            this.dataList[index].state = 0;
            this.dataList[index].loadingText = "发布";
            console.log("data", data);
            if (!data.code) {
              // 改变算法为已经发布
              this.updateAlgorithm(id, "已发布");
            } else {
              this.$message.error("发布失败", 1500);
            }
          })
          .catch(() => {
            this.$message({
              message: "发布失败",
              type: "error",
              duration: 1500,
              onClose: () => {
                this.dataList[index].state = 0;
                this.dataList[index].loadingText = "发布";
              },
            });
          });
      });
    },

    // 发布传统算法
    publishTraAlgorithm(name, id) {
      this.$confirm(`是否对算法${name}进行发布`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          this.param={
          Input:{
            ParameterInput:[],
            FileInput:[]
          },
          Output:{
            ParameterOutput:[],
            FileOutput:[]
          }
        }
        this.$http({
          url: this.$http.adornUrl("/kubeSphere/getTraParam"),
          method: "post",
          data: {
            algorithmName: name,
          },
          timeout: 300000,
        }).then(({ data }) => {
              let index = this.dataList.findIndex((item) => {
              return item.algorithmId == id;
            });
            this.dataList[index].state = 1;
            this.dataList[index].loadingText = "算法下载中";
            this.handleLog(index);
            let params=new Array();
            let results=new Array();
            params=data.params;
            results=data.results;
            console.log(params)
            console.log(results)
            for(var i=0;i<params.length;i++){
              this.paramInput.paraname=params[i].algorithmParameterName;
              this.paramInput.paratype=params[i].algorithmParameterType;
              
              var newParamObj=JSON.parse(JSON.stringify(this.paramInput));
              this.param.Input.ParameterInput.push(newParamObj);
            }
            for(var i=0;i<results.length;i++){
              this.paramOutput.paraname=results[i].algorithmResultName;
              this.paramOutput.paratype="file";
              this.paramOutput.valuefrom=results[i].algorithmResultLocation;
              var newParamOutputObj=JSON.parse(JSON.stringify(this.paramOutput));
              this.param.Output.ParameterOutput.push(newParamOutputObj);
            }
            console.log(this.param);
            this.$http({
              url: this.$http.adornUrl("/kubeSphere/traAlgorithmPublished"),
              method: "post",
              data:{
                params:this.param,
                algorithmName:name
              },
              Headers:{
                'Content-Type':'application/json;charset=UTF-8'
              },
            }).then(({ data }) => {
                this.dataList[index].state = 0;
                this.dataList[index].loadingText = "发布";
                console.log("data", data);
                if (!data.code) {
                  // 改变算法为已经发布
                  this.updateAlgorithm(id, "已发布");
                } else {
                  this.$message.error("发布失败", 1500);
                }
            });
          })
          .catch(() => {
            this.$message({
              message: "发布失败",
              type: "error",
              duration: 1500,
              onClose: () => {
                this.dataList[index].state = 0;
                this.dataList[index].loadingText = "发布";
              },
            });
          });
      });
    },

    // 添加镜像
    async addImage(name,type) {
      const { data } = await this.$http({
        url: this.$http.adornUrl("/generator/images/save"),
        method: "post",
        data: this.$http.adornData({
          imageName: name,
          imageTag: "latest",
          creatorName: this.$store.state.user.name,
          createTime: new Date().getTime(),
          imageType: type,
          buildEnvironment: "s2i-binary",
          imageDescription: "未发布",
        }),
      });
      if (data && data.code === 0) {
        this.$message({
          message: "发布成功",
          type: "success",
          duration: 3000,
        });
      } else {
        this.$message.error("发布失败", 1500);
      }
    },
    // 改变状态
    async updateAlgorithm(id, state) {
      try {
        await this.$http({
          url: this.$http.adornUrl("/generator/model/update"),
          method: "post",
          data: this.$http.adornData({
            modelId: id,
            remark: state,
          }),
        });
      } catch (e) {
        console.log("error", e);
      }
      this.getDataList();
    },


    //获取webSocket消息
    handleLog(id) {
      var websocket = null;
      
      var host = "ws://150.158.138.99:8085/mkcloud/webSocket/log";
      // if (window.location.protocol == 'http:') {
      //   host = 'ws://' + window.location.host + '/websocket';
      // } else {
      //   host = 'wss://' + window.location.host + '/websocket';
      // }

      //判断当前浏览器是否支持WebSocket
      if ('WebSocket' in window) {
        this.websocket = new WebSocket(host);
      } else if ('MozWebSocket' in window) {
        this.websocket = new MozWebSocket(host);
      } else {
        alert("该浏览器不支持WebSocket！");
      }
      console.log(host)
      this.initWebSocket(id);

      // if ("WebSocket" in window) {
      //   let url = `ws://localhost/websocket`;
      //   console.log(url);
      //   this.websocket = new WebSocket(url);
      //   this.initWebSocket();
      // }
    },

    //初始化webSocket
    initWebSocket(id) {
      // 连接错误
      this.websocket.onerror = () => {
        console.log(
            "WebSocket连接发生错误   状态码：" + this.websocket.readyState
        );
      };
      // 连接成功
      this.websocket.onopen = () => {
        console.log(
            "WebSocket连接成功    状态码：" + this.websocket.readyState
        );
      };
      this.websocket.onclose = () => {
        console.log(
            "WebSocket断开    状态码：" + this.websocket.readyState
        );
      };
      // 收到消息的回调
      this.websocket.onmessage = (event) => {
        // this.consumeCount = this.consumeCount + 1;
        // if (this.filter && event.data.indexOf(this.keyword) == -1) {
        //   return
        // }
        var curIndex=id;
        console.log(event.data)
        if (event.data.match("下载完成")) {
          this.dataList[curIndex].state = 1;
          this.dataList[curIndex].loadingText = "镜像制作中";
          this.getDataList();
        }
        if (event.data.match("制作完成")) {
          this.websocket.close();
          
        }
        /* else{
          this.websocket.close();
        } */
        
      }
    },
    constructMessage(algConstructMessage,id){
      let index = this.dataList.findIndex((item) => {
        return item.algorithmId == id;
      });
      if(algConstructMessage=="算法下载中"){
          this.dataList[index].state = 1;
          this.dataList[index].loadingText = "算法下载中";
      }else if(algConstructMessage=="镜像制作中"){
          this.dataList[index].state = 1;
          this.dataList[index].loadingText = "镜像制作中";
      }else if(algConstructMessage=="已发布"){

      }
    },
  },
};
</script>
