<template>
  <el-dialog
    v-model="visible"
    :title="type === 'edit' ? '修改' : '新增'"
    :before-close="fnClose"
  >
    <app-form-builder
      ref="formRef"
      v-model="form"
      :rules
      :options
      label-width="160px"
    >
    </app-form-builder>
    <template #footer>
      <el-button type="primary" @click="fnSubmit">提交</el-button>
      <el-button @click="fnClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import useForm from "@/hooks/useForm.js";
import { ref } from "vue";
import { debounce } from "throttle-debounce";
import { ElMessage } from "element-plus";
import AppFormBuilder from "@/components/form_builder/index.vue";
import {
  setScheduleAdd,
  setScheduleUpdate,
  getScheduleInfo,
} from "@/request/system_management.js";
const visible = defineModel("visible", { type: Boolean, required: true });
const props = defineProps({
  info: { type: Object, required: true },
  type: { type: String, required: true },
});
const emits = defineEmits(["getData"]);
const { formRef, validate, reset } = useForm();
const form = ref({
  beanName: "",
  chargeName: "",
  jobName: "",
  params: "",
  cronExpression: "",
  remark: "",
  status: 0,
});
const rules = {
  beanName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  jobName: [{ required: true, message: "任务名称不能为空", trigger: "blur" }],
  chargeName: [{ required: true, message: "负责人不能为空", trigger: "blur" }],
  cronExpression: [
    { required: true, message: "cron表达式不能为空", trigger: "blur" },
  ],
};
const options = [
  { key: "beanName", label: "bean名称" },
  { key: "jobName", label: "任务名称" },
  { key: "chargeName", label: "负责人" },
  { key: "params", label: "参数" },
  {
    key: "cronExpression",
    label: "cron表达式",
  },
  { key: "remark", label: "备注" },
];
const fnGetData = async () => {
  if (!props.info.id) return;
  if (visible.value) {
    const { schedule } = await getScheduleInfo({ jobId: props.info.id });
    form.value = schedule;
  }
};
fnGetData();
const fnSubmit = debounce(
  1000,
  async () => {
    await validate();
    !props.info.id
      ? await setScheduleAdd(form.value)
      : await setScheduleUpdate(form.value);

    ElMessage.success("操作成功");
    emits("getData");
    visible.value = false;
  },
  { atBegin: true }
);
const fnClose = () => {
  reset();
  visible.value = false;
};
</script>

<style scoped lang="scss"></style>
