<template>
  <div class="oo-page">
    <div class="oo-server">
      <h3 class="page-name" v-show="$customs.flag">{{title}}</h3>
      <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="请输入操作系统" 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="child" :prop="csTable" :parent="this">
        <template slot="form" scope="props">
          <model-form
            :model="props.obj"
            :action="props.action"
            :tableVm="props.tableVm"
            @closeModal="props.closeModal"
            :tableInfo="props.tableInfo"
            @group="addToGroup"
            ref="form"
          ></model-form>
        </template>
      </cs-dynamic-table>

      <Modal
        v-model="setAdminModalFlag"
        title="设置联系人"
        width="30"
        :mask-closable="false"
        @on-cancel="closeDialog"
      >
        <Select
          ref="adminSetter"
          v-model="currentAdmin"
          filterable
          allow-create
          @on-create="handleCreateAdmin"
          placeholder="请选择用户或输入联系人信息回车增加，最多输入32个字符"
        >
          <Option v-for="item in userList" :value="item.name" :key="item.username">{{ item.name }}</Option>
        </Select>
        <div slot="footer">
          <Button type="primary" @click="saveAdmin">确定</Button>
        </div>
      </Modal>

      <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>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { State, Mutation, Getter } from "vuex-class";
import ModelForm from "./group-form.vue";
import PingTest from "./ping-test.vue";
import CmdRun from "@/views/daily-maintenance/command/command-run.vue";
@Component({
  components: {
    ModelForm,
    PingTest,
    CmdRun
  }
})
export default class Server extends Vue {
  group!: any;
  resData: any = {
    id: "",
    name: "",
    resSet: ""
  };
  groupModel: any = { name: "" };
  title: any = "";
  private setAdminModalFlag: boolean = false;
  private currentAdmin: String = "";
  private model: any = {
    host: "",
    ip: "",
    osType: ""
  };
  private userList: Array<any> = [];
  private cmdTitle: string = "批量执行";
  private pingFlag: boolean = false;
  private cmdFlag: boolean = false;

  private csTable: 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",
    postMethod: true,
    pageableProp: {
      pageSize: "data.size",
      total: "data.totalElements",
      currentPage: "data.number"
    },
    showIndex: true,
    emptyModel: {},
    actions: {
      //表头操作按钮
      replace: true,
      def: [
        {
          name: "新建到组",
          icon: "md-add",
          type: "primary",
          isAdmin: true,
          action: () => {
            this.selectToGroup();
          }
        },
        {
          name: "设置联系人",
          icon: "ios-people",
          type: "primary",
          loading: false,
          action: () => {
            this.toSetAdmin();
          }
        },
        {
          name: "同步",
          icon: "ios-sync",
          type: "primary",
          loading: false,
          isAdmin: true,
          action: item => {
            this.sync(item);
          }
        },
        {
          name: "通信检测",
          icon: "ios-ionic",
          type: "primary",
          action: () => {
            this.pingTest();
          }
        },
           {
             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,
        sortable: "custom"
      },
      {
        key: "ip",
        title: "IP地址",
        align: "center",
        minWidth: 80,
        sortable: "custom"
      },
      {
        key: "osName",
        title: "操作系统",
        align: "center",
        tooltip: true,
        ellipsis: true,
        sortable: "custom",
        width: 250,
        resizable: false,
        // render: function(h, params) {
        //   let content =
        //     params.row.osName.length > 20
        //       ? params.row.osName.substring(0, 20) + "..."
        //       : params.row.osName;
        //   return h(
        //     "Tooltip",
        //     {
        //       props: {
        //         content: params.row.osName,
        //         placement: "bottom"
        //       }
        //     },
        //     [h("span", params.row.osName)]
        //   );
        // }
      },
      {
        key: "status",
        title: "状态",
        align: "center",
        ellipsis: true,
        tooltip: true,
        sortable: "custom",
        render: function(h, params) {
          let statusName = "正常";
          if (params.row.status == "UNREACHABLE") {
            statusName = "不可访问";
          }
          return h("span", statusName);
        }
      },

      {
        key: "administrator",
        title: "联系人",
        align: "center",
        sortable: "custom"
        // sortByFront:"true",
        // render:function(h,params){
        //     let adminName="";
        //     params.row.resExtList.forEach(ext=>{
        //         if(ext.extKey.extId.fieldCode=="administrator"){
        //             adminName=ext.value;
        //         }
        //     })
        //     return h("span",adminName)
        // }
      },
      {
        key: "description",
        title: "描述",
        align: "center",
        sortable: "custom"
      }
    ]
  };

  selectToGroup() {
    (this.$refs.child as any).formInfo.title = "新建到组";
    (this.$refs.child as any).formInfo.action = "add";
    let items = (this.$refs.child as any).multipleSelection;
    console.log("&&&&&", items);
    if (items.length == 0) {
      this.$tools.message("warning", "请至少选择一条记录!");
    } else {
      this.group = items;
      //this.addGroup();
      (this.$refs.child as any).dialogVisible = true;
     (this.$globalFun() as any).getMethod('show')
      
    }
  }

  addToGroup(data) {
    data.resSet = this.group;
    console.log("&*&***", data);
    this.getApiData(
      "post",
      this.$msPrefix.automation + "/api/v1/data/save/resGroup",
      data
    );
    (this.$refs.child as any).getData();
  }

  toSetAdmin() {
    let items = (this.$refs.child as any).multipleSelection;
    if (items.length == 0) {
      this.$tools.message("warning", "请至少选择一条记录!");
    } else {
      this.getExtDefList();
      this.setAdminModalFlag = true;
       (this.$globalFun() as any).getMethod('show')
    }
  }

  handleCreateAdmin(val) {
    if (val.length > 32) {
      this.$tools.message("warning", "不能超过32个字符");
      (this.$refs.adminSetter as any).setQuery("");
      return;
    }
    this.currentAdmin = val;
  }

  saveAdmin() {
    let items = (this.$refs.child as any).multipleSelection;
    let extInfos = [];
    if(this.currentAdmin){
    	  items.forEach(ele => {
      ele.administrator = this.currentAdmin;
      // let extInfo={
      //     extKey:{
      //         resId:ele.id,
      //         extId:{id:"1"}
      //     },
      //     value:this.currentAdmin
      //}
      // this.getApiData('post',this.$msPrefix.automation+'/api/v1/data/save/resExt',extInfo,res=>{
      //     if(res.rtnCode==0){
      //         this.searchTable();
      //         this.setAdminModalFlag=false;
      //     }else{
      //        this.$tools.message('error',res.msg)
      //        this.setAdminModalFlag=false;
      //     }
      // });
    });
    this.getApiData(
      "post",
      this.$msPrefix.automation + "/api/v1/data/batchSave/res",
      items,
      res => {
        if (res.rtnCode == 0) {
          this.searchTable();
          this.setAdminModalFlag = false;
          (this.$globalFun() as any).getMethod('close')
        } else {
          this.$tools.message("error", res.msg);
          this.setAdminModalFlag = false;
         (this.$globalFun() as any).getMethod('close')
        }
      }
    );
    }else{
    	 this.$tools.message("error", '请选择联系人');
    }
  
  }

  sync(item) {
    item.loading = true;
    this.getApiData(
      "get",
      this.$msPrefix.automation + "/api/v1/res/server/sync",
      {},
      res => {
        item.loading = false;
        (this.$refs.child as any).getData();
        this.$tools.message("success", "同步成功");
      },
      err => {}
    );
  }

  clickEvent(name: string, obj: any) {
    if (name == "delete") {
      (this.$refs.child as any).handleDelete(obj.id);
    } else {
      (this.$refs.child as any).formInfo.title =
        name == "update" ? "编辑" : "详情";
      (this.$refs.child as any).formInfo.action =
        name == "update" ? "update" : "detail";
      (this.$refs.child as any).formInfo.model = _.cloneDeep(obj);
      (this.$refs.child as any).dialogVisible = true;
       (this.$globalFun() as any).getMethod('close')
    }
  }

  getPostData() {
    var data = _.cloneDeep(this.model);
    var postData = {};
    this.filterData(postData, data);
    this.csTable.postData = postData;
  }
  filterData(postData, data) {
    var keys = Object.keys(data);
    keys.forEach(item => {
      if ([0, false].includes(data[item]) || (data[item] && data[item])) {
        postData[item] = ["" + data[item]];
      }
    });
  }

  searchTable() {
    this.getPostData();
    (this.$refs.child as any).getData();
  }

  getExtDefList() {
    this.getApiData(
      "get",
      this.$msPrefix.base + "/api/v1/data/all/user?size=1000",
      {},
      res => {
        this.userList = res.data.content;
      },
      err => {}
    );
  }

  closeModal() {
    (this.$refs.child as any).getData();
    ((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;
    } else {
      ((this.$refs.cmd as any).$refs["action"] as any).resetFields();
    }
    this.pingFlag = !1;
    this.cmdFlag = !1;
     (this.$globalFun() as any).getMethod('close')
  }
  closeDialog() {

  	 this.setAdminModalFlag = false;
  	 (this.$globalFun() as any).getMethod('close')
    
  }
  changeTitle(title) {
    this.cmdTitle = title;
  }

  //通信检测
  pingTest() {
    let items = (this.$refs.child as any).multipleSelection;
    if (items.length > 0) {
      this.pingFlag = true;
      (this.$refs.ping as any).postTableData(items);
      (this.$globalFun() as any).getMethod('show')
    } else {
      this.$tools.message("warning", "请先选择需要进行通信检测的数据");
    }
  }
  //批量执行
  runCmd() {
    let items = (this.$refs.child as any).multipleSelection;
    if (items.length > 0) {
      this.cmdFlag = true;
     (this.$globalFun() as any).getMethod('show')
      var data = items.map(item => item.id);
      console.log("hhh", items);
      (this.$refs.cmd as any).postCmdData(items, false);
    } else {
      this.$tools.message("warning", "请先选择需要进行批量执行的数据");
    }
  }

  mounted() {
   this.title = (this.$globalFun() as any).getMethod('title')
 }
 	created(){
    this.csTable.actions.def=(this.$globalFun() as any).getMethod('getServerAction',this.csTable.actions.def)
  }
}
</script>

