<template>
  <div class="p-2">
    <el-row :gutter="20">
      <el-col :span="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="执行器" prop="jobGroup">
                  <el-select v-model="queryParams.jobGroup" placeholder="请选择执行器" clearable style="width: 200px" @change="handleJobGroupChange">
                    <el-option v-for="group in jobGroupOptions" :key="group.id" :label="group.title" :value="group.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="任务" prop="jobId">
                  <el-select v-model="queryParams.jobId" placeholder="请选择任务" clearable style="width: 200px">
                    <el-option v-for="job in jobOptions" :key="job.id" :label="job.jobDesc" :value="job.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="调度状态" prop="logStatus">
                  <el-select v-model="queryParams.logStatus" placeholder="调度状态" clearable>
                    <el-option label="成功" :value="1" />
                    <el-option label="失败" :value="2" />
                    <el-option label="进行中" :value="3" />
                  </el-select>
                </el-form-item>
                <el-form-item label="调度时间">
                  <el-date-picker
                    v-model="queryParams.filterTime"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    @change="handleTimeChange"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-dropdown @command="handleClearLog">
                  <el-button v-hasPermi="['xxljob:xxljoblog:remove']" type="danger" plain icon="Delete">
                    清理日志<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="1">清理一个月前</el-dropdown-item>
                      <el-dropdown-item command="2">清理三个月前</el-dropdown-item>
                      <el-dropdown-item command="3">清理六个月前</el-dropdown-item>
                      <el-dropdown-item command="4">清理一年前</el-dropdown-item>
                      <el-dropdown-item command="5" divided>清理一千条以前</el-dropdown-item>
                      <el-dropdown-item command="6">清理一万条以前</el-dropdown-item>
                      <el-dropdown-item command="7">清理三万条以前</el-dropdown-item>
                      <el-dropdown-item command="8">清理十万条以前</el-dropdown-item>
                      <el-dropdown-item command="9" divided>清理全部</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-col>
              <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
            </el-row>
          </template>
          <el-table v-loading="loading" :data="logList">
            <el-table-column label="日志ID" align="center" prop="id" width="80" />
            <el-table-column label="任务ID" align="center" prop="jobId" width="80" />
            <el-table-column label="执行器组ID" align="center" prop="jobGroup" width="100" />
            <el-table-column label="执行器地址" align="center" prop="executorAddress" width="180" show-overflow-tooltip />
            <el-table-column label="JobHandler" align="center" prop="executorHandler" width="120" show-overflow-tooltip />
            <el-table-column label="任务参数" align="center" prop="executorParam" width="120" show-overflow-tooltip />
            <el-table-column label="分片参数" align="center" prop="executorShardingParam" width="120" show-overflow-tooltip />
            <el-table-column label="失败重试次数" align="center" prop="executorFailRetryCount" width="120" />
            <el-table-column label="调度时间" align="center" prop="triggerTime" width="180">
              <template #default="scope">
                <span>{{ proxy.parseTime(scope.row.triggerTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="调度结果" align="center" width="120">
              <template #default="scope">
                <el-tag :type="getTriggerStatusType(scope.row.triggerCode)">
                  {{ getTriggerStatusText(scope.row.triggerCode) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="调度备注" align="center" prop="triggerMsg" width="150" show-overflow-tooltip />
            <el-table-column label="执行时间" align="center" prop="handleTime" width="180">
              <template #default="scope">
                <span v-if="scope.row.handleTime">{{ proxy.parseTime(scope.row.handleTime) }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="执行结果" align="center" width="120">
              <template #default="scope">
                <el-tag :type="getHandleStatusType(scope.row.handleCode)" v-if="scope.row.handleCode">
                  {{ getHandleStatusText(scope.row.handleCode) }}
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="执行备注" align="center" prop="handleMsg" width="150" show-overflow-tooltip />
            <el-table-column label="告警状态" align="center" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.alarmStatus === 0 ? 'success' : 'danger'">
                  {{ scope.row.alarmStatus === 0 ? '正常' : '告警' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="执行日志" placement="top">
                  <el-button link type="primary" icon="Document" @click="handleViewLog(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="终止任务" placement="top" v-if="isRunning(scope.row)">
                  <el-button v-hasPermi="['xxljob:xxljoblog:kill']" link type="danger" icon="Close" @click="handleKillJob(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="getList"
          />
        </el-card>

        <!-- 日志详情对话框 -->
        <job-log-detail v-model:visible="logDetailVisible" :log-id="currentLogId" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="JobLog" lang="ts">
import { listJobLog, clearJobLog, killJob, getJobsByGroup } from '@/api/xxljob/log';
import { listJobGroup } from '@/api/xxljob/job';
import { JobLogQuery, JobLogVO } from '@/api/xxljob/log/types';
import { JobGroupVO, JobInfoVO } from '@/api/xxljob/job/types';
import { ArrowDown } from '@element-plus/icons-vue';
import JobLogDetail from './logDetail.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const logList = ref<JobLogVO[]>([]);
const jobGroupOptions = ref<JobGroupVO[]>([]);
const jobOptions = ref<JobInfoVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const logDetailVisible = ref(false);
const currentLogId = ref<number | string>('');
const queryFormRef = ref<ElFormInstance>();

// 查询参数 - 根据 XxlJobLogBo 调整
const queryParams = reactive<JobLogQuery>({
  pageNum: 1,
  pageSize: 10,
  jobGroup: '',
  jobId: '',
  logStatus: '',
  filterTime: [],
  startTime: '',
  endTime: ''
});

/** 获取调度状态类型 */
const getTriggerStatusType = (code: number) => {
  if (code === 200) return 'success';
  if (code === 0) return 'info';
  return 'danger';
};

/** 获取调度状态文本 */
const getTriggerStatusText = (code: number) => {
  switch (code) {
    case 200:
      return '成功';
    case 0:
      return '等待';
    case 500:
      return '失败';
    default:
      return '异常';
  }
};

/** 获取执行状态类型 */
const getHandleStatusType = (code: number) => {
  if (code === 200) return 'success';
  if (code === 0) return 'warning';
  return 'danger';
};

/** 获取执行状态文本 */
const getHandleStatusText = (code: number) => {
  switch (code) {
    case 200:
      return '成功';
    case 0:
      return '进行中';
    case 500:
      return '失败';
    default:
      return '异常';
  }
};

/** 判断任务是否正在运行 */
const isRunning = (row: JobLogVO) => {
  return row.triggerCode === 200 && row.handleCode === 0;
};

/** 查询执行器组列表 */
const getJobGroupList = async () => {
  const res = await listJobGroup();
  jobGroupOptions.value = res.data;
};

/** 执行器变化时加载任务列表 */
const handleJobGroupChange = async (jobGroup: string | number) => {
  if (jobGroup) {
    const res = await getJobsByGroup(Number(jobGroup));
    jobOptions.value = res.data;
  } else {
    jobOptions.value = [];
  }
  queryParams.jobId = '';
};

/** 时间范围变化 */
const handleTimeChange = (times: string[]) => {
  if (times && times.length === 2) {
    queryParams.startTime = times[0];
    queryParams.endTime = times[1];
  } else {
    queryParams.startTime = '';
    queryParams.endTime = '';
  }
};

/** 查询日志列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listJobLog(queryParams);
    logList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  queryParams.filterTime = [];
  queryParams.startTime = '';
  queryParams.endTime = '';
  jobOptions.value = [];
  handleQuery();
};

/** 查看执行日志 */
const handleViewLog = (row: JobLogVO) => {
  currentLogId.value = row.id;
  logDetailVisible.value = true;
};

/** 终止任务 */
const handleKillJob = async (row: JobLogVO) => {
  await proxy?.$modal.confirm('确认要终止该运行中的任务吗？');
  await killJob(row.id);
  await getList();
  proxy?.$modal.msgSuccess('终止成功');
};

/** 清理日志 */
const handleClearLog = async (command: string) => {
  // 完善的类型映射
  const typeMap: Record<string, string> = {
    '1': '一个月前',
    '2': '三个月前',
    '3': '六个月前',
    '4': '一年前',
    '5': '一千条以前',
    '6': '一万条以前',
    '7': '三万条以前',
    '8': '十万条以前',
    '9': '全部'
  };

  // 检查是否需要选择执行器和任务
  if (!queryParams.jobGroup) {
    proxy?.$modal.msgWarning('请先选择执行器');
    return;
  }

  if (!queryParams.jobId) {
    proxy?.$modal.msgWarning('请先选择任务');
    return;
  }

  const typeName = typeMap[command];
  if (!typeName) {
    proxy?.$modal.msgError('无效的清理类型');
    return;
  }

  try {
    await proxy?.$modal.confirm(`确认要清理${typeName}的日志吗？`, '警告', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' });

    // 确保参数类型正确
    const clearParams = {
      jobGroup: Number(queryParams.jobGroup),
      jobId: Number(queryParams.jobId),
      type: Number(command)
    };

    await clearJobLog(clearParams.jobGroup, clearParams.jobId, clearParams.type);
    await getList();
    proxy?.$modal.msgSuccess('清理成功');
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('清理失败');
    }
  }
};

onMounted(() => {
  getJobGroupList();
  getList();
});
</script>
