<script setup lang="ts">
import { h, onMounted, onUnmounted, ref } from 'vue';

import { Page } from '@vben/common-ui';

import {
  Button,
  Card,
  Modal,
  Select,
  Space,
  Switch,
  Table,
  Tag,
  message,
} from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

import {
  getTaskStatus,
  setCron as setCronApi,
  startTask,
  stopTask,
  wecomApprovalSyncFull,
  wecomApprovalSyncLogs,
  wecomApprovalSyncTemplates,
} from '#/api/system/wecom-approval-sync';

defineOptions({ name: 'WecomApprovalSync' });

const syncing = ref(false);
const syncingTemplates = ref(false);
const syncDays = ref(30);
const logs = ref<any[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const pollingTimer = ref<ReturnType<typeof setInterval> | null>(null);
const latestSyncLogId = ref<number | null>(null);

// 同步状态
const statusMap: Record<string, { text: string; color: string }> = {
  RUNNING: { text: '同步中', color: 'processing' },
  COMPLETED: { text: '已完成', color: 'success' },
  FAILED: { text: '失败', color: 'error' },
};

// 定时任务状态
const taskRunning = ref(false);
const currentCron = ref('0 0/5 * * * ?');
const taskLoading = ref(false);

const cronOptions = [
  { label: '每 1 分钟', value: '0 0/1 * * * ?' },
  { label: '每 5 分钟', value: '0 0/5 * * * ?' },
  { label: '每 10 分钟', value: '0 0/10 * * * ?' },
  { label: '每 30 分钟', value: '0 0/30 * * * ?' },
  { label: '每 1 小时', value: '0 0 * * * ?' },
  { label: '每天凌晨 2 点', value: '0 0 2 * * ?' },
];

const syncTypeMap: Record<string, { text: string; color: string }> = {
  FULL: { text: '全量同步', color: 'blue' },
  INCREMENTAL: { text: '增量同步', color: 'green' },
  MANUAL: { text: '手动同步', color: 'orange' },
};

const columns = [
  {
    title: '状态',
    key: 'status',
    width: 100,
    customRender: ({ record }: any) => {
      const info = statusMap[record.status] || { text: '未知', color: 'default' };
      return h(Tag, { color: info.color }, () => info.text);
    },
  },
  {
    title: '同步类型',
    dataIndex: 'syncTypeText',
    key: 'syncTypeText',
    width: 120,
    customRender: ({ record }: any) => {
      const info = syncTypeMap[record.syncType] || { text: record.syncType, color: 'default' };
      return h(Tag, { color: info.color }, () => info.text);
    },
  },
  { title: '开始时间', dataIndex: 'startTime', key: 'startTime', width: 180 },
  { title: '结束时间', dataIndex: 'endTime', key: 'endTime', width: 180 },
  { title: '耗时(秒)', dataIndex: 'duration', key: 'duration', width: 100 },
  { title: '新增', dataIndex: 'addedCount', key: 'addedCount', width: 80 },
  { title: '更新', dataIndex: 'updatedCount', key: 'updatedCount', width: 80 },
  { title: '失败', dataIndex: 'errorCount', key: 'errorCount', width: 80 },
  { title: '操作人', dataIndex: 'operator', key: 'operator', width: 120 },
];

async function handleFullSync() {
  Modal.confirm({
    title: '确认全量同步',
    icon: () => h(ExclamationCircleOutlined),
    content: `将同步近 ${syncDays.value} 天的所有审批数据，后台异步执行，请查看同步日志跟踪进度。确定继续吗？`,
    okText: '确定同步',
    cancelText: '取消',
    async onOk() {
      syncing.value = true;
      try {
        const logId = await wecomApprovalSyncFull(syncDays.value);
        latestSyncLogId.value = logId;
        message.success('已启动同步，请在下方同步日志中查看进度');
        await loadLogs();
        // 如果正在运行，启动轮询
        startPolling();
      } catch {
        message.error('启动同步失败');
      } finally {
        syncing.value = false;
      }
    },
  });
}

function startPolling() {
  stopPolling();
  pollingTimer.value = setInterval(async () => {
    await loadLogs();
    // 检查最新同步日志是否还在运行
    const runningLog = logs.value.find((l: any) => l.status === 'RUNNING');
    if (!runningLog) {
      stopPolling();
    }
  }, 3000);
}

function stopPolling() {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value);
    pollingTimer.value = null;
  }
}

async function loadLogs() {
  loading.value = true;
  try {
    const res = await wecomApprovalSyncLogs({
      pageNum: currentPage.value ?? 1,
      pageSize: pageSize.value ?? 10,
    });
    logs.value = res?.rows ?? [];
    total.value = res?.total ?? 0;
  } catch (error: any) {
    const errorMsg = error?.message || error?.response?.data?.msg || '未知错误';
    message.error(`加载同步日志失败: ${errorMsg}`);
  } finally {
    loading.value = false;
  }
}

async function loadTaskStatus() {
  try {
    const status = await getTaskStatus();
    taskRunning.value = status.running;
    currentCron.value = status.cron || '0 0/5 * * * ?';
  } catch { /* 忽略 */ }
}

async function handleTaskToggle(checked: boolean) {
  taskLoading.value = true;
  try {
    if (checked) {
      await startTask();
      message.success('定时任务已启动');
    } else {
      await stopTask();
      message.success('定时任务已停止');
    }
    await loadTaskStatus();
  } catch {
    message.error(checked ? '启动失败' : '停止失败');
  } finally {
    taskLoading.value = false;
  }
}

async function handleCronChange(value: string) {
  try {
    await setCronApi(value);
    message.success('同步频率已更新');
    currentCron.value = value;
  } catch {
    message.error('更新频率失败');
  }
}

function handlePageChange(pagination: any) {
  currentPage.value = pagination.current ?? 1;
  pageSize.value = pagination.pageSize ?? 10;
  loadLogs();
}

async function handleSyncTemplates() {
  Modal.confirm({
    title: '确认同步模板',
    icon: () => h(ExclamationCircleOutlined),
    content: '将从已同步的审批数据中提取模板ID并同步模板详情，确定继续吗？',
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      syncingTemplates.value = true;
      try {
        await wecomApprovalSyncTemplates();
        message.success('模板同步完成');
      } catch {
        message.error('模板同步失败');
      } finally {
        syncingTemplates.value = false;
      }
    },
  });
}

onMounted(() => {
  loadLogs();
  loadTaskStatus();
});

onUnmounted(() => {
  stopPolling();
});
</script>

<template>
  <Page :auto-content-height="true">
    <div style="overflow-y: auto; padding: 16px">
      <!-- 操作区 -->
      <Card title="操作" :bordered="false" style="margin-bottom: 16px">
        <Space>
          <span>同步近</span>
          <Select v-model:value="syncDays" style="width: 120px">
            <Select.Option :value="1">1 天</Select.Option>
            <Select.Option :value="7">7 天</Select.Option>
            <Select.Option :value="30">30 天</Select.Option>
            <Select.Option :value="90">90 天</Select.Option>
          </Select>
          <span>的数据</span>
          <Button type="primary" danger :loading="syncing" @click="handleFullSync">
            全量同步
          </Button>
          <Button :loading="syncingTemplates" @click="handleSyncTemplates">
            同步模板
          </Button>
        </Space>
      </Card>

      <!-- 定时任务管理 -->
      <Card title="定时任务" :bordered="false" style="margin-bottom: 16px">
        <Space>
          <span>启用定时同步：</span>
          <Switch
            v-model:checked="taskRunning"
            :loading="taskLoading"
            checked-children="开"
            un-checked-children="关"
            @change="handleTaskToggle"
          />
          <span style="margin-left: 24px">同步频率：</span>
          <Select
            :value="currentCron"
            style="width: 180px"
            :options="cronOptions"
            @change="handleCronChange"
          />
          <Tag :color="taskRunning ? 'green' : 'default'">
            {{ taskRunning ? '运行中' : '已停止' }}
          </Tag>
        </Space>
      </Card>

      <!-- 同步日志表格 -->
      <Card title="同步日志" :bordered="false">
        <Table
          :columns="columns"
          :data-source="logs"
          :loading="loading"
          :pagination="{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showTotal: (t: number) => `共 ${t} 条`,
          }"
          row-key="id"
          @change="handlePageChange"
        />
      </Card>
    </div>
  </Page>
</template>
