<template>
  <el-drawer direction="btt" v-model="show" append-to-body size="800px">
    <template #header>
      <div style="display: flex; justify-content: space-between;">
        <div style="color: #333;">定时任务管理器</div>
        <div style="padding-right: 1em;"><el-button
            @click="proxy.$refs.addRef.open(taskList, { groupId })">新建任务</el-button>
        </div>
      </div>
    </template>
    <div style="display: grid; height: 100%; margin-top: -1em; grid-template-rows: 1fr 2em;">
      <div style="overflow: hidden;">
        <el-table :data="list" border stripe height="100%" v-loading="loading" row-key="id" lazy :load="loadChildren">
          <el-table-column label="任务名称" align="left">
            <template #default="{ row }">
              {{ taskList.find(a => a.id == row.taskId)?.name || '未知任务' }}
            </template>
          </el-table-column>
          <el-table-column label="表达式" align="center" width="120" prop="cron">
            <template #default="{ row }">
              <div v-if="row.cron">{{ row.cron }}</div>
              <div v-else>{{ row.pid ? '父任务触发' : '手动触发' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" width="140" prop="createTime">
          </el-table-column>
          <el-table-column label="激活" align="center" width="70">
            <template #default="{ row }">
              <el-switch v-model="row.enabled" @change="handleEnabled(row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200" align="center">
            <template #default="{ row }">
              <el-button-group>
                <el-button type="default" link @click="proxy.$refs.runRef.open(taskList, row);">运行</el-button>
                <el-button type="default" link @click="subCron(row);">子任务</el-button>
                <el-button type="primary" link @click="proxy.$refs.editRef.open(taskList, row);">修改</el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <pagination v-show="total > 0" :page-sizes="[10, 20, 50]" :total="total" v-model:page="query.current"
          v-model:limit="query.size" @pagination="loadPage" />
      </div>
    </div>

    <w-cron-add ref="addRef" @success="handleSearch" />
    <w-cron-edit ref="editRef" @success="handleSearch" />
    <w-cron-run ref="runRef" />

  </el-drawer>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';
import * as api from '../cron'
import { ElMessage, ElMessageBox } from 'element-plus';
import WCronAdd from './WCronAdd.vue';
import WCronEdit from './WCronEdit.vue';
import WCronRun from './WCronRun.vue';

const emit = defineEmits(["success"]);

const { proxy } = getCurrentInstance();



const subCron = (row) => {
  proxy.$refs.addRef.open(taskList.value, { pid: row.id })
}

const loadChildren = async (row, node, resolve) => {
  let r = await api.page({ current: 1, size: 999, pid: row.id, searchCount: false })
  if (r.data.records && r.data.records.length > 0) {
    resolve(r.data.records.map(a => { return { ...a, hasChildren: true, children: [] } }))
  } else {
    resolve([])
  }
}

const show = ref(false)

const taskList = ref([])
const groupId = ref(undefined)

const open = async (_taskList, _groupId) => {
  taskList.value = _taskList
  groupId.value = _groupId
  query.value.groupId = _groupId
  show.value = true
  init()
}

const handleStart = async (row) => {
  let r = await ElMessageBox.prompt("执行日期yyyyMMdd", "输入对话框")
  if (!/^\d{8}$/.test(r.value)) {
    ElMessage.error("日期格式不正确")
    return;
  }
  await api.start(row.id, '', 0, r.value)
  ElMessage.success('运行成功')

}

const handleEnabled = async (row) => {
  await api.update({ id: row.id, enabled: row.enabled })
}

// 搜索表单
const search = ref({});
// 查询参数
const query = ref({
  current: 1,
  size: 10,
  orderBy: 'id desc',
  pid$exists: false
});

// 列表数据
const list = ref([]);
// 总数据量
const total = ref(0);

// 加载状态
const loading = ref(true);

// 加载分页数据
const loadPage = async () => {
  loading.value = true;
  list.value = [];
  let r = await api.page(query.value);
  list.value = r.data?.records || [];
  list.value = list.value.map(a => { return { ...a, hasChildren: true, children: [] } })
  total.value = Number(r.data?.total || 0);
  loading.value = false;
}

// 执行搜索
const handleSearch = () => {
  query.value = { ...query.value, ...search.value };
  query.value.current = 1;
  loadPage();
}



const handleDelete = async (row) => {
  await ElMessageBox.confirm(`确定要删除这条记录吗?`);
  await api.remove(row.id);
  ElMessage.success("删除成功");
  loadPage();
}


const init = async () => {

  handleSearch();
}

defineExpose({ open });
</script>

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