<template>
  <div class="mod-config">
    <el-dialog
      title="应用部署设备选择"
      :visible.sync="appDeviceVisible"
      width="30%"
      >
      <el-form>
        <el-form-item label="选择部署设备">
          <el-select v-model="device" placeholder="请选择" @change="getEdgenodes()">
            <el-option
              v-for="item in deviceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择边缘结点" v-if="edgeSelectVisible">
          <el-select v-model="edgenode" placeholder="请选择">
            <el-option
              v-for="item in edgenodes"
              :key="item.edgenodesId"
              :label="item.edgenodesName"
              :value="item.edgenodesId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="checkDeployDevice()">确 定</el-button>
      </span>
    </el-dialog>
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <!-- <el-button
          v-if="isAuth('generator:images:save')"
          type="primary"
          @click="addOrUpdateHandle()"
          >新增镜像</el-button
        > -->
        <el-form-item>
          <el-input
            v-model="dataForm.imageName"
            placeholder="镜像名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-button @click="getDataListByName()">查询</el-button>
      </el-form-item>

      <el-form-item>
        <el-select
          clearable
          label="镜像类别"
          v-model="dataForm.imageType"
          @change="getDataListByType(dataForm.imageType)"
        >
          <el-option
            v-for="item in imageTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </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="imageName"
        header-align="center"
        align="center"
        label="镜像名称"
      >
      </el-table-column>
      <!-- <el-table-column
        prop="imageAlias"
        header-align="center"
        align="center"
        label="镜像别名"
      >
      </el-table-column> -->
      <!-- <el-table-column
        prop="imageId"
        header-align="center"
        align="center"
        label="镜像id"
      >
      </el-table-column> -->
      <el-table-column
        prop="imageTag"
        header-align="center"
        align="center"
        label="镜像版本"
      >
      </el-table-column>
      <el-table-column
        prop="imageType"
        header-align="center"
        align="center"
        label="镜像类型"
      >
      </el-table-column>
      <el-table-column
        prop="buildEnvironment"
        header-align="center"
        align="center"
        label="构建环境"
      >
      </el-table-column>
      <el-table-column
        prop="creatorName"
        header-align="center"
        align="center"
        label="创建者"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="镜像创建时间"
      >
      </el-table-column>
      <!-- <el-table-column
        prop="imageSize"
        header-align="center"
        align="center"
        label="镜像大小"
      >
      </el-table-column> -->
      <el-table-column
        prop="imageDescription"
        header-align="center"
        align="center"
        label="描述信息"
      >
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        label="操作"
      >
        <template slot-scope="scope">
          <!-- <el-button
            type="primary"
            size="small"
            :disabled="scope.row.imageDescription == '已发布' ? true : false"
            :loading="scope.row.state == 0 ? false : true"
            @click="startImage(scope.row)"
            >{{ scope.row.loadingText }}</el-button
          > -->
          <el-button
            type="primary"
            size="small"
            :disabled="scope.row.imageDescription == '已发布' ? true : false"
            :loading="scope.row.state == 0 ? false : true"
            @click="chooseAppDevice(scope.row)"
            >{{ scope.row.loadingText }}</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="
              deleteHandle(
                scope.row.imageId,
                scope.row.imageAlias,
                scope.row.imageName
              )
            "
            >删除</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>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>
  </div>

</template>

<script>
import AddOrUpdate from "./images-add-or-update";
export default {
  data() {
    return {
      dataForm: {
        imageName: "",
        imageType: "",
      },
      dataList: [],
      pageIndex: 1,
      pageSize: this.$store.state.settings.pageSize,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      appDeviceVisible: false,
      filterVal: "",
      imageTypeOptions: [
        {
          value: "",
          label: "全部",
        },
        {
          value: "传统算法镜像",
          label: "传统算法镜像",
        },
        {
          value: "应用镜像",
          label: "应用镜像",
        },
      ],
      device:"",
      deviceOptions:[
        {
          value: "0",
          label: "中心云",
        },
        {
          value: "-1",
          label: "边缘云",
        },
      ],
      edgeSelectVisible:false,
      edgenode:"",
      edgenodes:[
        {
          edgenodesId:"1",
          edgenodesName:"边缘设备1",
        },{
          edgenodesId:"2",
          edgenodesName:"边缘设备2",
        },{
          edgenodesId:"3",
          edgenodesName:"边缘设备3",
        }
      ],
      image:{},
      deployDevice:"",
    };
  },
  components: {
    AddOrUpdate,
  },
  activated() {
    this.getDataList();
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/generator/images/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          imageName: this.dataForm.imageName,
          imageType: this.dataForm.imageType,
        }),
      }).then(({ data }) => {
        console.log(data);
        if (data && data.code === 0) {
          this.dataList = data.page.list.map((element) => {
            element["state"] = 0;
            element["loadingText"] = "启动";
            return element;
          });
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });

      //获取所有边缘结点
      this.$http({
          url: this.$http.adornUrl('/generator/edgenodes/list'),
          method: 'get',
          params: this.$http.adornParams({
            
          })
        }).then(({data}) => {
          this.edgenodes=data.page.list;
        })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    //详情
    showInfoHandle(id) {
      this.showInfoVisible = true;
      this.$nextTick(() => {
        this.$refs.showInfo.init(id);
      });
    },

    // 删除
    deleteHandle(id, aliasName, name) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.imageId;
          });
      this.$confirm(
        `确定对${name}进行${id ? "删除" : "批量删除"}操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/generator/images/delete"),
          method: "post",
          data: this.$http.adornData(ids, false),
        }).then(({ data }) => {
          if (!data.code) {
            // 删除kubesphere的记录
            this.deleteImage(aliasName);
            // 更新算法表
            this.updateAlgorithm(name);
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              },
            });
          } else {
            this.$message({
              message: "操作失败",
              type: "error",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              },
            });
          }
        });
      });
    },

    async updateAlgorithm(algorithmName) {
      const { data } = await this.$http({
        url: this.$http.adornUrl("/minioAlgorithm/getAlgorithmList"),
        method: "get",
      });
      const algorithm = data.find(
        (item) => item.algorithmName == algorithmName
      );
      if (algorithm) {
        await this.$http({
          url: this.$http.adornUrl("/generator/model/update"),
          method: "post",
          data: this.$http.adornData({
            modelId: algorithm.algorithmId,
            remark: "未发布",
          }),
        });
      }
    },
    // 删除镜像
    async deleteImage(aliasName) {
      try {
        await this.$http({
          url: `/kubesphereApi/apis/devops.kubesphere.io/v1alpha1/namespaces/mkcloud/s2ibuilders/${aliasName}`,
          method: "delete",
        });
      } catch (e) {
        console.log("error", e);
      }
    },
    //查询搜索框
    getDataListByName(value) {
      console.log(
        "getDataListByName  dataForm  " +
          this.dataForm.imageId +
          "|" +
          this.dataForm.imageName +
          "|" +
          this.dataForm.imageType
      );
      this.getDataList();
    },
    //根据下拉框进行查询，这里是指通过镜像类型进行查询
    getDataListByType(value) {
      console.log(
        "getDataListByType  dataForm  " +
          this.dataForm.imageId +
          "|" +
          this.dataForm.imageName +
          "|" +
          this.dataForm.imageType
      );
      this.getDataList();
    },
    // 选择应用部署设备
    chooseAppDevice(image){
      this.appDeviceVisible=true;
      this.image=image;

    },
    // 启动镜像
    async startImage(image) {
      this.$confirm(`是否启动镜像${image.imageName}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let index = this.dataList.findIndex((item) => {
          return item.imageId == image.imageId;
        });
        this.dataList[index].state = 1;
        this.dataList[index].loadingText = "启动中";
        console.log("123");
        this.$http({
          url: this.$http.adornUrl("/kubeSphere/algorithmStart"),
          method: "post",
          data: {
            imageName: image.imageName,
          },
        })
          .then(({ data }) => {
            this.dataList[index].state = 0;
            this.dataList[index].loadingText = "启动";
            if (!data.code) {
              this.addApplication(image.imageName);
              this.updateImage(image, "已发布");
            } else {
              this.$message.error("启动失败", 1500);
              this.updateImage(image, "发布失败");
            }
          })
          .catch((error) => {
            this.$message({
              message: "启动失败",
              type: "error",
              duration: 1500,
              onClose: () => {
                this.dataList[index].state = 0;
                this.dataList[index].loadingText = "启动";
                this.updateImage(image, "发布失败");
              },
            });
          });
      });
    },
    // 添加应用
    async addApplication(name) {
      const { data } = await this.$http({
        url: this.$http.adornUrl("/generator/applications/save"),
        method: "post",
        data: this.$http.adornData({
          applicationName: name,
          deployDeviceId: this.deployDevice,
          applicationType: "算法",
          applicationVersion: "v1",
          applicationStatus: "运行中",
          parentProjectName: "mkcloud",
          createTime: new Date().getTime(),
          creatorName: this.$store.state.user.name,
        }),
      });
      if (data && data.code === 0) {
        this.$message({
          message: "启动成功",
          type: "success",
          duration: 3000,
        });
      } else {
        this.$message.error("启动失败", 1500);
      }
    },
    // 修改镜像状态
    async updateImage(image, state) {
      await this.$http({
        url: this.$http.adornUrl("/generator/images/update"),
        method: "post",
        data: this.$http.adornData({
          imageName: image.imageName,
          buildEnvironment: image.buildEnvironment,
          createTime: image.createTime,
          imageId: image.imageId,
          imageSize: image.imageSize,
          imageTag: image.imageTag,
          imageType: image.imageType,
          imageDescription: state,
          imageAlias: image.imageAlias,
          creatorName: image.creatorName,
        }),
      });
      this.getDataList();
    },
    // 获取所有边缘设备
    getEdgenodes(){
      if(this.device=="-1"){
        this.edgeSelectVisible=true;
      }else{
        this.edgeSelectVisible=false;
      }
    },
    checkDeployDevice(){
      if(this.device=="-1"){
        this.deployDevice=this.edgenode;
        console.log("部署在边缘结点："+this.deployDevice);
      }else{
        this.deployDevice=this.device;
        console.log("部署在中心云："+this.deployDevice);
      }
      if(this.deployDevice.length==0){
        this.$message.error("请选择部署设备", 1500);
      }else{
        this.startImage(this.image);
        this.appDeviceVisible=false;
      }
      
    }
  },
};
</script>

