<template>
  <el-dialog
    v-model="currentVisible"
    :title="currentMode === AddMode.ADD_TASK ? '新增' : '修改'"
    width="710"
    center
    align-center
    @close="handleClose"
    draggable
  >
    <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px">
      <el-form-item label="任务名称:" v-if="currentMode === AddMode.ADD_TASK" prop="taskName">
        <el-input v-model="ruleForm.taskName" placeholder="请输入任务名称" style="width: 90%" />
      </el-form-item>
      <el-form-item label="选择爬虫:" v-if="currentMode === AddMode.ADD_TASK" prop="spiderTypeValue">
        <el-select v-model="ruleForm.spiderTypeValue" placeholder="请选择爬虫" style="width: 90%">
          <el-option
            v-for="item in spiderTypeOptions"
            :key="item.spider"
            :label="item.spider"
            :value="item.spider"
            :id="item.spider"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行频率:">
        <!-- <Crontab v-model="ruleForm.cronExpression" style="width: 90%"/> -->
        <div class="gap-units">
          <div class="gap-unit">
            <el-input-number
              v-model="exGaps.day"
              class="gap-ipt"
              :min="0"
              :precision="0"
              size="small"
            ></el-input-number>
            <span class="unit-num">天</span>
          </div>
          <div class="gap-unit">
            <el-input-number
              v-model="exGaps.hour"
              class="gap-ipt"
              :min="0"
              :precision="0"
              size="small"
            ></el-input-number>
            <span class="unit-num">小时</span>
          </div>
          <div class="gap-unit">
            <el-input-number
              v-model="exGaps.minute"
              class="gap-ipt"
              :min="0"
              :precision="0"
              size="small"
            ></el-input-number>
            <span class="unit-num">分钟</span>
          </div>
          <div class="gap-unit">
            <el-input-number
              v-model="exGaps.second"
              class="gap-ipt"
              :min="0"
              :precision="2"
              size="small"
            ></el-input-number>
            <span class="unit-num">秒</span>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { watch } from "vue";
import { addSpiderTask } from "@/api/spiderTask";
import { AddMode } from "./enum";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { getSpiderList } from "@/api/system.ts";

interface RuleForm {
  taskName: string;
  spiderTypeValue: string;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref<RuleForm>({
  taskName: "",
  spiderTypeValue: "",
});
interface addDialogPropType {
  dialogVisible: boolean;
  mode: AddMode;
  jobId: string;
  exGap: number[];
  spiderType: string;
  options: string;
}
const props = defineProps<addDialogPropType>();
const rules = ref<FormRules<RuleForm>>({
  taskName: [
    { required: true, message: "请输入任务名称", trigger: "blur" },
    { min: 2, max: 50, message: "任务名称应在2-20个字符之间", trigger: "blur" },
  ],
  spiderTypeValue: [
    {
      required: true,
      message: "请选择所属爬虫",
      trigger: "change",
    },
  ],
});
// 向父组件传递dialog值
const emit = defineEmits(["update:dialogVisible", "confirm", "update:mode", "getTaskList"]);
// 组件的状态
const currentVisible = ref(props.dialogVisible);
const currentMode = ref(props.mode);
const spiderTypeOptions = ref();
const taskParams = ref({
  scrapyd_server_id: "1",
  schedule_type: "0",
  project: "spiders",
});

// 关闭的方法
const handleClose = () => {
  ruleForm.value.taskName = "";
  ruleForm.value.spiderTypeValue;
  ruleFormRef.value?.resetFields();
  currentVisible.value = false;
};

//间隔数据
const exGaps = reactive({
  second: 0,
  minute: 0,
  hour: 0,
  day: 0,
});

// 确定的方法
const handleConfirm = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid) => {
    //验证表单内容是否通过，通过继续执行
    if (valid) {
      if (currentMode.value === AddMode.ADD_TASK) {
        if (!checkExGap(exGaps)) return;
        await addSpiderTask({
          scrapyd_server_id: taskParams.value.scrapyd_server_id,
          schedule_type: taskParams.value.schedule_type,
          project: taskParams.value.project,
          spider: ruleForm.value.spiderTypeValue,
          options: JSON.stringify({ jobName: ruleForm.value.taskName }),
          interval: [exGaps.second, exGaps.minute, exGaps.hour, exGaps.day],
        });

        currentVisible.value = false;
        emit("getTaskList");
        ElMessage.success("添加成功");
      } else if (currentMode.value === AddMode.UPDATE_TASK) {
        if (!checkExGap(exGaps)) return;
        await addSpiderTask({
          scrapyd_server_id: taskParams.value.scrapyd_server_id,
          schedule_type: taskParams.value.schedule_type,
          project: taskParams.value.project,
          spider: props.spiderType,
          job_id: props.jobId,
          options: props.options,
          interval: [exGaps.second, exGaps.minute, exGaps.hour, exGaps.day],
        });
        currentVisible.value = false;
        emit("getTaskList");
        ElMessage.success("修改成功");
      }
    } else {
      console.log("校验不通过");
    }
    exGaps.second = 0;
    exGaps.minute = 0;
    exGaps.hour = 0;
    exGaps.day = 0;
  });
};

//校验设置的间隔是否合法
const checkExGap = (exGaps: any) => {
  if (exGaps.second < 5 && exGaps.minute <= 0 && exGaps.hour <= 0 && exGaps.day <= 0) {
    ElMessage.warning("间隔时间不能小于5秒");
    return false;
  } else {
    return true;
  }
};

const getData = async () => {
  const res = await getSpiderList({ scrapydServerId: "1", project: "spiders" });
  spiderTypeOptions.value = res.data;
};
// 监听props变化，同步给组件内部
watch(
  () => props.dialogVisible,
  (newVal) => {
    currentVisible.value = newVal;
  }
);

// 监听组件内部状态变化，同步给父组件，这样才能做到控制对话框组件的显隐
watch(
  () => currentVisible.value,
  (newVal) => {
    emit("update:dialogVisible", newVal);
  }
);

watch(
  () => props.mode,
  (newVal) => {
    currentMode.value = newVal;
  }
);

watch(
  () => currentMode.value,
  (newVal) => {
    emit("update:mode", newVal);
  }
);
watch(
  () => props.exGap,
  (newVal) => {
    exGaps.second = newVal[0] || 0;
    exGaps.minute = newVal[1] || 0;
    exGaps.hour = newVal[2] || 0;
    exGaps.day = newVal[3] || 0;
  },
  { immediate: true }
);
onMounted(() => {
  getData();
});
</script>

<style>
/* 修改弹出框样式 */
.el-dialog {
  background: transparent;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  color: #ffffff;

  .el-dialog__title {
    color: #ffffff;
  }

  .el-input__inner {
    color: #ffffff;
  }
}

/* 修改表单样式 */
.el-form {
  .el-form-item__label {
    color: #ffffff;
  }
}
</style>

<style scope>
.gap-unit {
  display: flex;
  gap: 2px;
  align-items: center;
  margin-right: 10px;
}
.unit-num {
  color: white;
}

.gap-units {
  display: flex;
}

.gap-ipt {
  width: 100px;
}
</style>
