<template>
  <div class="table-form">
    <Row v-if="!hasRunResult">
      <Col span="14">
        <Form :model="model" :rules="rules" ref="action" :label-width="labelWidth">
          <Row :gutter="10">
            <Col span="8">
              <Form-item label="快捷方式" prop="type">
                <Select v-model="model.type" placeholder="请选择快捷方式" @on-change="changeType">
                  <Option :value="0">收藏命令</Option>
                  <Option :value="1">最近执行</Option>
                  <Option :value="2">频率最高</Option>
                </Select>
              </Form-item>
            </Col>
            <Col span="16">
              <Form-item label="快捷命令">
                <Select
                  v-model="fastCommand"
                  clearable="true"
                  placeholder="请选择快捷命令"
                  @on-change="changeCommand"
                >
                  <Option :value="item.command" v-for="item in commands">{{item.command}}</Option>
                </Select>
              </Form-item>
            </Col>
          </Row>
          <Row :gutter="10">
            <Col span="24">
              <Form-item label="任务名称" prop="name">
                <Input v-model="model.name" maxlength="32"  placeholder="请输入0~32位字符"></Input>
              </Form-item>
            </Col>
          </Row>

          <Row :gutter="10">
            <Col span="24">
              <Form-item label="命令类型" prop="commandType">
                <Select v-model="model.commandType" placeholder="请选择命令类型" v-validate:commandType.required.@change="rules">
                  <Option v-for="script in scriptType" :value="script.key" :key="script.key">{{script.value}}</Option>
                </Select>
              </Form-item>
            </Col>
          </Row>
          <Row :gutter="10">
            <Col span="24">
              <Form-item label="命令内容" prop="command" v-validate:command.required="rules">
                <Input
                  v-model="model.command"
                  type="textarea"
                  placeholder="请输入命令内容"
                  @on-change="enterText"
                ></Input>
              </Form-item>
            </Col>
          </Row>
          <Row :gutter="10">
            <Col span="6">
              <Form-item label="调度执行" prop="flag">
                <i-switch v-model="model.flag" />
              </Form-item>
            </Col>
            <Col span="18" v-if="model.flag">
              <Form-item label="" prop="cron" v-validate:command.required="rules">
                <Input v-model="model.cron"  placeholder="请输入命令内容" clearable>
                  <span slot="prepend" @click="cronClicked=!cronClicked">cron表达式生成器</span>
                </Input>
                
              </Form-item>
            </Col>
          </Row>
          <Row>
            <easy-cron
                  v-model="model.cron"
                  v-show="model.flag&&cronClicked"
                  :hideSecond="true"
                  :hideYear="true"
                  :isSaWeek="true"
                  :isSaCron="true"
                ></easy-cron>
          </Row>
          <Row v-if="showAlert">
            <Col>
              <Alert type="warning" show-icon>
                <template slot="desc">
                  <div v-if="!isValid">{{validErrorMsg}}</div>
                  <div v-if="isValid">
                    <p>&nbsp;</p>
                    <p>执行概览：</p>
                    <p>执行命令内容：{{model.command}}</p>
                    <p>执行方式：{{model.flag?"调度执行":"立即执行"}}</p>
                    <p v-if="model.flag">执行周期表达式：{{model.cron}}</p>
                    <p>目标主机数量：{{resInfoDataList.length}}</p>
                  </div>
                  <div v-if="isValid">
                    <Button :loading="loading" type="primary" @click="submitForm">执&nbsp;&nbsp;行</Button>
                  </div>
                </template>
              </Alert>
            </Col>
          </Row>
        </Form>
      </Col>
      <Col span="9" offset="1">
        <!-- <p>
          <strong>目标服务器({{resStat.total}}):</strong>
        </p>-->
        <div class="cmd-right-div">
          <div class="windows">{{resStat.win}}</div>
          <div class="unix">{{resStat.unix}}</div>
        </div>
        <List border size="small" split>
          <ListItem v-for="item in resInfoDataList" :key="item.id">{{item.host}}({{item.ip}})</ListItem>
        </List>
      </Col>
    </Row>
    <Row class="buttonDiv" v-if="!hasRunResult">
      <Button @click="prevStep" type="primary" v-if="showPrev">上&nbsp;一&nbsp;步</Button>

      <Button :loading="loading" type="primary" @click="preSubmit">校&nbsp;&nbsp;验</Button>

      <Button @click="cancel">关&nbsp;&nbsp;闭</Button>
    </Row>
    <cmd-run-result v-if="hasRunResult" ref="result" @closeModal="cancel"></cmd-run-result>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Emit } from "vue-property-decorator";
import CmdRunResult from "./cmd-run-result.vue";
import { State, Mutation, Getter } from "vuex-class";
@Component({
  components: {
    CmdRunResult
  }
})
export default class CmdRun extends Vue {
  @State private userInfo!: any;
  private loading: boolean = false;
  private model: any = { commandType: "SH", cron: "" };
  private rules: any = {};
  private labelWidth: number = 120;
  private commands: Array<any> = [];
  private cronClicked: boolean = false;
  private showPrev: boolean = false;
  private hasRunResult: boolean = false;
  private command: any = "";
  private fastCommand: any = "";
  private resInfoDataList: any = [];
  private isValid: boolean = false;
  private showAlert: boolean = false;
  private validErrorMsg: String = "";
  private resStat: any = {
    win: 0,
    unix: 0,
    total: 0
  };
  private scriptType: Array<any> = [];
  private scriptTypes:Array<any>=[
    {key:"SH",value:"Shell"},
    {key:"PY2",value:"Python"},
    {key:"BAT",value:"Windows BAT"},
    {key:"PS1",value:"Windows PowerShell"},
    {key:"VBS",value:"Windows VBScript"}
  ];

   computScriptType(){
    this.model.commandType=""
    var typeArr = _.cloneDeep(this.scriptTypes);
    if(this.resStat.win>0&&this.resStat.unix>0){
      return typeArr.splice(1,1);
    }else if(this.resStat.win>0){
      return typeArr.splice(1);
    }else{
      return typeArr.splice(0,2);
    }
  }

  enterText(val) {
    // this.fastCommand = null;
  }

  changeType(val) {
    //this.model.command = "";
    this.commands = [];
    if (val == 0) {
      this.postComondFavor();
    } else {
      if (val && val) {
        let mapUrl = { 1: "getRecentCommand", 2: "getFrequencyCommand" };
        this.getApiData(
          "get",
          this.$msPrefix.automation + "/api/v1/command/" + mapUrl[val],
          {},
          res => {
            let data: Array<any> = [];
            res.data.forEach(element => {
              data.push({ command: element });
            });
            this.commands = data;
            console.error("commands", this.commands);
          },
          err => {}
        );
      }
    }
  }

  changeCommand(val) {
    this.model.command = val;
  }

  postComondFavor() {
    var param = { userName: [localStorage.getItem("username")] };
    this.getApiData(
      "post",
      this.$msPrefix.automation + "/api/v1/data/list/commandFavor",
      param,
      res => {
        this.commands.splice(0, this.commands.length, ...res.data.content);
      },
      err => {}
    );
  }

  postCmdData(data, showPrev = false) {
    this.model.resList = [];
    this.resInfoDataList = data;
    this.resStat.total = data.length;
    //累加之前，先清零，避免数据缓存干扰
    this.resStat.win = 0;
    this.resStat.unix = 0;
    data.forEach(res => {
      this.model.resList.push(res.id);
      if (res.osType && res.osType.startsWith("Microsoft")) {
        this.resStat.win = this.resStat.win + 1;
      } else {
        this.resStat.unix = this.resStat.unix + 1;
      }
    });
    this.scriptType=this.computScriptType();
    console.log('dadjk',this.scriptType)
    this.showPrev = showPrev;
  }

  @Emit("back") prev() {}
  prevStep() {
    this.prev();
  }

  preSubmit() {
    (this.$refs["action"] as any).validate(valid => {
      this.isValid = valid;
      if (valid) {
        if (this.model.commandType == "SH" && this.resStat.win > 0) {
          //this.$tools.message("warning", "存在Shell命令类型不匹配的目标服务器");
          this.isValid = false;
          this.validErrorMsg = "存在Shell命令类型不匹配的目标服务器";
          return;
        }
        if (
          (this.model.commandType == "BAT" ||
            this.model.commandType == "PS1" ||
            this.model.commandType == "VBS") &&
          this.resStat.unix > 0
        ) {
          // this.$tools.message(
          //   "warning",
          //   "存在与Window命令类型不匹配的目标服务器"
          // );
          this.isValid = false;
          this.validErrorMsg = "存在与Window命令类型不匹配的目标服务器";
          return;
        }

        if (this.model.flag && (!this.model.cron||this.model.cron==="* * * * *")) {
          //this.$tools.message("warning", "请先输入cron表达式");
          this.isValid = false;
          this.validErrorMsg = "请 输入正确的cron表达式";
          return;
        }

        this.getApiData(
          "post",
          this.$msPrefix.automation + "/api/v1/commandBlack/test",
          { command: this.model.command },
          res => {
            if (!res.data) {
              this.isValid = false;
              this.validErrorMsg = "该命令为黑名单命令，不允许执行";
            }
          }
        );
      } else {
        this.validErrorMsg = "输入项目校验失败，请检查";
      }
    });
    this.model = _.cloneDeep(this.model);
    this.showAlert = true;
  }

  submitForm() {
    (this.$refs["action"] as any).validate(valid => {
      if (valid) {
        if (this.model.commandType == "SH" && this.resStat.win > 0) {
          this.$tools.message("warning", "存在Shell命令类型不匹配的目标服务器");
          return;
        }
        if (
          (this.model.commandType == "BAT" ||
            this.model.commandType == "PS1" ||
            this.model.commandType == "VBS") &&
          this.resStat.unix > 0
        ) {
          this.$tools.message(
            "warning",
            "存在与Window命令类型不匹配的目标服务器"
          );
          return;
        }

        if (this.model.flag && !this.model.cron) {
          this.$tools.message("warning", "请先输入cron表达式");
          return;
        }
        this.model.executeType = this.model.flag
          ? "RECURRING_EXE_TYPE"
          : "RUNNING_EXE_TYPE";
        this.getApiData(
          "post",
          this.$msPrefix.automation + "/api/v1/command/executeTask",
          this.model,
          res => {
            if (this.model.flag) {
              this.$tools.message("success", "调度任务下发成功");
              this.cancel();
            } else {
              this.$tools.message("success", "执行成功");
              let id = res.data.id;
              this.showResult(id);
            }
            // this.close();
          },
          err => {
            //this.$tools.message('error','执行失败');
          }
        );
      }
    });
  }

  showResult(id) {
    this.hasRunResult = !0;
    this.$nextTick(() => {
      this.setModalTitle("执行结果");
      (this.$refs.result as any).postTableData(id, this.model.command);
    });
  }

  @Emit("changeTitle") setModalTitle(title) {}

  @Emit("closeModal") cancel() {
    this.showAlert = false;
    if (!this.hasRunResult) {
      setTimeout(() => {
        (this.$refs["action"] as any).resetFields();
        this.command = "";
      }, 300);
    } else {
      this.hasRunResult = !1;
    }
  }
}
</script>

