<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <!-- <el-button type="primary" @click="addOrUpdateHandle()"
          >新增应用</el-button
        > -->
        <el-form-item>
          <el-input
            v-model="dataForm.applicationName"
            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.deployDeviceId"
          @change="getDataListByType(dataForm.applicationType)"
        >
          <el-option
            v-for="data in deployDevices"
            :key="data.edgenodesId"
            :label="data.edgenodesName"
            :value="data.edgenodesId"
          ></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="applicationName"
        header-align="center"
        align="center"
        label="名称"
      >
      </el-table-column>
      <!-- <el-table-column
        prop="applicationId"
        header-align="center"
        align="center"
        label="应用ID"
      >
      </el-table-column> -->
      <el-table-column
        prop="applicationVersion"
        header-align="center"
        align="center"
        label="应用版本"
      >
      </el-table-column>
      <el-table-column
        prop="applicationType"
        header-align="center"
        align="center"
        label="应用类型"
      >
      </el-table-column>

      <el-table-column
        prop="applicationStatus"
        header-align="center"
        align="center"
        label="应用状态"
      >
      </el-table-column>
      <el-table-column
        prop="deployDeviceName"
        header-align="center"
        align="center"
        label="部署设备"
      >
      </el-table-column>
      <!-- <el-table-column
        prop="parentProjectName"
        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="applicationDescription"
        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="text"
            size="small"
            :disabled="scope.row.applicationStatus == '运行中' ? true : false"
            @click="
              startApp(
                scope.row.applicationName,
                scope.row.applicationId,
                scope.row.applicationStatus
              )
            "
            >{{ scope.row.loadingText }}</el-button
          >
          <el-button
            type="text"
            size="small"
            :disabled="scope.row.applicationStatus == '运行中' ? false : true"
            @click="updateApplication(scope.row, '暂停')"
            >暂停</el-button
          >
          <el-button
            type="text"
            size="small"
            :disabled="scope.row.applicationStatus == '运行中' ? false : true"
            @click="viewApplicationDetail(scope.row.applicationId)"
            >查看详情</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="updateApplication(scope.row, '删除')"
            >删除</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>
    <view-detail v-if="viewDetailVisible" ref="viewDetail"> </view-detail>
  </div>
</template>

<script>
import AddOrUpdate from "./createApp/applications-add-or-update";
import ViewDetail from "./createApp/applications-view-detail.vue";
export default {
  data() {
    return {
      dataForm: {
        applicationType: "",
        applicationName: "",
        deployDeviceId:"",
      },
      dataList: [],
      pageIndex: 1,
      pageSize: this.$store.state.settings.pageSize,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      viewDetailVisible: false,
      filterVal: "",
      applicationTypeOptions: [
      ],
      deployDevices:[
        
      ]
    };
  },
  components: {
    AddOrUpdate,
    ViewDetail,
  },
  activated() {
    this.getDataList();
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      /* this.$http({
        url: this.$http.adornUrl("/category/select"),
        method: "get",
      }).then(({ data }) => {
        this.applicationTypeOptions = this.unique(data.list);
      }); */
      //获取所有边缘结点
      this.$http({
          url: this.$http.adornUrl('/generator/edgenodes/list'),
          method: 'get',
          params: this.$http.adornParams({
            
          })
        }).then(({data}) => {
          this.deployDevices=data.page.list;
          var center={edgenodesId:0,edgenodesName:"中心云"};
          this.deployDevices.push(center);
        })
      this.$http({
        url: this.$http.adornUrl("/generator/applications/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          deployDeviceId: this.dataForm.deployDeviceId,
          applicationName: this.dataForm.applicationName,
        }),
      }).then(({ 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;
      });
    },
    // 每页数
    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);
      });
    },
    //去重
    unique(arr) {
      var ss = [];
      for (var i = 0; i < arr.length; i++) {
        ss[i] = arr[i].categoryName;
      }
      return Array.from(new Set(ss));
    },
    // 查看详情
    viewApplicationDetail(id) {
      var item = this.dataList.filter((item) => item.applicationId === id);
      // 获取应用的name和版本号,传入到详情
      console.log("查看item中数据" + item);
      this.viewDetailVisible = true;
      this.$nextTick(() => {
        this.$refs.viewDetail.init(
          item[0].applicationName,
          item[0].applicationVersion,
          item[0].createTime,
          item[0].applicationType,
          item[0].applicationDescription,
          item[0].parentProjectName
        );
      });
    },

    // 格式化名字
    formatName(name) {
      return name + "application";
    },
    // 更新应用状态
    async updateApplication(application, state) {
      this.$confirm(
        `是否${state}应用${
          application.applicationName
        }`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        // 改变应用描述
        this.updateApplicationState(application, state);
        // 删除应用
        this.deleteApp(application);
        this.$message({
          message: "操作成功",
          type: "success",
          duration: 1500,
          onClose: () => {
            this.getDataList();
          },
        });
      });
    },
    // 在kubesphere删除
    async deleteApp(application) {
      try {
        await this.$http({
          url: `/kubesphereApi/apis/app.k8s.io/v1beta1/namespaces/mkcloud/applications/${this.formatName(
            application.applicationName
          )}`,
          method: "delete",
        });
      } catch (e) {
        console.log("error", e);
      }
    },
    // 将状态更改
    async updateApplicationState(application, state) {
      if (state == "暂停") {
        console.log("state", state);
        await this.$http({
          url: this.$http.adornUrl("/generator/applications/update"),
          method: "post",
          data: this.$http.adornData({
            applicationId: application.applicationId,
            applicationStatus: state,
          }),
        });
      } else if (state == "删除") {
        var ids = [application.applicationId];
        await this.$http({
          url: this.$http.adornUrl("/generator/applications/delete"),
          method: "post",
          data: this.$http.adornData(ids, false),
        });
        // 改变image表
        this.updateImage(application.applicationName);
      }
    },
    // 更新image状态
    async updateImage(name) {
      const { data } = await this.$http({
        url: this.$http.adornUrl("/generator/images/listAll"),
        method: "get",
      });
      console.log(data.list)
      const image = data.list.find((item) => item.imageName == name);
      if (image) {
        await this.$http({
          url: this.$http.adornUrl("/generator/images/update"),
          method: "post",
          data: this.$http.adornData({
            imageId: image.imageId,
            imageDescription: "未发布",
          }),
        });
      }
    },
    // 启动
    startApp(name, id, state) {
      this.$confirm(`是否启动应用${name}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (state != "运行中") {
          let index = this.dataList.findIndex((item) => {
            return item.applicationId == id;
          });
          this.dataList[index].state = 1;
          this.dataList[index].loadingText = "正在启动";
          this.$http({
            url: this.$http.adornUrl("/kubeSphere/algorithmStart"),
            method: "post",
            data: {
              imageName: name,
            },
          })
            .then(({ data }) => {
              this.dataList[index].state = 0;
              this.dataList[index].loadingText = "启动";
              if (!data.code) {
                this.$http({
                  url: this.$http.adornUrl("/generator/applications/update"),
                  method: "post",
                  data: this.$http.adornData({
                    applicationId: id,
                    applicationStatus: "运行中",
                  }),
                }).then(({ data }) => {
                  if (!data.code) {
                    this.$message({
                      message: "启动成功",
                      type: "success",
                      duration: 3000,
                      onClose: () => {
                        this.getDataList();
                      },
                    });
                  } else {
                    this.$message.error("启动失败", 1500);
                  }
                });
              } else {
                this.$message.error("启动失败", 1500);
              }
            })
            .catch((error) => {
              this.$message({
                message: "启动失败",
                type: "error",
                duration: 1500,
                onClose: () => {
                  this.dataList[index].state = 0;
                  this.dataList[index].loadingText = "启动";
                },
              });
            });
        } else {
          this.$message.warning("已运行", 1500);
        }
      });
    },
    getDataListByName(value) {
      console.log(
        "getDataListByName  dataForm  " +
          this.dataForm.applicationId +
          "|" +
          this.dataForm.applicationName +
          "|" +
          this.dataForm.applicationType
      );
      this.getDataList();
    },
    //根据下拉框进行查询，这里是指通过镜像类型进行查询
    getDataListByType(value) {
      console.log(
        "getDataListByType  dataForm  " +
          this.dataForm.applicationId +
          "|" +
          this.dataForm.applicationName +
          "|" +
          this.dataForm.applicationType
      );
      this.getDataList();
    },
  },
};
</script>


