<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" ref="searchForm">
          <Row :gutter="15">
            <i-col span="6">
              <FormItem label="操作类型:" prop="operatorType">
                <Select v-model="model.operatorType" clearable placeholder="请选择操作类型" @on-clear="filterScript" @on-change="filterScript">
                  <Option v-for="(item,i) in operateOptions" :value="item.value" :key="i" :label="item.label"></Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col span="6">
              <FormItem label="品种类型:" prop="kindType">
                <Select v-model="model.kindType" clearable placeholder="请选择品种类型" @on-clear="filterScript" @on-change="filterScript">
                  <Option v-for="(item, i) in varietyOptions" :value="item.value" :key="i" :label="item.label"></Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col span="6">
              <FormItem label="选择脚本:" prop="function">
                <Select v-model="script" clearable placeholder="请选择脚本" @on-change="searchTable">
                  <Option
                    v-for="item in scriptOptions"
                    :value="item.value"
                    :key="item"
                  >{{ item.name }}</Option>
                </Select>
              </FormItem>
            </i-col>
          </Row>
          <br>
        </Form>
      </div>
      <div class="i-table clearfix">
        <Row class="i-table-top-btns">
          <i-button type="success" @click="execute" icon="ios-arrow-dropright">执行</i-button>
        </Row>
        <Table
          ref="elTable"
          :border="true"
          :data="tableData"
          :show-header="true"
          highlight-row
          stripe
          :columns="columns"
        ></Table>
      </div>
      <Modal
        v-model="showhostMachine"
        title="选择主机"
        width="80"
        :mask-closable="false"
        @on-cancel="closeModel"
      >
        <server-selector :resSelectList="resList" @handleChange="handleResChange"></server-selector>
        <div slot="footer"></div>
        <Row class="buttonDiv" style="margin-top:15px;">
          <Button @click="closeModel" type="primary">取消</Button>
          <Button @click="sure" type="primary">确定</Button>
        </Row>
      </Modal>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import ServerSelector from "../../index/cmdb/server-selector.vue";
// import axios from 'axios'
@Component({
  components: {
    ServerSelector
  }
})
export default class LogView extends Vue {
  private title: any = "";
  script: any = "";
  scriptArr: any = [];
  private model: any = {
    operatorType: "",
    kindType: "",
    name: ""
  };
  currentChooseIndex: number = 0;
  showhostMachine: boolean = false;
  resList: any = [];
  tableDataResList: any = [];
  lastTableData: any = {
    host: "",
    status: ""
  };
  tableModel: any = {
    host: ""
  };
  tableRules: any = {
    host: [
      {
        required: true,
        message: "请输入主机名",
        trigger: "blur"
      }
    ]
  };
  columnOparateData: any = [
    {
      align: "center",
      title: " ",
      width: 80,
      resizeable: true,
      render: (h, params) => {
        return h("a", {
          style: {
            color: "green"
          },
          class:
            (this as any).tableData.length - 1 == params.index
              ? "ivu-icon ivu-icon-md-add"
              : "ivu-icon ivu-icon-md-remove",
          on: {
            click: e => {
              if ((this as any).tableData.length - 1 == params.index) {
                // 点击的是最后一行的加号 做增加操作
                this.addEmptyRow();
              } else {
                // 删除这一行数据
                this.removeRow(params.index);
              }
            }
          }
        });
      }
    },
    {
      type: "index",
      title: "编号",
      align: "center",
      width: 60,
      resizeable: true,
      ellipsis: true,
      tooltip: true
    },
    {
      key: "host",
      title: "主机名",
      align: "center",
      minWidth: 200,
      resizeable: true,
      ellipsis: true,
      tooltip: true,
      render: (h, params) => {
        // return h(
        //   "i-form",
        //   {
        //     props: {
        //       model: this.tableModel,
        //       rules: this.tableRules,
        //       ref: "form"
        //     }
        //   },
        //   [
        //     h(
        //       "form-item",
        //       {
        //         props: {
        //           prop: params.column.key,
        //           label: " "
        //         }
        //       },
        //       [
        //         h("i-input", {
        //           props: {
        //             placeholder: "请输入" + params.column.title,
        //             value: params.row.host,
        //             autosize: true
        //           },
        //           attrs: {
        //             id: "ags" + params.index //保证每个输入框的id唯一
        //           },
        //           on: {
        //             "on-focus": () => {
        //               this.$nextTick(() => {
        //                 document
        //                   .getElementById("ags" + params.index)
        //                   .childNodes.forEach(item => {
        //                     if (item.tagName == "INPUT") {
        //                       item.focus();
        //                     }
        //                   });
        //               });
        //             },
        //             "on-blur": event => {
        //               this.tableModel.host = event.target.value; //数据绑定
        //               params.row.host = event.target.value;
        //              (this as any).tableData[params.index] = params.row;
        //               this.input(event.target.value);
        //             }
        //           }
        //         })
        //       ]
        //     )
        //   ]
        // );
        return h("i-input", {
          props: {
            placeholder: "请选择" + params.column.title,
            value: params.row.host
          },
          on: {
            "on-focus": () => {
              this.$nextTick(() => {
                this.showDialog(params.index);
              });
            }
          }
        });
      }
    },
    {
      key: "status",
      title: "状态",
      align: "center",
      minWidth: 200,
      fixed: "right",
      resizeable: true,
      ellipsis: true,
      tooltip: true,
      render: (h, params) => {
        return h(
          "a",
          {
            style: {
              color:params.row.status == " " || params.row.status == undefined
                  ? "":params.row.status == 0
                  ? "#19be6b"
                  : "red"
            }
          },
          params.row.status == "" || params.row.status == undefined? " " : params.row.status == 0 ? '成功' : '失败'
        );
      }
    }
  ];
  tableData: any = [];
  columns: any = [];
  operateOptions: any = [{label: "白名单", value: "白名单"}, {label: "服务请求", value: "服务请求"}];
  varietyOptions: any = [{label: "系统", value: "系统"}, {label: "数据库", value: "数据库"}];
  scriptOptions: any = [];

  addEmptyRow() {
    this.tableData.push(this.lastTableData);
  }

  removeRow(index) {
    (this as any).tableData.splice(index, 1);
  }
  // input(val) {
  //   if (val) {
  //     this.$refs.form.validateField("host", err => {
  //       console.log(err);
  //     });
  //   }
  // }
  getTypeData() {
    this.getApiData(
      "post",
      this.$msPrefix.automation + "/api/v1/data/list/script?size=999999999&page=0",
      {},
      res => {
        if (res.data.content.length !== 0) {
          res.data.content.forEach(item => {
            this.scriptArr = this.scriptArr.concat(item)
          })
          this.scriptArr.forEach(item => {
            if (item.name) {
              this.scriptOptions.push({
                value: item.id,
                name: item.name
              });
            }
          });
        }
      }
    );
  }

  searchTable() {
    this.columns = [];
    this.columns = _.cloneDeep(this.columnOparateData)
    let id = this.script;
    this.scriptArr.forEach(item => {
      if ((item.id == this.script)) {
        this.model = item;
        if (item.scriptArgs.length !== 0) {
          let columnData;
          item.scriptArgs.forEach((arg, index) => {
            columnData = {
              key: arg.id,
              title: arg.nameZh,
              align: "center",
              minWidth: 200,
              resizeable: true,
              ellipsis: true,
              tooltip: true,
              render: (h, params) => {
                params.row[arg.id] = arg.value;
                this.tableData[params.index] = params.row;
                return h(
                  "Input",
                  {
                    props: {
                      placeholder: "请输入" + params.column.title,
                      value: arg.value
                    },
                    on: {
                      "on-change": e => {
                        params.row[arg.id] = e.target.value;
                        this.tableData[params.index] = params.row;
                      }
                    }
                  },
                  arg.value
                );
              }
            };
            this.columns.splice(this.columns.length - 1, 0, columnData);
          });
        }
      }
    });
  }
 
  filterScript (val) {
    if(this.scriptArr.length !== 0) {
      this.scriptOptions = []
      this.model.operatorType = this.model.operatorType == undefined? "" : this.model.operatorType
      this.model.kindType = this.model.kindType == undefined? "" : this.model.kindType
      this.scriptArr.forEach(item => {
        
        if(this.model.operatorType !== '' && this.model.kindType !== '' && this.model.operatorType == item.operatorType && this.model.kindType == item.kindType) {
          this.scriptOptions.push({
            value: item.id,
            name: item.name
          });
        } else if(this.model.operatorType !== '' && this.model.kindType == '' && this.model.operatorType == item.operatorType) {
          this.scriptOptions.push({
            value: item.id,
            name: item.name
          });
        } else if(this.model.operatorType == '' && this.model.kindType !== '' && this.model.kindType == item.kindType) {
          this.scriptOptions.push({
            value: item.id,
            name: item.name
          });
        } else if(this.model.operatorType == '' && this.model.kindType == '') {
          this.scriptOptions.push({
            value: item.id,
            name: item.name
          });
        }
      })
    }
  }
  execute() {
    let tableData = (this as any).tableData;
    for (var i = 0; i <= tableData.length; i++) {
      for (var key in tableData[i]) {
        if (
          key !== "status" &&
          key !== "_index" &&
          key !== "_rowKey" &&
          tableData[i][key] == ""
        ) {
          this.$tools.message("warning", "请完善参数值");
          return false;
        }
      }
    }
    if (!this.script) {
      this.$tools.message("warning", "请选择脚本");
      return false;
    }
    this.model.resources = [];
    this.tableDataResList.forEach(item => {
      this.model.resources.push(item[0]);
    });
    this.model.scriptDetails = [];
    this.tableData.forEach((item, index) => {
      var tableArgs = "";
      for (var key in item) {
        if (key !== "host" && key !== "_index" && key !== "_rowKey" && key !== "status") {
          tableArgs += item[key] + " ";
          this.model.scriptDetails[index] = {
            res: this.tableDataResList[index][0],
            value: tableArgs
          };
        }
      }
    });
    this.getApiData(
      "post",
      this.$msPrefix.automation + "/api/v1/script/start",
      this.model,
      res => {
        if(res.data.length !==0) {
          this.tableData.forEach(item => {
            item.status = res.data[0].status
          })
        }
      }
    );
  }
  showDialog(index) {
    this.currentChooseIndex = index;
    this.resList = this.tableDataResList[index];
    this.showhostMachine = true;
    (this.$globalFun() as any).getMethod("show");
  }
  closeModel() {
    this.showhostMachine = false;
    (this.$globalFun() as any).getMethod("close");
  }
  sure() {
    if (this.resList.length == 0) {
      this.$tools.message("warning", "请至少选择一个资源");
    } else {
      this.closeModel();
    }
  }
  handleResChange(res) {
    this.resList = res;
    var host = "";
    this.resList.forEach((item, index) => {
      host += this.resList.length == index + 1 ? item.host : item.host + ",";
    });
    var obj = {
      host: host,
      status: ''
    };
    this.tableDataResList.splice(this.currentChooseIndex, 0, res);
    this.tableData.splice(this.currentChooseIndex, 1, obj);
  }

  mounted() {
    this.getTypeData();
    this.title = (this.$globalFun() as any).getMethod("title");
    this.columns = _.cloneDeep(this.columnOparateData)
    this.tableData.push(this.lastTableData);
  }
}
</script>
