<template>
  <div class="oo-page">
    <a @click="showSrcPanel=!showSrcPanel">
      <Icon type="md-add" v-if="!showSrcPanel"/>
      <Icon type="md-remove" v-if="showSrcPanel"/>
      追加服务器
    </a>
    <div class="oo-server seprate-server" v-show="showSrcPanel">
      <Divider />
      <div class="table-search">
        <Form :model="model" :label-width="90" ref="searchForm">
          <Row :gutter="15">
            <i-col span="6">
              <FormItem label="主机名：" prop="hostLike">
                <Input v-model="model.host" placeholder="请输入主机名" clearable></Input>
              </FormItem>
            </i-col>
            <i-col span="6">
              <FormItem label="IP地址：" prop="ipLike">
                <Input v-model="model.ip" placeholder="请输入IP地址" clearable></Input>
              </FormItem>
            </i-col>
            <i-col span="6">
              <FormItem label="操作系统：" prop="osTypeLike">
                <Input v-model="model.osType" placeholder="请输入OS类型" clearable></Input>
              </FormItem>
            </i-col>
            <i-col span="6">
              <div class="table-search-btns">
                <Button type="primary" icon="ios-search" @click="searchTable">搜索</Button>
              </div>
            </i-col>
          </Row>
        </Form>
      </div>
      <cs-dynamic-table ref="source" :prop="csSourceTable" :parent="this"></cs-dynamic-table>
    </div>

    <div class="seprate-server">
      <cs-dynamic-table ref="destination" :prop="csDestinationTable" :parent="this"></cs-dynamic-table>
    </div>

    <Modal
      v-model="pingFlag"
      title="通信检测"
      width="50"
      :mask-closable="false"
      @on-cancel="closeModal"
    >
      <ping-test @closeModal="closeModal" ref="ping"></ping-test>
      <div slot="footer"></div>
    </Modal>
    <Modal
      v-model="cmdFlag"
      :title="cmdTitle"
      width="80"
      :mask-closable="false"
      @on-cancel="closeModal"
    >
      <cmd-run @closeModal="closeModal" ref="cmd" @changeTitle="changeTitle"></cmd-run>
      <div slot="footer"></div>
    </Modal>
    <Row class="buttonDiv">
      <Button :loading="loading" @click="submitForm" type="primary">确&nbsp;&nbsp;定</Button>
      <Button @click="cancel">关&nbsp;&nbsp;闭</Button>
    </Row>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Emit } from "vue-property-decorator";
import PingTest from "./ping-test.vue";
import CmdRun from "@/views/daily-maintenance/command/command-run.vue";

@Component({
  components: {
    PingTest,
    CmdRun
  }
})
export default class Server extends Vue {
  @Prop() group!: any;
  private loading: boolean = false;
  private model: any = {
    host: "",
    ip: "",
    osType: ""
  };
  private cmdTitle: string = "批量执行";
  private showSrcPanel: boolean = false;
  private pingFlag: boolean = false;
  private addLog: Array<any> = [];
  private cmdFlag: boolean = false;
  private csSourceTable: any = {
    formWidth: 35,
    parentVm: this,
    dataSrc: this.$msPrefix.automation + "/api/v1/res/server/resList",
    delSrc: this.$msPrefix.automation + "/api/v1/data/delete/DBCollector/",
    batchDelUri: this.$msPrefix.automation + "/api/v1/data/batch/DBCollector",
    dataProp: "data.content",
    paginationByFront: false,
    dataFun:this.getCsSourceData,
    dataPropFront: "data",
    postMethod: true,
    pageInfo:{
      pageSize:5,
      pageSizes:[5,10,20,50,100]
    },
    pageableProp: {
      pageSize: "data.size",
      total: "data.totalElements",
      currentPage: "data.number"
    },
    disableFun:this.disableSourceTable,
    showIndex: true,
    emptyModel: {},
    actions: {
      //表头操作按钮
      replace: true,
      def: [
        {
          name: "追加",
          icon: "md-add",
          type: "primary",
          action: () => {
            this.addToDestion();
          }
        }
      ]
    },
    columns: [
      {
        type: "selection",
        width: 60,
        align: "center"
      },
      {
        key: "host",
        title: "主机名",
        align: "center",
        ellipsis: true,
        tooltip: true
      },
      {
        key: "ip",
        title: "IP地址",
        align: "center",
        minWidth: 80
      },
      {
        key: "osName",
        title: "操作系统",
        align: "center",
        ellipsis: true,
        tooltip: true
      },

      {
        key: "administrator",
        title: "联系人",
        align: "center"
      },
      {
        key: "description",
        title: "描述",
        align: "center"
      }
    ]
  };

  private csDestinationTable: any = {
    paginationByFront: true,
    dataPropFront: "data",
    formWidth: 35,
    parentVm: this,
    dataSrc: this.$msPrefix.automation + "/api/v1/data/list/res",
    delSrc: this.$msPrefix.automation + "/api/v1/data/delete/DBCollector/",
    batchDelUri: this.$msPrefix.automation + "/api/v1/data/batch/DBCollector",
    dataProp: "data.content",
    postMethod: true,
    pageableProp: {
      pageSize: "data.size",
      total: "data.totalElements",
      currentPage: "data.number"
    },
    showIndex: true,
    emptyModel: {},

    dataFun: this.getDyData,
    actions: {
      //表头操作按钮
      replace: true,
      def: [
        {
          name: "删除",
          icon: "md-trash",
          type: "error",
          action: () => {
            this.delete();
          }
        },
        {
          name: "还原追加",
          icon: "md-undo",
          type: "primary",
          action: () => {
            this.restore();
          }
        },
        // {
        //   name: "传文件",
        //   icon: "ios-cloud-upload",
        //   type: "primary",
        //   action: () => {
        //     //this.addToDestion();
        //   }
        // },
        {
          name: "通信检测",
          icon: "ios-ionic",
          type: "primary",
          action: () => {
            this.pingTest();
          }
        },
        // hx项目中隐藏这一操作
        // {
        //   name: "执行命令行",
        //   icon: "md-paper",
        //   type: "primary",
        //   action: () => {
        //     this.runCmd();
        //   }
        // }
      ]
    },
    columns: [
      {
        type: "selection",
        width: 60,
        align: "center"
      },
      {
        key: "host",
        title: "主机名",
        align: "center",
        ellipsis: true,
        tooltip: true
      },
      {
        key: "ip",
        title: "IP地址",
        align: "center",
        minWidth: 80
      },
      {
        key: "osName",
        title: "操作系统",
        align: "center",
        ellipsis: true,
        tooltip: true
      },
      {
        key: "administrator",
        title: "联系人",
        align: "center"
      },
      {
        key: "description",
        title: "描述",
        align: "center"
      }
    ]
  };

  getCsSourceData(){

  }

  getSourceTableData(){
    this.csSourceTable.dataFun=false;
    (this.$refs.source as any).getData();
  }

  disableSourceTable(data){
    data.forEach((item, index, list) => {
      list[index]._disabled =
        undefined == this.group.resSet.find(res => res.id == item.id)
          ? false
          : true;
      list[index]._checked =
        undefined == this.group.resSet.find(res => res.id == item.id)
          ? false
          : true;
    });
  (this.$refs.source as any).multipleSelection = [];
  ((this.$refs.destination as any).$refs.elTable as any).selectAll(false);
  }

  changeTitle(title) {
    this.cmdTitle = title;
  }

  closeModal() {
    ((this.$refs.ping as any).$refs.child as any).tableData = [];
    if ((this.$refs.cmd as any).hasRunResult) {
      ((this.$refs.cmd as any).$refs.result as any).clearTime();
      (this.$refs.cmd as any).hasRunResult = false;
    }
    this.pingFlag = !1;
    this.cmdFlag = !1;
  }
  @Emit("closeModal") close() {}
  cancel() {
    (this.$refs["searchForm"] as any).resetFields();
    this.csSourceTable.postData={};
    this.close();
  }
  @Emit("getData") getGroupData() {}
  refreshData() {
    this.getGroupData();
  }

  submitForm() {
    this.getApiData(
      "post",
      this.$msPrefix.automation + "/api/v1/data/save/resGroup",
      this.group,
      res => {
        this.$tools.message("success", "保存成功");
        this.refreshData();
        this.cancel();
      },
      err => {
        this.$tools.message("error", "保存出错");
      }
    );
  }
  //从所有列表追加到已选列表
  addToDestion() {
    var logIds: Array<any> = [];
    let items = (this.$refs.source as any).multipleSelection;
    console.log("items-----", items);
    console.log("this.group.resSet-----", this.group);
    if (items.length == 0) {
      this.$tools.message("warning", "请至少选择一条数据");
    } else {
      items.forEach(item => {
        if (!this.group.resSet.find(res => res.id == item.id)) {
          this.group.resSet.push(item);
          logIds.push(item.id);
        }
      });
      this.addLog.push(logIds);
      (this.$refs.source as any).$refs.elTable.selectAll(false);

      this.reFlowTable();
    }
  }
  //恢复追加
  restore() {
    if(this.addLog.length>0){
        let ids = this.addLog[this.addLog.length - 1];
        ids.forEach(id => {
          var splice_index = this.group.resSet.findIndex((item, index, arr) => {
            return item.id == id;
          });
          this.group.resSet.splice(splice_index, 1);
        });
        this.addLog.pop();

        this.reFlowTable();
    }else{
      this.$tools.message("warning", "当前并无追加记录或已恢复所有追加记录");
    }

  }
  //通信检测
  pingTest() {
    let items = (this.$refs.destination as any).multipleSelection;
    if (items.length > 0) {
      this.pingFlag = true;
      (this.$refs.ping as any).postTableData(items.map(item => item.id));
    } else {
      this.$tools.message("warning", "请先选择需要进行通信检测的数据");
    }
  }
  //批量执行
  runCmd() {
    let items = (this.$refs.destination as any).multipleSelection;
    if (items.length > 0) {
      this.cmdFlag = true;
      (this.$refs.cmd as any).postCmdData(items, false);
    } else {
      this.$tools.message("warning", "请先选择需要进行批量执行的数据");
    }
  }
  //从分组管理列表界面进来所需要的渲染所有列表数据
  renderSourceTable() {
    setTimeout(() => {
      var data = (this.$refs.source as any).tableData;
      this.disableSourceTable(data)
    }, 200);
  }
  //从已选删除数据
  delete() {
    let items = (this.$refs.destination as any).multipleSelection;
    if (items.length > 0) {
      this.$Modal.confirm({
        title: "提示",
        content: "确定删除所选择的选项?",
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          let ids = items.map(item => item.id);
          ids.forEach(id => {
            var splice_index = this.group.resSet.findIndex(
              (item, index, arr) => {
                return item.id == id;
              }
            );
            this.group.resSet.splice(splice_index, 1);
          });
          this.reFlowTable();
        },
        onCancel: () => {
          this.$tools.message("info", "已取消删除");
        }
      });
    } else {
      this.$tools.message("warning", "请先选择需要删除的选项");
    }
  }
  //重绘两个table
  reFlowTable() {
    this.csDestinationTable.paginationByFront = true;
    this.renderDestinationTableData(this.group.resSet);
    this.$nextTick(() => {
      this.renderSourceTable();
    });
  }

  getDyData() {}

  renderDestinationTableData(res) {
    (this.$refs.destination as any).tableData = [];
    (this.$refs.destination as any).afterGetData({ data: res });
  }

  getPostData() {}

  searchTable() {
    var data = _.cloneDeep(this.model);
    var postData = {};
    var keys = Object.keys(data);
    keys.forEach(item => {
      if ([0, false].includes(data[item]) || data[item] != "") {
        postData[item] = ["" + data[item]];
      }
    });
    this.csSourceTable.postData = postData;
    (this.$refs.source as any).getData();
  }

  resetSearch(){
    this.model = {
      host: "",
      ip: "",
      osType: ""
    };
     (this.$refs["searchForm"] as any).resetFields();
  }
}
</script>

