<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">
                    <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="jobDesc">
                  <el-input v-model="queryParams.jobDesc" placeholder="请输入任务描述" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="负责人" prop="author">
                  <el-input v-model="queryParams.author" placeholder="请输入负责人" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="任务状态" prop="triggerStatus">
                  <el-select v-model="queryParams.triggerStatus" placeholder="任务状态" clearable>
                    <el-option label="运行中" value="1" />
                    <el-option label="已停止" value="0" />
                  </el-select>
                </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-button v-hasPermi="['xxljob:jobinfo:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['xxljob:jobinfo:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                  >修改</el-button
                >
              </el-col>
              <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
            </el-row>
          </template>
          <el-table v-loading="loading" :data="jobList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="任务ID" align="center" prop="id" width="80" />
            <el-table-column label="任务描述" align="center" width="260" prop="jobDesc" show-overflow-tooltip />
            <el-table-column label="执行器" align="center" prop="jobGroup" width="120">
              <template #default="scope">
                {{ getJobGroupName(scope.row.jobGroup) }}
              </template>
            </el-table-column>
            <el-table-column label="JobHandler" align="center" prop="executorHandler" width="150" show-overflow-tooltip />
            <el-table-column label="负责人" align="center" prop="author" width="100" />
            <el-table-column label="调度配置" align="center" width="180" show-overflow-tooltip>
              <template #default="scope">
                <div>
                  <el-tag size="small" :type="scope.row.scheduleType === 'CRON' ? 'primary' : 'success'">
                    {{ scope.row.scheduleType === 'CRON' ? 'CRON' : '固定速度' }}
                  </el-tag>
                </div>
                <div v-if="scope.row.scheduleConf" class="mt-1">
                  <el-text size="small" type="info">{{ scope.row.scheduleConf }}</el-text>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="运行状态" align="center" prop="triggerStatus" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.triggerStatus === 1 ? 'success' : 'danger'">
                  {{ scope.row.triggerStatus === 1 ? '运行中' : '已停止' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="上次调度时间" align="center" prop="triggerLastTime" width="180">
              <template #default="scope">
                <span v-if="scope.row.triggerLastTime > 0">{{ proxy.parseTime(scope.row.triggerLastTime) }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="下次调度时间" align="center" prop="triggerNextTime" width="180">
              <template #default="scope">
                <span v-if="scope.row.triggerNextTime > 0">{{ proxy.parseTime(scope.row.triggerNextTime) }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip v-if="scope.row.triggerStatus === 0" content="启动" placement="top">
                  <el-button v-hasPermi="['xxljob:jobinfo:start']" link type="success" icon="VideoPlay" @click="handleStart(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip v-if="scope.row.triggerStatus === 1" content="停止" placement="top">
                  <el-button v-hasPermi="['xxljob:jobinfo:stop']" link type="warning" icon="VideoPause" @click="handleStop(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="执行一次" placement="top">
                  <el-button v-hasPermi="['xxljob:jobinfo:trigger']" link type="primary" icon="CaretRight" @click="handleTrigger(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top">
                  <el-button v-hasPermi="['xxljob:jobinfo:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button v-hasPermi="['xxljob:jobinfo:remove']" link type="primary" icon="Delete" @click="handleDelete(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-form v-model:visible="formVisible" :edit-type="editType" :row-data="currentRow" @save="handleSave"> </job-form>

        <!-- 执行一次对话框 -->
        <el-dialog v-model="triggerDialogVisible" title="执行一次" width="600px" append-to-body>
          <el-form ref="triggerFormRef" :model="triggerForm" :rules="triggerRules" label-width="100px">
            <el-form-item label="任务参数" prop="executorParam">
              <el-input v-model="triggerForm.executorParam" type="textarea" :rows="4" placeholder="请输入任务参数" />
              <div class="param-tips">
                <el-text type="info" size="small"> 任务参数建议使用JSON格式，例如：{"key1":"value1","key2":"value2"} </el-text>
              </div>
            </el-form-item>
            <el-form-item label="机器地址" prop="addressList">
              <el-input
                v-model="triggerForm.addressList"
                type="textarea"
                :rows="2"
                placeholder="请输入本次执行的机器地址，为空则从执行器获取，如：http://192.168.1.100:9999,http://192.168.1.101:9999"
              />
              <div class="param-tips">
                <el-text type="info" size="small"> 多个地址用逗号分隔，格式：http://IP:PORT 或 https://IP:PORT </el-text>
              </div>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="confirmTrigger">保存</el-button>
              <el-button @click="cancelTrigger">取消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="JobInfo" lang="ts">
import { delJobInfo, listJobGroup, listJobInfo, startJob, stopJob, triggerJob } from '@/api/xxljob/job';
import { JobGroupVO, JobInfoQuery, JobInfoVO } from '@/api/xxljob/job/types';
import JobForm from './jobForm.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 表单控制状态
const formVisible = ref(false);
const editType = ref('');
const currentRow = ref<JobInfoVO | null>(null);

const jobList = ref<JobInfoVO[]>([]);
const jobGroupOptions = ref<JobGroupVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();

// 执行一次对话框相关
const triggerDialogVisible = ref(false);
const triggerFormRef = ref<ElFormInstance>();
const triggerForm = ref({
  executorParam: '',
  addressList: ''
});
const currentTriggerJob = ref<JobInfoVO | null>(null);

// HTTP URL 验证函数
const validateHttpUrl = (url: string): boolean => {
  try {
    const urlObj = new URL(url);

    // 检查协议
    if (!['http:', 'https:'].includes(urlObj.protocol)) {
      return false;
    }

    // 检查主机名
    if (!urlObj.hostname) {
      return false;
    }

    // 检查端口号（如果有的话）
    if (urlObj.port) {
      const port = parseInt(urlObj.port);
      if (isNaN(port) || port < 1 || port > 65535) {
        return false;
      }
    }

    // 检查IP地址格式或域名格式
    const hostname = urlObj.hostname;

    // IPv4 地址检查
    const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;

    // IPv6 地址检查（简化版）
    const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::1$|^::$/;

    // 域名检查
    const domainRegex = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;

    // localhost 特殊处理
    const isLocalhost = hostname === 'localhost';

    // 验证主机名格式
    const isValidHostname = isLocalhost || ipv4Regex.test(hostname) || ipv6Regex.test(hostname) || domainRegex.test(hostname);

    return isValidHostname;
  } catch (error) {
    return false;
  }
};

// 任务参数验证函数（复用jobForm中的验证逻辑）
const validateExecutorParam = (rule: any, value: any, callback: any) => {
  if (!value || value.trim() === '') {
    callback();
    return;
  }

  // 检查是否包含危险字符或关键字
  const dangerousPatterns = [
    /eval\s*\(/i,
    /exec\s*\(/i,
    /system\s*\(/i,
    /runtime\s*\./i,
    /processbuilder/i,
    /<script/i,
    /javascript:/i,
    /vbscript:/i,
    /onload\s*=/i,
    /onerror\s*=/i,
    /\$\{.*\}/, // EL表达式
    /#\{.*\}/, // OGNL表达式
    /\{\{.*\}\}/ // 模板表达式
  ];

  for (const pattern of dangerousPatterns) {
    if (pattern.test(value)) {
      callback(new Error('任务参数包含不安全的内容，请检查参数格式'));
      return;
    }
  }

  // 检查参数长度
  if (value.length > 2000) {
    callback(new Error('任务参数过长，请控制在2000字符以内'));
    return;
  }

  // 检查是否为有效的JSON格式（可选）
  if (value.trim().startsWith('{') || value.trim().startsWith('[')) {
    try {
      JSON.parse(value);
    } catch (e) {
      callback(new Error('JSON格式不正确，请检查参数格式'));
      return;
    }
  }

  callback();
};

// 机器地址验证函数
const validateAddressList = (rule: any, value: string, callback: any) => {
  if (!value || value.trim() === '') {
    // 机器地址为空是允许的，会从执行器获取
    callback();
    return;
  }

  // 分割地址并去除空白
  const addresses = value
    .split(',')
    .map((addr) => addr.trim())
    .filter((addr) => addr);

  if (addresses.length === 0) {
    callback();
    return;
  }

  // 验证每个地址
  for (const addr of addresses) {
    if (!validateHttpUrl(addr)) {
      callback(new Error(`地址格式不正确: ${addr}，正确格式如：http://127.0.0.1:9999 或 https://example.com:8080`));
      return;
    }
  }

  // 检查是否有重复地址
  const uniqueAddresses = [...new Set(addresses)];
  if (uniqueAddresses.length !== addresses.length) {
    callback(new Error('存在重复的机器地址，请检查'));
    return;
  }

  // 地址数量限制
  if (addresses.length > 10) {
    callback(new Error('机器地址数量不能超过10个'));
    return;
  }

  callback();
};

// 执行一次表单验证规则
const triggerRules = ref({
  executorParam: [{ validator: validateExecutorParam, trigger: 'blur' }],
  addressList: [{ validator: validateAddressList, trigger: 'blur' }]
});

// 查询参数
const queryParams = reactive<JobInfoQuery>({
  pageNum: 1,
  pageSize: 10,
  jobGroup: '',
  jobDesc: '',
  executorHandler: '',
  author: '',
  triggerStatus: ''
});

/** 根据执行器ID获取执行器名称 */
const getJobGroupName = (jobGroupId: number): string => {
  const group = jobGroupOptions.value.find((item) => item.id === jobGroupId);
  return group ? group.title : '未知执行器';
};

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

/** 查询任务列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listJobInfo(queryParams);
    jobList.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;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: JobInfoVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  currentRow.value = null;
  editType.value = 'add';
  formVisible.value = true;
};

/** 修改按钮操作 */
const handleUpdate = (row?: JobInfoVO) => {
  if (row) {
    currentRow.value = row;
  } else {
    const selectedJob = jobList.value.find((item) => item.id === ids.value[0]);
    currentRow.value = selectedJob || null;
  }
  editType.value = 'edit';
  formVisible.value = true;
};

/** 保存成功后的处理 */
const handleSave = () => {
  getList();
};

/** 启动任务 */
const handleStart = async (row: JobInfoVO) => {
  await proxy?.$modal.confirm('确认要启动任务"' + row.jobDesc + '"吗？');
  await startJob(row.id);
  await getList();
  proxy?.$modal.msgSuccess('启动成功');
};

/** 停止任务 */
const handleStop = async (row: JobInfoVO) => {
  await proxy?.$modal.confirm('确认要停止任务"' + row.jobDesc + '"吗？');
  await stopJob(row.id);
  await getList();
  proxy?.$modal.msgSuccess('停止成功');
};

/** 执行一次 */
const handleTrigger = async (row: JobInfoVO) => {
  currentTriggerJob.value = row;
  triggerForm.value = {
    executorParam: row.executorParam || '',
    addressList: ''
  };
  triggerDialogVisible.value = true;
};

/** 确认执行一次 */
const confirmTrigger = async () => {
  if (!currentTriggerJob.value) return;

  await triggerFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 处理地址列表格式
        let addressList = triggerForm.value.addressList;
        if (addressList && addressList.trim()) {
          addressList = addressList
            .split(',')
            .map((addr) => addr.trim())
            .filter((addr) => addr)
            .join(',');
        }

        await triggerJob(currentTriggerJob.value!.id, triggerForm.value.executorParam, addressList);
        proxy?.$modal.msgSuccess('触发成功');
        triggerDialogVisible.value = false;
      } catch (error) {
      }
    }
  });
};

/** 取消执行 */
const cancelTrigger = () => {
  triggerDialogVisible.value = false;
  triggerForm.value = {
    executorParam: '',
    addressList: ''
  };
  triggerFormRef.value?.resetFields();
};

/** 删除按钮操作 */
const handleDelete = async (row?: JobInfoVO) => {
  const jobIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除选择数据项？');
  await delJobInfo(jobIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

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

<style scoped>
.mt-1 {
  margin-top: 4px;
}

.param-tips {
  margin-top: 4px;
}

.dialog-footer {
  text-align: center;
}
</style>
