<template>
  <div class="xf-root">
    <div class="search-form">

      <el-select v-model="search.taskId" style="width: 10em; display: block;" clearable placeholder="任务">
        <el-option v-for="item in taskList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="search.ok" style="width: 6em; display: block;" clearable placeholder="成败">
        <el-option label="成功" :value="true" />
        <el-option label="失败" :value="false" />
      </el-select>
      <div style="width: 20em;"><el-date-picker v-model="daterange" value-format="YYYY-MM-DD" type="daterange"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" /></div>
      <el-button type="default" @click="handleSearch">搜索</el-button>
      <el-badge :value="cList.length" style="margin-left: auto; margin-right: 1em;">
        <el-button :disabled="cList.length == 0" type="primary" plain @click="cShow = true">运行中</el-button>
      </el-badge>
      <el-button type="primary" @click="proxy.$refs.cronListRef.open(taskList, query.groupId);">定时任务</el-button>
    </div>
    <el-table :data="list" border stripe height="100%" v-loading="loading">
      <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="left">
        <template #default="{ row }">
          <template v-if="row.ok">
            <el-popover placement="bottom" :width="800" trigger="hover">
              <template #reference>
                <el-button type="success" link>执行成功</el-button>
              </template>
              <div style="width: 100%; height: 400px; overflow: auto;">
                <pre>{{ row.ex }}</pre>
              </div>
            </el-popover>
          </template>
          <template v-else>
            <el-popover placement="bottom" :width="800" trigger="hover">
              <template #reference>
                <el-button type="danger" link>{{ row.msg || '未知异常' }}</el-button>
              </template>
              <div style="width: 100%; height: 400px; overflow: auto;">
                <pre>{{ row.ex }}</pre>
              </div>
            </el-popover>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="参数" align="center" width="100">
        <template #default="{ row }">
          <template v-if="!row.params">
            无
          </template>
          <template v-else>
            <el-popover placement="bottom" :width="300" trigger="hover">
              <template #reference>
                共{{ JSON.parse(row.params).length }}个参数
              </template>
              <div style="width: 100%; height: 200px; overflow: auto;">
                <pre>{{ JSON.stringify(JSON.parse(row.params), null, 2) }}</pre>
              </div>
            </el-popover>
          </template>
        </template>
      </el-table-column>



      <el-table-column label="启动时间" align="center" width="170" prop="startTime" />

      <el-table-column label="耗时" align="center" width="100">
        <template #default="{ row }">
          {{ times(row) }}
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :page-sizes="[10, 20, 50]" :total="total" v-model:page="query.current"
      v-model:limit="query.size" @pagination="loadPage" />

    <w-cron-list ref="cronListRef" />
    <el-drawer direction="rtl" size="40%" title="正在运行的任务" v-model="cShow">
      <el-collapse :modelValue="0" accordion>
        <el-collapse-item v-for="row in cList" :key="row.id">
          <template #title>
            <div style="display: grid; width: 100%; grid-template-columns: 2fr 1fr 1fr; ">
              <div style="font-weight: bold; text-align: left;">• {{ taskList.find(a => a.id == row.taskId)?.name ||
                '未知任务' }}</div>
              <div>{{ row.startTime.toDate("yyyy-MM-dd HH:mm:ss").format("HH:mm:ss") }}</div>
              <div style="display: flex; align-items: center; justify-content: center;">
                <div class="w-loading" style="margin-right: .5em;"></div> 运行中
              </div>
            </div>
          </template>
          <div style="width: 100%; height: 400px; overflow: auto;">
            <pre>{{ row.ex }}</pre>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-drawer>
  </div>
</template>
<script setup>
import WCronList from './components/WCronList.vue'
import { ref, getCurrentInstance, watch, onMounted, computed, onUnmounted } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'
import * as api from './cron'


const daterange = computed({
  get() {
    return search.value.beginDate ? [search.value.beginDate, search.value.endDate] : []
  },
  set(value) {
    if (value && value[0]) {
      search.value.beginDate = value[0];
      search.value.endDate = value[1];
    } else {
      search.value.beginDate = "";
      search.value.endDate = "";
    }
  }

})

const { proxy } = getCurrentInstance()

const times = (a) => ((a.endTime.toDate("yyyy-MM-dd HH:mm:ss") - a.startTime.toDate("yyyy-MM-dd HH:mm:ss")) / 1000).toTime()

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

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

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

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

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


const taskList = ref([])

const init = async () => {
  let r = await api.list(proxy.$route.query.group || 0)
  taskList.value = r.data

  query.value.groupId = proxy.$route.query.group || 0
  handleSearch()
}


const cList = ref([])
const cShow = ref(false)

watch(
  () => cList.value.length, () => {
    handleSearch();
    if (cList.value.length == 0) {
      cShow.value = false;
    }
  }
)



let timer = null;

onMounted(async () => {
  await proxy.$nextTick()
  await init()
  timer = window.setInterval(async () => {
    let r = await api.current(query.value.groupId)
    cList.value = r.data
  }, 100);
})

onUnmounted(() => {
  window.clearInterval(timer)
})


</script>
<style lang="scss" scoped>
.xf-root {
  padding: 1rem;

  .search-form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 0 0 .3rem 0;
    position: relative;

    &>* {
      margin: 0 .5rem .5rem 0;
      display: flex;
      align-items: center;
    }
  }

  .doing {
    line-height: 2;
  }
}
</style>