<template>
  <el-card>
    <!-- 筛选框 -->
    <el-form
      :model="form"
      ref="resetFormDataRef"
      style="margin-top: 50px"
      @keyup.enter.native="onSubmit"
    >
      <el-space :size="30">
        <el-form-item label="任务类别：" prop="leibie">
          <el-input
            placeholder="请输入任务类别"
            v-model="form.leibie"
          ></el-input>
        </el-form-item>
        <el-form-item label="任务状态：">
          <el-select
            v-model="form.region"
            placeholder="请选择任务状态"
            prop="region"
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onClear">重置</el-button>
        </el-form-item>
      </el-space>
    </el-form>
    <!-- 新增 -->
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="addForm">新增</el-button>
    </div>

    <!-- table框 -->
    <el-table :data="tableData" style="width: 100%" border stripe flexible>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        type="index"
        label="#"
        :index="indexMethod"
        align="center"
      />
      <el-table-column prop="jobClassName" label="任务类名" align="center" />
      <el-table-column
        prop="cronExpression"
        label="cron表达式"
        align="center"
      />
      <el-table-column prop="parameter" label="参数" align="center" />
      <el-table-column prop="description" label="描述" align="center" />
      <el-table-column
        prop="status"
        label="状态"
        width="100"
        align="center"
        :filters="[
          { text: '已启动', value: '1' },
          { text: '已暂停', value: '0' },
        ]"
        :filter-method="filterTag"
        filter-placement="bottom-end"
        :filter-multiple="false"
      >
        <template #default="scope">
          <el-tag
            :type="scope.row.status === 0 ? 'warning' : 'success'"
            disable-transitions
            >{{ scope.row.status === 0 ? "已暂停" : "已启动" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="operation"
        label="操作"
        align="center"
        width="150px"
      >
        <template #default="scope">
          <span
            class="el-dropdown-link"
            @click="handleNow(scope)"
            style="color: #409eff; cursor: pointer; margin-top: 2px"
            >启动</span
          >

          <el-divider direction="vertical" />
          <el-dropdown
            :hide-on-click="false"
            style="color: #409eff; cursor: pointer; margin-top: 2px"
          >
            <span class="el-dropdown-link">
              更多
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleEdit(scope)"
                  >编辑</el-dropdown-item
                >
                <el-dropdown-item @click="handleDelete(scope)"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <div class="demo-pagination-block" style="margin-top: 20px">
      <el-pagination
        v-model:currentPage="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30]"
        layout="->, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        hide-on-single-page
      />
    </div>

    <!-- 对话框区域 -->
    <el-dialog
      v-model="dialogVisible"
      :title="titleName"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :mode="taskForm"
        label-position="right"
        label-width="100px"
        style="padding: 5%"
      >
        <el-form-item
          label="任务类别"
          prop="jobClassName"
          :rules="[{ required: true, message: '请输入任务类别：' }]"
        >
          <el-input
            v-model="taskForm.jobClassName"
            placeholder="请输入任务类别："
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="cron表达式：" prop="cronExpression">
          <el-input
            v-model="taskForm.cronExpression"
            placeholder="* * * * * ? *"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="参数：" prop="parameter">
          <el-input
            type="textarea"
            v-model="taskForm.parameter"
            placeholder="请输入参数："
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="描述：" prop="description">
          <el-input
            type="textarea"
            v-model="taskForm.description"
            placeholder="请输入描述："
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-radio-group v-model="taskForm.status">
            <el-radio-button label="0">启动</el-radio-button>
            <el-radio-button label="1">暂停</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="onConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from "element-plus";
import {
  getQuartzJobList,
  addQuartzJob,
  putQuartzJob,
  deleteQuartzJob,
} from "@/services/api/systemApi/scheduledTask/scheduledTaskAPI";

// table的index列
const indexMethod = (index: number) => {
  index = 1;
  return index++;
};
const options = ref([
  { label: "全部", value: "0" },
  { label: "正常", value: "1" },
  { label: "停止", value: "2" },
]);

const tableData = ref([]);

const taskForm = ref({
  jobClassName: "",
  cronExpression: "",
  parameter: "",
  description: "",
  status: 0,
});

const total = ref(10);
const currentPage = ref(10);
const pageSize = ref(10);

// ref
const resetFormDataRef = ref<FormInstance>();
const form = reactive({
  region: "",
  leibie: "",
});

// 对话框
const dialogVisible = ref(false);
// 表单的标题
const titleName = ref("");
const editId = ref();
const onSubmit = () => {
  const { region, leibie } = form;
  console.log("查询" + region + "--" + leibie);
};

const init = () => {
  getQuartzJobList().then((res: any) => {
    tableData.value = res.data.records;
    console.log("定时任务列表", res);
  });
};
init();
// 重置按钮
const onClear = () => {
  // 清空数组
  resetFormDataRef.value?.resetFields();
};

const filterTag = (value: string, row: any) => {
  // return row.e === value
  console.log("prop:" + row.status + "true or false:" + value);
};
// 新增任务
const addForm = () => {
  titleName.value = "新增任务";
  dialogVisible.value = true;
};
const handleEdit = (scope: any) => {
  titleName.value = "编辑任务";
  editId.value = scope.row.id;
  dialogVisible.value = true;
};
// 确认按钮
const onConfirm = () => {
  if(!resetFormDataRef.value) return
  resetFormDataRef.value.validate((valid, fields) => {
    if (valid) {
      if (editId.value) {
        putQuartzJob(taskForm.value, editId.value).then((res: any) => {
          console.log(res);
        })
        console.log("编辑");
      } else {
        addQuartzJob(taskForm.value).then((res: any) => {
          console.log(res);
        })
        console.log("添加");
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const handleDelete = (res: any) => {
  ElMessageBox.confirm("确认删除？", "确认提醒", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage({ type: "success", message: "删除成功" });
    })
    .catch(() => {
      ElMessage({ type: "info", message: "取消删除" });
    });
  console.log("删除");
};
// 启动任务
const handleNow = (res: any) => {
  console.log("启动");
};
// 立即执行
// const restartNow = () => {
//   ElMessageBox.confirm("是否立即执行任务？", "确认提醒", {
//     confirmButtonText: "确认",
//     cancelButtonText: "取消",
//     type: "warning",
//   })
//     .then(() => {
//       ElMessage({ type: "success", message: "执行成功" });
//     })
//     .catch(() => {
//       ElMessage({ type: "info", message: "取消执行" });
//     });
// };
// 分页事件
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
};
// 关闭对话框
const handleClose = () => {
  titleName.value = "";
  dialogVisible.value = false;
  console.log("关闭对话框");
};
</script>

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