<template>
  <div style="border: 1px solid #e7e7e7;" id="baseManage">
    <el-container>
      <el-aside width="280px" style="min-height:868px;max-height:868px;border-right:1px solid #DCDFE6">
        <h2 style="text-align: center; color: #8492a6; margin-top: 10px;">云服务器
          <el-dropdown>
            <span class="el-dropdown-link">
              <i class="el-icon-edit"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-plus" @click.native="addHost(0)">新增</el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" @click.native="showCheckBox = !showCheckBox">删除</el-dropdown-item>
              <el-divider></el-divider>
              <el-dropdown-item icon="el-icon-check" :disabled="!showCheckBox" @click.native="showCheckBox = false">完成
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </h2>
        <el-menu :default-active="defaultActiveMenu" style="border:0px">
          <el-menu-item v-for="(host, i) in hostList" :key="host.id" :index="String(i)" style="margin:0px;padding:0px"
                        @click="handle(i)">
            <span slot="title" style="font-size:16px;display:inline-block;width:80%">{{ host.hostName }}
              <div v-if="showCheckBox" @click="deleteHost(i)" style="position:absolute;right:10px;display:inline-block">
                <i class="el-icon-delete" style="color:#F56C6C;"></i>
              </div>
            </span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main style="text-align: left;padding:0px">
        <div style="margin: 10px 20px;">
          <!-- <div v-if="!showCheckBox">
             <el-button @click="addHost(0)" type="success" size="small" ><i class="el-icon-plus"></i>新增</el-button>
             <el-button @click="showCheckBox = !showCheckBox" type="danger" size="small" ><i class="el-icon-delete"></i>删除</el-button>
             <el-button @click="addHost(1)" type="primary" size="small" ><i class="el-icon-edit"></i>编辑</el-button>
           </div>
           <div v-if="showCheckBox">
             <el-button @click="showCheckBox = false" type="success" size="small" >完成</el-button>
           </div>-->
          <div style="text-align: right;">
            <i class="el-icon-edit" @click="addHost(1)" style="color: rgb(96, 98, 102);cursor: pointer;"></i>
          </div>
          <el-row :gutter="10" style="text-align: left;margin: 10px 0px;font-size: 14px;color: #606266;">
            <el-col :span="8">
              名称:&nbsp;&nbsp;{{ currentHost.hostName }}
            </el-col>
            <el-col :span="8">
              IP地址:&nbsp;&nbsp;{{ currentHost.ipPort }}
            </el-col>
            <el-col :span="8">
              物理地址:&nbsp;&nbsp;{{ currentHost.location }}
            </el-col>
          </el-row>
          <el-row :gutter="10" style="text-align: left;margin: 10px 0px;font-size: 14px;color: #606266;">
            <el-col :span="8">
              核心数:&nbsp;&nbsp;{{ currentHost.coreNum }}
            </el-col>
            <el-col :span="8">
              内存:&nbsp;&nbsp;{{ currentHost.memory }}
            </el-col>
            <el-col :span="8">
              存储:&nbsp;&nbsp;{{ currentHost.storage }}
            </el-col>
          </el-row>
          <el-row :gutter="10" style="text-align: left;margin: 10px 0px;font-size: 14px;color: #606266;">
            <el-col :span="8">
              操作系统:&nbsp;&nbsp;{{ currentHost.nodeSystem }}
            </el-col>
            <el-col :span="8">
              订购时间:&nbsp;&nbsp;{{ currentHost.subscribeDate }}
            </el-col>
            <el-col :span="8">
              到期时间:&nbsp;&nbsp;{{ currentHost.expireDate }}
            </el-col>
          </el-row>
        </div>
        <el-divider></el-divider>
        <div style="margin: 20px 20px 10px 20px">
          <el-button @click="addCrawlNode()" type="success" size="mini"><i class="el-icon-plus"></i> 新增</el-button>
          <el-button @click="deleteCrawlNode()" type="danger" size="mini"><i class="el-icon-delete"></i> 删除</el-button>
        </div>
        <mytable :metaData="metadata" :tableData="crawlNodes" :isLoading="isLoading" @selection-change="handleSelectionChangeOfCrawlNodes">
          <template #default="{ index }">
            <el-button
                @click.native.prevent="editCrawlNode(index)"
                icon="el-icon-edit-outline"
                size="small"
                circle
            ></el-button>
          </template>
        </mytable>
        <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :total="totalNodeCount"
            :hide-on-single-page="totalNodeCount <= 10"
            @current-change="onPageChange">
        </el-pagination>
      </el-main>
    </el-container>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px;margin-top: 20vh;" center>
      <div class="dialogForm">
        <el-form :model="hostForm" style="width:100%">
          <el-col :span="12">
            <el-form-item label="IP地址" :label-width="formLabelWidth">
              <el-input size="small" v-model="hostForm.ipPort" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主机名" :label-width="formLabelWidth">
              <el-input size="small" v-model="hostForm.hostName" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节点名" :label-width="formLabelWidth">
              <el-input size="small" v-model="hostForm.nodeName" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地理位置" :label-width="formLabelWidth">
              <el-input size="small" v-model="hostForm.location" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订阅时间" :label-width="formLabelWidth">
              <el-date-picker size="small" type="date" style="width:100%" placeholder="请选择日期"
                              v-model="hostForm.subscribeDate"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到期时间" :label-width="formLabelWidth">
              <el-date-picker size="small" type="date" style="width:100%" placeholder="请选择日期"
                              v-model="hostForm.expireDate"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 新加属性 -->
            <el-form-item label="核心数" :label-width="formLabelWidth">
              <el-input size="small" v-model="hostForm.coreNum" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内存" :label-width="formLabelWidth">
              <el-input size="small" v-model="hostForm.memory" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存储" :label-width="formLabelWidth">
              <el-input size="small" v-model="hostForm.storage" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作系统" :label-width="formLabelWidth">
              <el-input size="small" v-model="hostForm.nodeSystem" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitHostForm">提交</el-button>
        <el-button size="small" type="info" @click="cancel">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible2" width="410px" center>
      <div class="dialogForm">
        <el-form :model="nodeForm" style="width:100%" class="dialog">
          <el-form-item label="名称" :label-width="formLabelWidth">
            <el-input size="small" v-model="nodeForm.nodeName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="地址" :label-width="formLabelWidth">
            <el-input size="small" v-model="nodeForm.nodeIp" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="状态" :label-width="formLabelWidth">
            <el-radio-group v-model="nodeForm.nodeStatus" size="mini">
              <el-radio-button label="1">在线</el-radio-button>
              <el-radio-button label="0">离线</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="说明" :label-width="formLabelWidth">
            <el-input size="small" v-model="nodeForm.nodeDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button size="small" type="primary" @click="submitNodeForm">提交</el-button>
          <el-button size="small" type="info" @click="cancelNodeForm">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Vue from "vue";
import {mapActions, mapMutations} from "vuex";

import {
  Button,
  Col,
  DatePicker,
  Dialog,
  Form,
  FormItem,
  Input,
  Message,
  MessageBox,
  Option,
  Pagination,
  Row,
  Select
} from "element-ui";
import mytable from '../components/CustomTable'
import hostApi from '../../js/api/serverApi'
import crawlNodeApi from '../../js/api/crawlNodeApi'

Vue.use(Select);
Vue.use(Option);
Vue.use(Input);
Vue.use(DatePicker);
Vue.use(Row);
Vue.use(Col);
Vue.use(Button);
Vue.use(Dialog);
Vue.use(Form);
Vue.use(FormItem);
Vue.use(Pagination);

export default {
  name: "ServerManage",
  components: {
    'mytable': mytable
  },
  data() {
    return {
      isLoading: false,
      totalNodeCount: 10,
      dialogVisible: false,
      dialogVisible2: false,
      dialogTitle: "添加节点",
      formLabelWidth: "70px",
      showCheckBox: false,
      showEditBox: false,
      defaultActiveMenu: '0',
      hostForm: {
        id: "",
        ipPort: "",
        hostName: "",
        nodeName: "",
        location: "",
        subscribeDate: "",
        expireDate: "",
        status: "",
        pending: "",
        running: "",
        stop: "",
        //以下为服务器信息新增属性
        coreNum: "",
        memory: "",
        storage: "",
        nodeSystem: ""
      },
      nodeForm: {
        id: "",
        nodeName: "",
        nodeIp: "",
        nodeStatus: "",
        nodeDesc: ""
      },
      hostList: [],
      crawlNodes: [],
      timer: {},
      currentHost: {},
      checkedHosts: [],
      checkedNodes: []
    }
  },
  computed: {
    metadata: function () {
      let temp = [];
      this.$store.state.metadata.metadata.forEach(element => {
        if (element.tableName === 'crawl_node' && element.visible !== '0') {
          let tempElement = {...element};
          tempElement.minWidth = tempElement.columnWidth + "%";
          tempElement.columnWidth = 0;
          temp.push(tempElement);
        }
      });
      return temp;
    },
  },
  methods: {
    //新增方法
    //左侧服务列表项点击响应
    handle(i) {
      this.currentHost = this.hostList[i];
      this.defaultActiveMenu = String(i);
      this.queryCrawlNodesPageable(0, 10, this.currentHost.id);
      this.queryCrawlNodesCountOfHost(this.currentHost.id);
    },
    //格式化时间
    getFormateDate(millSeconds) {
      if (millSeconds === undefined || millSeconds.length === 0) {
        return "--";
      }
      let ct = new Date(millSeconds);
      let month = ct.getMonth() + 1;
      month = month > 9 ? month : '0' + month;
      let day = ct.getDate() > 9 ? ct.getDate() : '0' + ct.getDate();
      let hours = ct.getHours() > 9 ? ct.getHours() : '0' + ct.getHours();
      let minutes = ct.getMinutes() > 9 ? ct.getMinutes() : '0' + ct.getMinutes();
      let seconds = ct.getSeconds() > 9 ? ct.getSeconds() : '0' + ct.getSeconds();
      return ct.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    },
    getMillSeconds(fDate) {
      return new Date(fDate);
    },
    handleSelectionChangeOfCrawlNodes(val) {
      this.checkedNodes = val;
    },
    clearCrawlNodeForm() {
      return {
        id: "",
        nodeName: "",
        nodeIp: "",
        nodeStatus: "",
        nodeDesc: ""
      }
    },
    editCrawlNode(index) {
      this.nodeForm = this.crawlNodes[index];
      this.dialogTitle = "编辑采集节点"
      this.dialogVisible2 = true
    },
    addCrawlNode() {
      this.nodeForm = this.clearCrawlNodeForm()
      this.dialogTitle = "添加采集节点"
      this.dialogVisible2 = true
    },
    submitNodeForm() {
      if (this.nodeForm.id !== "") {
        //修改节点信息
        crawlNodeApi.updateCrawlNode(this.nodeForm, response => {
          if (response.data.code === 200) {
            Message({
              message: "更新成功！",
              type: "success"
            });
            this.queryCrawlNodesPageable(0, 10, this.currentHost.id);
            this.dialogVisible2 = false;
          } else {
            Message({
              message: "更新失败！",
              type: "error"
            });
          }
        })
      } else {
        this.nodeForm.hostId = this.currentHost.id;
        crawlNodeApi.saveCrawlNode(this.nodeForm, response => {
          if (response.data.code === 200) {
            Message({
              message: "添加成功！",
              type: "success"
            });
            this.queryCrawlNodesPageable(0, 10, this.currentHost.id);
            this.dialogVisible2 = false;
          } else {
            Message({
              message: "添加失败！",
              type: "error"
            });
          }
        })
      }
    },
    cancelNodeForm() {
      this.dialogVisible2 = false;
    },
    deleteCrawlNode() {
      let selection = this.checkedNodes;
      if (selection.length > 0) {
        let ids = []
        for (let k in selection) {
          ids.push(selection[k].id)
        }
        crawlNodeApi.delCrawlNodes(ids, (response) => {
          if (response.data.code === 200) {
            for (let i = 0; i < this.crawlNodes.length; i++) {
              for (let j = 0; j < selection.length; j++) {
                if (this.crawlNodes[i]['id'] === selection[j]['id']) {
                  this.crawlNodes.splice(i, 1)
                  i--;
                  break;
                }
              }
            }
            Message({
              message: "删除成功！",
              type: "success"
            });
          } else {
            Message({
              message: response.data.message,
              type: "warning"
            });
          }
        });
      }
    },
    //查找全部的采集节点信息
    queryCrawlNodes() {
      crawlNodeApi.queryAllCrawlNodes(response => {
        this.isLoading = true;
        if (response.data.code === 200) {
          this.crawlNodes = response.data.content
          this.isLoading = false;
        } else {
          this.isLoading = false;
        }
      })
    },
    //查找该host下的采集节点
    queryCrawlNodesPageable(page, size, hostid) {
      this.isLoading = true;
      crawlNodeApi.queryCrawlNodesPageable(page, size, hostid, (response) => {
        if (response.data.code === 200) {
          this.crawlNodes = response.data.content;
          this.isLoading = false;
        } else {
          this.isLoading = false;
        }
      })
    },
    queryCrawlNodesCountOfHost(hostid) {
      crawlNodeApi.queryCawlNodesCount(hostid, (response) => {
        this.isLoading = true;
        if (response.data.code === 200) {
          this.totalNodeCount = response.data.content;
          this.isLoading = false;
        } else {
          this.isLoading = false;
        }
      })
    },
    //以上为新增方法
    clearForm() {
      return {
        id: "",
        ipPort: "",
        hostName: "",
        nodeName: "",
        location: "",
        subscribeDate: "",
        expireDate: "",
        status: ""
      }
    },
    addHost(add) {
      this.hostForm = this.clearForm();
      if (add === 1) {
        this.hostForm = this.currentHost;
        this.dialogTitle = "修改节点";
      } else {
        this.dialogTitle = "添加节点";
      }
      this.dialogVisible = true;
    },
    cancel() {
      this.dialogVisible = false;
    },
    submitHostForm() {
      if (this.hostForm.subscribeDate === "") {
        this.hostForm.subscribeDate = new Date();
      }
      if (this.hostForm.expireDate === "") {
        this.hostForm.expireDate = new Date(new Date().getTime() + 1000 * 3600 * 24 * 30);
      }
      if (this.hostForm.id !== "") {
        this.hostForm.subscribeDate = this.getMillSeconds(this.hostForm.subscribeDate);
        this.hostForm.expireDate = this.getMillSeconds(this.hostForm.expireDate);
        hostApi.updateHost(this.hostForm, response => {
          if (response.data.code === 200) {
            Message({
              message: "修改成功！",
              type: "success"
            });
            this.hostForm.subscribeDate = this.getFormateDate(this.hostForm.subscribeDate);
            this.hostForm.expireDate = this.getFormateDate(this.hostForm.expireDate);
            this.currentHost = this.hostForm;
            this.dialogVisible = false;
          } else {
            Message({
              message: "修改失败！",
              type: "warning"
            });
          }
        })
      } else {
        hostApi.saveHost(this.hostForm, response => {
          if (response.data.code === 200) {
            Message({
              message: "保存成功！",
              type: "success"
            });
            this.hostList.push(response.data.content);
            this.dialogVisible = false;
          } else {
            Message({
              message: "保存失败！",
              type: "warning"
            });
          }
        })
      }
    },
    deleteHost(i) {
      event.stopPropagation();//edit by pangq@2021/2/5 阻止事件冒泡
      MessageBox.confirm('确认删除信息', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        hostApi.delHosts([this.hostList[i].id], response => {
          if (response.data.code === 200) {
            this.hostList.splice(i, 1);
            if (this.hostList.length > 0 && this.defaultActiveMenu === i)//edit by pangq@2021/2/5 删除选中的服务器后跳转到第一条
              this.handle(0);
            Message({
              message: '删除成功！',
              type: 'success'
            })
            if (this.hostList.length > 0)
              this.currentHost = this.hostList[this.hostList.length - 1];
          }
        })
      })
    },
    queryHosts() {
      hostApi.queryAllHost((response) => {
        if (response.data.code === 200) {
          this.hostList = response.data.content;
          for (let i in this.hostList) {
            this.hostList[i].subscribeDate = this.getFormateDate(this.hostList[i].subscribeDate);
            this.hostList[i].expireDate = this.getFormateDate(this.hostList[i].expireDate);
          }
          if (this.hostList.length > 0) {
            this.currentHost = response.data.content[0];
            this.queryCrawlNodesPageable(0, 10, response.data.content[0].id);
            this.queryCrawlNodesCountOfHost(response.data.content[0].id);
          }
        }
      })
    },
    onPageChange(index) {
      this.queryCrawlNodesPageable(index - 1, 10, this.currentHost.id);
    },
    queryNodesStatus() {
      crawlNodeApi.queryNodeStatus(this.crawlNodes, (response) => {
        this.isLoading = true;
        if (response.data.code === 200) {
          this.crawlNodes = response.data.content;
          this.isLoading = false;
        } else {
          this.isLoading = false;
        }
      })
    },
    ...mapActions({
      delNode: "node/delNodes",
      saveNode: "node/saveNode",
      updateNode: "node/updateNode"
    }),
    ...mapMutations({
      updateNodeMutations: 'node/updateNode'
    })
  },
  mounted: function () {
    this.queryHosts();
    // this.queryCrawlNodes();
    // this.queryNodesStatus();
    // this.timer = setInterval(() => {
    //   this.queryNodesStatus()
    // }, 1000 * 30);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>

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

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

.el-table .cell {
  text-align: center;
}

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


/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸,只在chrome下生效*/
::-webkit-scrollbar {
  width: 5px;
  height: 1px;
  background-color: #F5F5F5;
}

/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(161, 159, 159, 0.3);
  border-radius: 2px;
  background-color: #F5F5F5;
}

/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb {
  border-radius: 2px;
  -webkit-box-shadow: inset 0 0 6px rgba(145, 143, 143, 0.3);
  background-color: #a6a6a7;
}


.el-divider {
  margin: 0px;
}

.el-col-12, .dialog .el-form-item {
  padding-right: 10px;
}


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

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