<template>
  <div class="page-wrapper equipment-add">
    <div class="page-container">
      <a-form-model
        ref="addForm"
        :model="addForm"
        :rules="rules"
        label-position="right"
        label-width="110px"
        class="addForm"
      >
        <a-collapse
          v-model="activeName"
          :bordered="false"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('BASE_INFO')">
            <a-row type="flex">
              <a-col :span="8">
                <!-- 执行器 -->
                <a-form-model-item
                  prop="jobGroup"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  :label="$t('EXECUTOR')"
                >
                  <a-select
                    v-model="addForm.jobGroup"
                    style="width: 100%"
                    allow-clear
                    :placeholder="$t('PLACEENTER')"
                  >
                    <a-select-option
                      v-for="item in jobGroupList"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.title }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <!-- 任务名称 -->
                <a-form-model-item
                  prop="jobDesc"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  :label="$t('TASK_NAME')"
                >
                  <a-input
                    v-model="addForm.jobDesc"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <!-- 路由策略 -->
                <a-form-model-item
                  prop="executorRouteStrategy"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  :label="$t('EXECTOR_ROUTE_STRATEGY')"
                >
                  <a-select
                    v-model="addForm.executorRouteStrategy"
                    style="width: 100%"
                    allow-clear
                    :placeholder="$t('PLACEENTER')"
                  >
                    <a-select-option
                      v-for="item in strategyList"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row type="flex">
              <!-- Cron -->
              <a-col :span="8">
                <a-form-model-item
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  prop="jobCron"
                  :label="$t('CRON')"
                >
                  <j-cron
                    ref="innerVueCron"
                    v-decorator="[
                      'cronExpression',
                      {
                        initialValue: '0/1 * * * * ?',
                      },
                    ]"
                    @change="changeCron"
                  ></j-cron>
                  <a-input
                    slot="reference"
                    v-model="addForm.jobCron"
                    placeholder="* * * * * ? *"
                    @click="cronPopover = true"
                  />
                </a-form-model-item>
              </a-col>
              <!--  阻塞处理-->
              <a-col :span="8">
                <a-form-model-item
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  prop="executorBlockStrategy"
                  :label="$t('BLOCK_HANDLE')"
                >
                  <a-select
                    v-model="addForm.executorBlockStrategy"
                    style="width: 100%"
                    allow-clear
                    :placeholder="$t('PLACEENTER')"
                  >
                    <a-select-option
                      v-for="item in blockStrategyList"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <!-- 报警邮件 -->
              <a-col :span="8">
                <a-form-model-item
                  prop="alarmEmail"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  :label="$t('ALARM_EMAIL')"
                >
                  <a-input
                    v-model="addForm.alarmEmail"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row type="flex">
              <!-- 失败重试次数 -->
              <a-col :span="8">
                <a-form-model-item
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  prop="executorFailRetryCount"
                  :label="$t('FAILED_RETRIES')"
                >
                  <a-input-number
                    v-model="addForm.executorFailRetryCount"
                    :min="0"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <!-- 超时时间(秒) -->
              <a-col :span="8">
                <a-form-model-item
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  prop="executorTimeout"
                  :label="$t('TIMEOUT_SECONDS')"
                >
                  <a-input-number
                    v-model="addForm.executorTimeout"
                    :min="0"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row type="flex">
              <a-col :span="8">
                <!-- 任务类型 -->
                <a-form-model-item
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  prop="glueType"
                  :label="$t('TASK_TYPE')"
                >
                  <a-select
                    v-model="addForm.glueType"
                    style="width: 100%"
                    allow-clear
                    :placeholder="$t('PLACEENTER')"
                    @change="glueTypeChange"
                  >
                    <a-select-option
                      v-for="item in glueTypeList"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <!-- JobHandler -->
              <a-col
                v-if="
                  addForm.glueType === 'JAVA' || addForm.glueType === 'DATAX'
                "
                :span="8"
              >
                <a-form-model-item
                  prop="executorHandler"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  :label="$t('JOB_HANDLER')"
                >
                  <a-input
                    v-model="addForm.executorHandler"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
              <!-- JVM启动参数 -->
              <a-col v-if="addForm.glueType === 'DATAX'" :span="8">
                <a-form-model-item
                  prop="jvmParam"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 16 }"
                  :label="$t('JVM_PARAM')"
                >
                  <a-input
                    v-model="addForm.jvmParam"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-model-item
                  :label="$t('REMARK')"
                  :label-col="{ span: 2 }"
                  :wrapper-col="{ span: 20 }"
                  prop="glueRemark"
                >
                  <a-input
                    v-model="addForm.glueRemark"
                    type="textarea"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <codemirror
              v-if="addForm.glueType === 'DATAX'"
              id="codemirror-code"
              v-model="addForm.jobJson"
              class="codemirror"
              :options="cmOption"
            />
            <codemirror
              v-else
              id="codemirror-code"
              v-model="addForm.glueSource"
              class="codemirror"
              :options="cmOption"
            />
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <a-button type="primary" @click="confirm">
        <Icon type="icon-cur-save_1" :size="18" />
        {{ $t("SAVE") }}
      </a-button>
      <a-button @click="cancel">
        <Icon type="icon-dir-f-rollback" :size="18" />
        {{ $t("CANCEL") }}
      </a-button>
    </div>
  </div>
</template>

<script>
import { codemirror } from "vue-codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/rubyblue.css";
import { Icon } from "@mega-design/ui-vue";
import JCron from "@/components/model/JCron.vue";

export default {
  components: {
    codemirror,
    JCron,
    Icon,
  },
  data() {
    return {
      activeName: "a",
      jobCron: "",
      cronPopover: false,
      addForm: {
        id: "",
        jobGroup: "", // 执行器主键ID
        jobDesc: "", // 任务描述
        executorRouteStrategy: "", // 	执行器路由策略
        jobCron: "", // 任务执行CRON表达式
        executorBlockStrategy: "", // 阻塞处理策略
        alarmEmail: "", // 报警邮件
        glueType: "", // 任务类型
        executorHandler: "", // 执行器，任务Handler名称
        executorFailRetryCount: 1, // 	失败重试次数
        executorTimeout: 1, // 任务执行超时时间，单位秒
        jvmParam: "", // 	JVM启动参数
        jobJson: "", // DATAX运行脚本
        glueSource: "", // GLUE源代码
        executorParam: "", // 执行器，任务参数
        glueRemark: "", // GLUE备注
      },
      cmOption: {
        tabSize: 2,
        styleActiveLine: true,
        lineNumbers: true,
        line: true,
        mode: {
          name: "javascript",
          json: true,
        },
        theme: "rubyblue",
      },
      jobGroupList: [],
      eqpStatusList: [],
      eqpTypeList: [],
      strategyList: [],
      blockStrategyList: [],
      glueTypeList: [],
    };
  },
  computed: {
    rules() {
      return {
        jobGroup: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        jobDesc: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        executorRouteStrategy: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        jobCron: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        executorBlockStrategy: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        glueType: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        executorHandler: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  watch: {
    "addForm.jobCron": function (val) {
      if (val) {
        this.$refs.addForm.clearValidate(["jobCron"]);
      }
    },
  },
  mounted() {
    this.initData();
    // 路由策略
    this.getDictByCode(`DIC:CORE:JOB_ROUTING_STRATEGY`).then((res) => {
      this.strategyList = res.data.data;
    });
    this.getDictByCode(`DIC:CORE:JOB_BLOCKING_STRATEGY`).then((res) => {
      this.blockStrategyList = res.data.data;
    });
    this.getDictByCode(`DIC:CORE:JOB_TASK_TYPE`).then((res) => {
      this.glueTypeList = res.data.data;
    });
  },
  methods: {
    glueTypeChange(val) {
      if (val === "DATAX") {
        this.$set(this.addForm, "executorHandler", "executorJobHandler");
      } else {
        this.$set(this.addForm, "executorHandler", "");
      }
    },
    initData() {
      if (this.$route.query.id) {
        this.$axios
          .get(`/job-server/api/job/${this.$route.query.id}`)
          .then((res) => {
            this.addForm = res.data.data;
          });
      }
      // 获取任务类型
      this.$axios.get(`/job-server/api/job-group/list`).then((res) => {
        res.data.data.forEach((element) => {
          // eslint-disable-next-line
          element.id = element.id.toString();
        });
        this.jobGroupList = res.data.data;
      });
    },
    cancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/upms/system/job/task" },
        vm: this,
      });
    },
    // cron 表达式
    changeCron(val) {
      this.$set(this.addForm, "jobCron", val);
    },
    confirm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (this.addForm.glueType !== "JAVA") {
            if (!this.addForm.jobJson && !this.addForm.glueSource) {
              this.$message.error(this.$t("PLEASE_ENTER_THE_SCRIPT"));
              return;
            }
          }
          const isjson =
            typeof this.addForm.jobJson === "object" &&
            Object.prototype.toString
              .call(this.addForm.jobJson)
              .toLowerCase() === "[object object]" &&
            !this.addForm.jobJson.length;
          if (this.addForm.jobJson && !isjson) {
            this.addForm.jobJson = JSON.stringify(
              JSON.parse(this.addForm.jobJson),
              null,
              "\t"
            );
          }
          this.$axios.post(`/job-server/api/job`, this.addForm).then((res) => {
            this.$message.success(this.$t("ADD_SUCCESS"));
            this.$store.dispatch("tagsView/jumpBeforeView", {
              to: { path: "/upms/system/job/task" },
              vm: this,
            });
          });
        } else {
          this.$message.error(this.$t("REQUIRED_INFO"));
        }
      });
    },
  },
};
</script>
