<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="120" :rules="rules" ref="searchForm">
          <Row :gutter="15">
            <i-col span="6">
              <Form-item label="硬件厂商：" prop="vendor">
                <Select v-model="model.vendor" placeholder="请选择服务器厂商" clearable>
                  <Option v-for="item in vendorList" :value="item" :key="item">{{ item }}</Option>
                </Select>
              </Form-item>
            </i-col>
            <i-col span="6">
              <FormItem label="操作系统：" prop="os">
                <Select v-model="model.os" placeholder="请选择操作系统" clearable>
                  <Option v-for="item in osList" :value="item" :key="item">{{ item }}</Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col span="6">
              <FormItem label="管理IP：" prop="manageIpLike">
                <Input v-model="model.manageIpLike" placeholder="请输入管理IP" clearable></Input>
              </FormItem>
            </i-col>
            <i-col span="6">
              <FormItem label="主机名称：" prop="hostNameLike">
                <Input v-model="model.hostNameLike" placeholder="请输入主机名称" clearable></Input>
              </FormItem>
            </i-col>
          </Row>
          <br>
          <Row :gutter="15">
            <i-col span="6">
              <FormItem label="开始时间：" prop="startTime">
                <DatePicker
                  v-model="model.startTime"
                  format="yyyy-MM-dd HH:mm:ss"
                  type="datetimerange"
                  placeholder="请选择开始时间范围"
                  clearable
                ></DatePicker>
              </FormItem>
            </i-col>
            <i-col span="6">
              <FormItem label="结束时间：" prop="endTime">
                <DatePicker
                  v-model="model.endTime"
                  format="yyyy-MM-dd HH:mm:ss"
                  type="datetimerange"
                  placeholder="请选择结束时间范围"
                  clearable
                ></DatePicker>
              </FormItem>
            </i-col>
            <i-col span="6">
              <div class="table-search-btns">
                <Button type="primary" icon="ios-search" @click="searchTable">搜索</Button>
                <Button
                  type="primary"
                  icon="ios-refresh"
                  @click="resetSearch"
                  style="margin-left:10px"
                >重置</Button>
              </div>
            </i-col>
          </Row>
        </Form>
      </div>
      <cs-dynamic-table ref="child" :prop="csTable" :parent="this">
        <template slot="form">
          <select-mode @closeModal="closeSelectMode"  v-show="!$customs.flag"></select-mode>
          <select-mode-hisense @closeModal="closeSelectMode"  v-show="$customs.flag"></select-mode-hisense>
        </template>
      </cs-dynamic-table>
      <Modal
        v-model="modelFlag"
        title="结果明细"
        width="50"
        :mask-closable="false"
        @on-cancel="closeModel" 
      >
        <deploy-result ref="deployResult" @fill="fill"></deploy-result>
        <div slot="footer"></div>
      </Modal>

      <Modal
        v-model="knowledgeFlag"
        title="知识库"
        width="50"
        :mask-closable="false"
        @on-cancel="closeModel" 
      >
        <knowledge ref="knowledge" action="knowledge" @closeModal="closeModel"></knowledge>
        <div slot="footer"></div>
      </Modal>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import SelectMode from "./select-mode.vue";
import SelectModeHisense from "@/views/customs/hisense/select-mode.vue";
import Knowledge from "./knowledge.vue";

import DeployResult from "./deploy-result.vue";

import { formatDateTime } from "@/libs/util";

@Component({
  components: {
    SelectMode,
    DeployResult,
    Knowledge,
    SelectModeHisense
  }
})
export default class BareMachine extends Vue {
  modelFlag: boolean = false;
  knowledgeFlag: boolean = false;
  picker: any = "";
  rules: any = {};
  result: any = {};
  vendorList: Array<any> = [];
  osList: Array<any> = [];
  knowledge: any = {};
  title: any = "";

  private activeModel: any = {
    code: "",
    name: "",
    description: "",
    roleMenus: []
  };

  private model: any = {
    commandLike: "",
    timerange: "",
    status: ""
  };
  private statusMap: any = { "0": "执行中", "101": "成功", "-101": "失败" };

  starts = { a: "b" };
  private csTable: any = {
    formWidth: 85,
    parentVm: this,
    timeout: 30000,
    dataSrc:
      this.$msPrefix.automation + "/api/v1/data/list/bareMachineTaskEntity",
    delSrc:
      this.$msPrefix.automation + "/api/v1/data/delete/bareMachineTaskEntity/",
    batchDelUri:
      this.$msPrefix.automation + "/api/v1/data/batch/bareMachineTaskEntity",
    dataProp: "data.content",
    postMethod: true,
    pageableProp: {
      pageSize: "data.size",
      total: "data.totalElements",
      currentPage: "data.number"
    },
    order: "job.startTime,DESC",
    showIndex: true,
    emptyModel: {
      name: ""
    },
    actions: {
      //表头操作按钮
      replace: true,
      def: [
        {
          name: "新建裸机部署任务",
          icon: "md-add",
          type: "primary",
          action: () => {
            this.addModel();
          }
        },
        {
          name: "导出",
          icon: "ios-download-outline",
          type: "primary",
          action: () => {
            this.exportRecord();
          }
        }
      ]
    },
    columns: [
      {
        type: "selection",
        width: 60,
        align: "center"
      },
      {
        key: "taskName",
        title: "任务名称",
        align: "center",
        width: 200,
        resizable: true,
        ellipsis: true,
        tooltip: true,
        sortable: "custom"
      },
      {
        key: "config.vendor",
        title: "硬件厂商",
        align: "center",
        ellipsis: true,
        tooltip: true,
        sortable: "custom",
        width: 200,
        resizable: true,
        render: (h, params) => {
          let value = params.row.config.vendor;
          return h("span", value);
        }
      },
      {
        key: "config.model",
        title: "硬件型号",
        align: "center",
        ellipsis: true,
        tooltip: true,
        sortable: "custom",
        width: 200,
        resizable: true,
        render: (h, params) => {
          let value = params.row.config.model;
          return h("span", value);
        }
      },
      {
        key: "hostName",
        title: "主机名称",
        align: "center",
        ellipsis: true,
        tooltip: true,
        width: 200,
        resizable: true,
        sortable: "custom"
      },
      {
        key: "manageIp",
        title: "管理IP",
        align: "center",
        ellipsis: true,
        tooltip: true,
        width: 200,
        resizable: true,
        sortable: "custom"
      },
      {
        key: "config.os",
        title: "操作系统",
        align: "center",
        width: 200,
        resizable: true,
        ellipsis: true,
        tooltip: true,
        sortable: "custom",
        render: (h, params) => {
          let value = params.row.config.os;
          return h("span", value);
        }
      },
      {
        key: "config.type",
        title: "安装方式",
        align: "center",
        ellipsis: true,
        tooltip: true,
        width: 200,
        resizable: true,
        sortable: "custom",
        render: (h, params) => {
          let value = params.row.config.type;
          return h("span", value);
        }
      },
      {
        key: "job.startTime",
        title: "开始时间",
        align: "center",
        width: 200,
        resizable: true,
        render: (h, params) => {
          let value = params.row.job.startTime;
          return h("span", value);
        },
        tooltip: true,
        ellipsis: true,
        sortable: "custom"
      },
      {
        key: "job.endTime",
        title: "结束时间",
        align: "center",
        width: 200,
        resizable: true,
        ellipsis: true,
        tooltip: true,
        sortable: "custom",
        render: (h, params) => {
          let value = params.row.job.endTime;
          return h("span", value);
        }
      },
      {
        key: "status",
        title: "状态",
        align: "center",
        ellipsis: true,
        width: 200,
        resizable: true,
        tooltip: true,
        sortable: "custom",
        render: (h, params) => {
          let value = this.transform(params.row.job, params.row.status);
          return h("span", value);
        }
      },
      {
        title: "结果",
        key: "action",
        width: 200,
        fixed: "right",
        align: "center",
        render: (h, params) => {
          let menus = [
            {
              icon: "ios-eye",
              action: "detail",
              label: "明细",
              type: "primary"
            },
            {
              icon: "md-school",
              action: "knowledge",
              label: "知识",
              type: "primary"
            }
          ];
          let clickEvent = this.clickEvent;
          return h("div", [
            h("CsButton", {
              props: {
                actions: menus,
                click: clickEvent,
                data: params.row,
                size: "small",
                styleCss: "marginRight:10px",
                disabled: params.row._disabled
              }
            })
          ]);
        }
      }
    ]
  };
  clickEvent(name: string, obj: any) {
    let data = _.cloneDeep(obj);
    if (name == "detail") {
      this.picker.showDetail(data);
    } else if (name == "knowledge") {
      (this.$refs.knowledge as any).model = data;
      if (data.knowledge) {
        (this.$refs.knowledge as any).knowledge = data.knowledge;
      }
      (this.$refs.knowledge as any).getData();
      this.knowledgeFlag = true;
      //打开父页面的遮罩层
       (this.$globalFun() as any).getMethod('show');
    }
  }
  transform(job, obj) {
    var res;
    //整个job是否已被取消
    if (job.status == "102") {
      return "已取消";
    } else {
      switch (obj) {
        case "fail":
          res = "安装失败";
          break;
        case "success":
          res = "安装成功";
          break;
        default:
          res = "安装中";
      }
      return res;
    }
  }
  //退出页面需要清空掉定时器
  beforeRouteLeave(to, from, next) {
    clearInterval((this.$refs.child as any).timer);
    next();
  }

  mounted() {
    this.getColumnList("os");
    this.getColumnList("vendor");
    this.title = (this.$globalFun() as any).getMethod('title')

  }

  getColumnList(name) {
    this.getApiData(
      "get",
      this.$msPrefix.automation +
        "/api/v1/res/bareMachineConfig/findListByKey?type=" +
        name,
      {},
      res => {
        let list = this.camel(name, true) + "List";
        this[list] = res.data;
      }
    );
  }
  camel(str, firstUpper) {
    let ret = str.toLowerCase();
    ret = ret.replace(/_([\w+])/g, function(all, letter) {
      return letter.toUpperCase();
    });
    if (firstUpper) {
      ret = ret.replace(/\b(\w)(\w*)/g, function($0, $1, $2) {
        return $1.toUpperCase() + $2;
      });
    }
    return ret.charAt(0).toLowerCase() + ret.slice(1);
  }

  getPostData() {
    var data = _.cloneDeep(this.model);
    var postData: any = {};
    if (data.vendor) {
      data = JSON.parse(
        JSON.stringify(data).replace(/vendor/g, "config.vendor")
      );
    }
    this.filterData(postData, data);
    if (data.startTime[0] && data.startTime[1]) {
      postData["job.startTimeBetween"] = [
        formatDateTime(new Date(data.startTime[0]), "yyyy-MM-dd hh:mm:ss") +
          "," +
          formatDateTime(new Date(data.startTime[1]), "yyyy-MM-dd hh:mm:ss")
      ];
      delete postData.startTime;
    }
    if (data.endTime[0] && data.endTime[1]) {
      postData["job.endTimeBetween"] = [
        formatDateTime(new Date(data.endTime[0]), "yyyy-MM-dd hh:mm:ss") +
          "," +
          formatDateTime(new Date(data.endTime[1]), "yyyy-MM-dd hh:mm:ss")
      ];
      delete postData.endTime;
    }
    if (postData.os) {
      postData["config.os"] = postData.os;
      delete postData.os;
    }
    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]];
      }
    });
  }

  addModel() {
    this.getApiData(
      "get",
      this.$msPrefix.automation + "/api/v1/res/bareMachineTask/hasRunningTask",
      {},
      res => {
        if (res.data && res.data.length > 0) {
          this.$tools.message(
            "warning",
            "当前有裸机部署任务正在执行，请稍后！"
          );
        } else {
          (this.$refs.child as any).formInfo.title = "新建裸机部署任务";
          (this.$refs.child as any).formInfo.action = "save";
          (this.$refs.child as any).formInfo.model = {};
          (this.$refs.child as any).dialogVisible = true;
            (this.$globalFun() as any).getMethod('show')
        }
      }
    );
  }

  exportRecord() {
    this.download(
      this.$msPrefix.automation + "/api/v1/res/bareMachineTask/export/history",
      (this.$refs.child as any).multipleSelection,
      "裸机部署记录.xlsx"
    );
    (this.$refs.child as any).getData();
  }

  closeSelectMode() {
    (this.$refs.child as any).dialogVisible = false;
     (this.$globalFun() as any).getMethod('close');
  }

  closeModel() {
    this.knowledgeFlag = false;
    (this.$globalFun() as any).getMethod('close');
  }

  fill(picker: any) {
    this.picker = picker;
  }

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

  resetSearch() {
    (this.$refs.searchForm as any).resetFields();
  }
}
</script>
