<template>
  <div id="projectManage">
    <el-row>
      <el-col :span="24">
        <el-button @click="add()" type="success" style="margin-left: 20px;" size="mini"><i class="el-icon-plus"></i> 新增
        </el-button>
        <mytable :metaData="metadata" :tableData="tableData" :isLoading="isLoading"
                 @selection-change="handleSelectionChange">
          <template #default="{ index }">
            <el-button
                @click.native.prevent="editProject(index, tableData)"
                icon="el-icon-edit-outline"
                size="small"
                circle
            ></el-button>
            <el-button
                @click.native.prevent="deleteOne(index, tableData)"
                icon="el-icon-delete"
                size="small"
                circle
            ></el-button>
          </template>
        </mytable>
        <el-pagination
            style="padding: 15px"
            background
            layout="total, prev, pager, next, jumper"
            :total="total"
            @current-change="onPageChange">
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog title="引擎管理" :visible.sync="dialogVisible" width="410px" center @closed="dialogClose">
      <div class="dialogForm">
        <el-form :model="uploadForm" size="small" style="width:100%" :label-width="formLabelWidth">
          <el-form-item label="文件">
            <el-input v-model="uploadForm.filename" size="small" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="引擎">
            <el-input v-model="uploadForm.project" size="small" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="节点">
            <el-select size="small"
                       v-model="uploadForm.nodeAddress"
                       placeholder="请选择"
                       multiple
                       collapse-tags
                       style="width:100%"
            >
              <el-option
                  v-for="item in nodes"
                  :key="item.nodeIp"
                  :label="item.nodeName"
                  :value="item.nodeIp"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input size="small" v-model="uploadForm.remark" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-upload
            class="upload-demo"
            ref="upload"
            action="/api/project/file"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :with-credentials="true"
            accept=".egg"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button v-if="!isEdit" style="margin-left: 10px;" size="small" type="success" @click="deploy"
                     :loading="deploying">发布部署</el-button>
          <el-button v-if="isEdit" style="margin-left: 10px;" size="small" type="success"
                     @click="saveProject(0)">发布</el-button>
        </el-upload>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import projectApi from "../../js/api/projectApi"
import Vue from "vue";
import {mapState} from "vuex";
import {
  Select,
  Option,
  Input,
  Row,
  Col,
  Table,
  TableColumn,
  Button,
  Dialog,
  Form,
  FormItem,
  Upload,
  Message, MessageBox,
} from "element-ui";
import mytable from '../components/CustomTable'

Vue.use(Select);
Vue.use(Option);
Vue.use(Input);
Vue.use(Row);
Vue.use(Col);
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Button);
Vue.use(Dialog);
Vue.use(Form);
Vue.use(FormItem);
Vue.use(Upload);

export default {
  name: "ProjectManage",
  components: {
    'mytable': mytable
  },
  data() {
    return {
      isLoading: false,
      dialogVisible: false,
      multipleSelection: [],
      formLabelWidth: "60px",
      uploadForm: {
        filename: "",
        project: "",
        nodeAddress: [],
        remark: ''
      },
      total: 0,
      tableData: [],
      isEdit: false,
      editProjectIndex: -1,
      deploying: false
    };
  },
  computed: {
    metadata: function () {
      let temp = [];
      this.$store.state.metadata.metadata.forEach((element) => {
        if (element.tableName === "project") {
          let tempElement = {...element};
          tempElement.minWidth = tempElement.columnWidth + "%";
          tempElement.columnWidth = 0;
          temp.push(tempElement);
        }
      });
      return temp;
    },
    ...mapState({
      nodes: (state) => state.node.nodes,
    }),
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    editProject(index, tableData) {
      this.editProjectIndex = index;
      this.uploadForm.filename = "";
      this.uploadForm.project = tableData[Number(index)].projectName;
      this.uploadForm.nodeAddress = [tableData[Number(index)].ipPort];
      this.uploadForm.remark = tableData[Number(index)].remark;
      this.dialogVisible = true;
      this.isEdit = true;
    },
    deleteOne(index, tableData) {
      MessageBox.confirm("是否删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            const targets = [tableData[Number(index)]];
            projectApi.delProjects(targets, (response) => {
              if (response.data.code === 200) {
                Message({
                  message: "删除成功！",
                  type: "success",
                });
                this.queryProject()
              } else {
                Message({
                  message: "删除失败！",
                  type: "error",
                });
              }
            })
          })
          .catch(() => {
          });
    },
    add() {
      this.dialogVisible = true;
    },
    deploy() {
      this.deploying = true;
      let project = {
        address: this.uploadForm.nodeAddress.join(","),
        project: this.uploadForm.project,
        file: this.uploadForm.filename,
        remark: this.uploadForm.remark
      };
      if (this.uploadForm.filename.indexOf('egg') > 0) {
        projectApi.deployProjectEgg(project, (response) => {
          if (response.data.code === 200) {
            this.uploadForm.filename = '';
            this.saveProject(1);
          } else {
            Message({
              message: "部署失败！",
              type: "warning",
            });
          }
        })
      } else {
        projectApi.deployProjectZip(project, (response) => {
          if (response.data.code === 200) {
            this.uploadForm.filename = '';
            this.saveProject(1);
          } else {
            Message({
              message: "部署失败！",
              type: "warning",
            });
          }
        })
      }
    },
    uploadSuccess(response) {
      if (response.code === 200) {
        this.uploadForm.filename = response.content[0];
        this.uploadForm.project = response.content[1];
        Message({
          message: "文件上传成功！",
          type: "success",
        });
      } else {
        Message({
          message: "文件上传失败！",
          type: "warning",
        });
      }
    },
    onPageChange(index) {
      this.isLoading = true;
      projectApi.getProjects(index - 1, 10, (response) => {
        if (response.data.code === 200) {
          this.tableData = response.data.content;
          this.isLoading = false;
        } else {
          this.isLoading = false;
        }
      });
    },
    saveProject(code) {
      if (this.uploadForm.filename !== '') {
        console.log(this.uploadForm.filename);
        this.deploy();
      } else {
        let projects = [];
        if (code === 1) {
          this.uploadForm.nodeAddress.forEach(ipPort => {
            let nodeName = "";
            this.nodes.forEach(e => {
              if (e.nodeIp === ipPort) {
                nodeName = e.nodeName;
              }
            });
            projects.push({
              projectName: this.uploadForm.project,
              ipPort: ipPort,
              nodeName: nodeName,
              hostName: nodeName,
              remark: this.uploadForm.remark
            })
          })
        } else {
          this.tableData[this.editProjectIndex].remark = this.uploadForm.remark;
          projects.push(this.tableData[this.editProjectIndex])
        }
        projectApi.saveProject(projects, (response) => {
          if (response.data.code === 200) {
            Message({
              message: "保存成功！",
              type: "success",
            });
            this.deploying = false;
            this.dialogVisible = false;
            this.queryProject();
          }
        })
      }
    },
    queryProject() {
      this.isLoading = true;
      projectApi.getProjects(0, 10, (response) => {
        if (response.data.code === 200) {
          this.tableData = response.data.content;
          this.isLoading = false;
        } else {
          this.isLoading = false;
        }
      });
      projectApi.getProjectsCount((response) => {
        if (response.data.code === 200) {
          this.total = response.data.content;
        }
      })
    },
    dialogClose() {
      this.uploadForm.filename = "";
      this.uploadForm.project = "";
      this.uploadForm.nodeAddress = [];
      this.uploadForm.remark = '';
      this.isEdit = false;
    }
  },
  mounted: function () {
    this.queryProject();
  },
};
</script>

<style scoped>
.searchBar {
  padding-bottom: 20px;
  border-bottom: solid 1px lightgrey;
}

.el-pagination {
  display: flex;
  justify-content: center;
}

.dialogForm {
  display: flex;
  justify-content: center;
}

.el-table .cell,
.el-table th > .cell {
  text-align: center;
}
</style>

<style>
#projectManage .el-dialog__body {
  padding-bottom: 0px !important;
}

#projectManage .el-dialog {
  margin-top: 20vh !important;
}
</style>