
<template>
  <CommonPage title="公司信息清洗监控">
    <div class="flex flex-col gap-4">
      <!-- 1. 统计概览 -->
      <n-grid :x-gap="12" :cols="4">
        <n-grid-item>
          <n-card :bordered="false" embedded class="bg-gray-50 dark:bg-gray-800">
            <n-statistic label="总待处理">
              <template #prefix>
                <TheIcon icon="mdi:clipboard-clock" :size="24" :color="themeVars.primaryColor" />
              </template>
              {{ stats.total_pending }}
            </n-statistic>
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card :bordered="false" embedded class="bg-gray-50 dark:bg-gray-800">
             <n-statistic label="今日已清洗">
               <template #prefix>
                 <TheIcon icon="mdi:check-circle" :size="24" :color="themeVars.successColor" />
               </template>
               {{ stats.today_processed }}
               <template #suffix>
                 <span class="text-xs text-gray-400">家</span>
               </template>
             </n-statistic>
          </n-card>
        </n-grid-item>
      </n-grid>

      <!-- 2. 任务控制台 -->
      <n-card title="任务控制台" size="medium">
        <template #header-extra>
            <n-button text type="primary" @click="fetchStats">
                <template #icon><TheIcon icon="mdi:refresh" /></template>
                刷新数据
            </n-button>
        </template>
        <n-grid :x-gap="24" :cols="2">
            <!-- 左侧：数据分析 -->
            <n-grid-item>
                <div class="flex flex-col gap-3">
                    <div class="flex items-center gap-2">
                        <TheIcon icon="mdi:magnify-scan" class="text-info" :size="20"/>
                        <span class="font-bold text-gray-700 dark:text-gray-200">数据分析 (Analysis)</span>
                    </div>
                    <n-space align="center">
                        <n-select
                            v-model:value="selectedSource"
                            size="medium"
                            :options="sourceOptions"
                            style="width: 150px"
                            placeholder="选择数据源"
                        />
                        <n-input-number
                            v-model:value="analyzeLimit"
                            size="medium"
                            :min="1"
                            :max="5000"
                            style="width: 140px"
                            placeholder="分析数量"
                        >
                            <template #suffix>条</template>
                        </n-input-number>
                        <n-button
                            size="medium"
                            type="info"
                            secondary
                            :loading="analyzing"
                            @click="handleAnalyze"
                        >
                            分析待处理数据
                        </n-button>
                    </n-space>
                    <n-alert type="info" :show-icon="false" class="mt-2">
                        扫描原始招聘数据，将未处理的公司提取到 Pending 队列中
                    </n-alert>
                </div>
            </n-grid-item>
            
             <!-- 右侧：任务执行 -->
            <n-grid-item>
                 <div class="flex flex-col gap-3 border-l pl-6 border-gray-100 dark:border-gray-700">
                    <div class="flex items-center gap-2">
                         <TheIcon icon="mdi:spider-web" class="text-primary" :size="20"/>
                         <span class="font-bold text-gray-700 dark:text-gray-200">批量执行 (Execution)</span>
                    </div>
                     <n-space align="center">
                        <n-select
                            v-model:value="globalProxy"
                            size="medium"
                            :options="batchProxyOptions"
                            style="width: 200px"
                            placeholder="使用全局代理 (可选)"
                            clearable
                        />
                        <n-input-number
                            v-model:value="runLimit"
                            size="medium"
                            :min="1"
                            :max="5000"
                            style="width: 120px"
                            placeholder="每批数量"
                        />
                        <n-input-number
                            v-model:value="batchMaxDelay"
                            size="medium"
                            :min="1"
                            :max="60"
                            style="width: 120px"
                            placeholder="最大延时"
                        >
                             <template #suffix>秒</template>
                        </n-input-number>
                    </n-space>
                    <n-alert type="warning" :show-icon="false" class="mt-2">
                        <span class="font-bold">配置应用于：</span> 下方所有执行操作
                    </n-alert>
                </div>
            </n-grid-item>
        </n-grid>
      </n-card>

      <!-- 3. 数据表格 -->
      <n-card title="各平台进度详情" size="medium">
        <n-data-table
          :columns="columns"
          :data="stats.details"
          :loading="loading"
        />
      </n-card>
      
      <!-- 说明 -->
      <n-card title="说明" size="small">
          <n-ul>
              <n-li>系统每天凌晨 02:00 自动扫描待处理公司ID。</n-li>
              <n-li>pending (待处理): 已识别但尚未获取详情的公司。</n-li>
              <n-li>done (已完成): 已成功获取详情并入库。</n-li>
              <n-li>failed (失败): 获取详情失败，需重试或检查爬虫。</n-li>
          </n-ul>
      </n-card>
      
      <!-- 详情抽屉 -->
      <n-drawer v-model:show="showDrawer" width="1200">
        <n-drawer-content title="待处理公司列表">
          <div class="flex gap-2 mb-4 items-center justify-between">
             <div class="flex gap-2">
                 <n-select 
                    v-model:value="drawerSource" 
                    :options="sourceOptions" 
                    placeholder="平台" 
                    clearable 
                    size="medium"
                    style="width: 160px"
                    @update:value="handleDrawerFilter"
                 />
                 <n-select 
                    v-model:value="drawerStatus" 
                    :options="statusOptions" 
                    placeholder="状态" 
                    clearable 
                    size="medium"
                    style="width: 160px"
                    @update:value="handleDrawerFilter"
                 />
             </div>
             <div class="flex items-center gap-2">
                 <n-button size="medium" @click="handleBatchActionInDrawer" disabled>
                     批量操作 (开发中)
                 </n-button>
             </div>
          </div>
          <n-data-table
            remote
            :columns="detailColumns"
            :data="detailData"
            :loading="detailLoading"
            :pagination="pagination"
            :scroll-x="1200"
            @update:page="handlePageChange"
          />
        </n-drawer-content>
      </n-drawer>

      <!-- JSON 查看模态框 -->
      <n-modal v-model:show="showResultModal" preset="card" title="公司详情" style="width: 800px">
        <n-code :code="resultJson" language="json" word-wrap />
      </n-modal>
      <n-modal v-model:show="showSingleResultModal" preset="card" title="任务执行结果" style="width: 800px">
        <n-code :code="singleResultJson" language="json" word-wrap />
      </n-modal>
    </div>
  </CommonPage>
</template>

<script setup>
import { ref, onMounted, h, reactive, computed } from 'vue'
import { NGrid, NGridItem, NCard, NStatistic, NDataTable, NButton, NUl, NLi, NTag, NInputNumber, NSelect, NDrawer, NDrawerContent, NModal, NCode, NSpace, NDropdown, useMessage, NIcon, useThemeVars, NText, NAlert } from 'naive-ui'
import CommonPage from '@/components/page/CommonPage.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import api from '@/api'
import proxyApi from '@/api/proxy'

const themeVars = useThemeVars()

const message = useMessage()
const loading = ref(false)
const running = ref(false)
const analyzing = ref(false)
const stats = ref({
    total_pending: 0,
    today_processed: 0,
    details: []
})

// Drawer state
const showDrawer = ref(false)
const detailLoading = ref(false)
const detailData = ref([])
const drawerSource = ref(null)
const drawerStatus = ref(null)
const pagination = reactive({
    page: 1,
    pageSize: 20,
    itemCount: 0,
    prefix: ({ itemCount }) => `共 ${itemCount} 条`
})

const statusOptions = [
    { label: '全部状态', value: null },
    { label: '待处理', value: 'pending' },
    { label: '已完成', value: 'done' },
    { label: '失败', value: 'failed' }
]

// Modals
const showResultModal = ref(false)
const resultJson = ref('')
const showSingleResultModal = ref(false)
const singleResultJson = ref('')

// Config & State
const allProxies = ref([])
const executingMap = ref({}) 
const platformRunningMap = ref({})

// Global Configs
const runLimit = ref(100)
const analyzeLimit = ref(1000)
const selectedSource = ref(null)
const globalProxy = ref(null)
const batchMaxDelay = ref(5)

const sourceOptions = [
    { label: '全部数据源', value: null },
    { label: 'Boss直聘', value: 'boss' },
    { label: '前程无忧', value: 'qcwy' },
    { label: '智联招聘', value: 'zhilian' }
]

const batchProxyOptions = computed(() => {
    if (!allProxies.value || !allProxies.value.length) return []
    const source = selectedSource.value
    return allProxies.value
        .filter((item) => {
            if (!item.is_active) return false
            if (!source) return true
            if (source === 'boss') return item.platform === 'boss' || item.platform === 'all'
            if (source === 'qcwy') return item.platform === 'qcwy' || item.platform === 'all'
            if (source === 'zhilian') return item.platform === 'zhilian' || item.platform === 'all'
            return true
        })
        .map((item) => ({
            label: `${item.name} (${item.proxy_type.toUpperCase()})`,
            value: item.proxy_url
        }))
})

// --- Columns Definitions ---

const columns = [
    {
        title: '平台',
        key: 'source',
        render(row) {
             const map = { 'boss': 'Boss直聘', 'qcwy': '前程无忧', 'zhilian': '智联招聘' }
             return map[row.source] || row.source
        }
    },
    {
        title: '待处理',
        key: 'pending',
        render(row) {
            return h(NTag, { type: 'warning', bordered: false }, { default: () => row.pending })
        }
    },
    {
        title: '已完成',
        key: 'done',
        render(row) {
            return h(NTag, { type: 'success', bordered: false }, { default: () => row.done })
        }
    },
    {
        title: '失败',
        key: 'failed',
        render(row) {
            return row.failed > 0 
                ? h(NTag, { type: 'error', bordered: false }, { default: () => row.failed })
                : '-'
        }
    },
    {
        title: '完成率',
        key: 'rate',
        render(row) {
            if (!row.total) return '0%'
            const rate = ((row.done / row.total) * 100).toFixed(1)
            return `${rate}%`
        }
    },
    {
        title: '操作',
        key: 'actions',
        width: 250,
        render(row) {
            return h(
                'div',
                { class: 'flex gap-2 items-center' },
                [
                    h(
                        NButton,
                        {
                            size: 'small', // Keep buttons small in table, but not tiny
                            type: 'primary',
                            secondary: true,
                            disabled: row.pending === 0,
                            loading: !!platformRunningMap.value[row.source],
                            onClick: () => handleExecuteBySource(row.source)
                        },
                        { 
                            default: () => '执行任务',
                            icon: () => h(TheIcon, { icon: 'mdi:play' }) 
                        }
                    ),
                    h(
                        NButton,
                        {
                            size: 'small',
                            tertiary: true,
                            onClick: () => openDetail(row.source)
                        },
                        { default: () => '查看详情' }
                    )
                ]
            )
        }
    }
]

const detailColumns = [
    {
        title: '平台',
        key: 'source',
        width: 80,
        render(row) {
             const map = { 'boss': 'Boss', 'qcwy': '前程', 'zhilian': '智联' }
             return map[row.source] || row.source
        }
    },
    {
        title: '公司名称',
        key: 'company_name',
        width: 200,
        ellipsis: { tooltip: true }
    },
    {
        title: '公司ID',
        key: 'company_id',
        width: 150,
        ellipsis: { tooltip: true }
    },
    {
        title: '状态',
        key: 'status',
        width: 90,
        render(row) {
            const typeMap = { 'pending': 'warning', 'done': 'success', 'failed': 'error' }
            return h(NTag, { type: typeMap[row.status] || 'default', size: 'small' }, { default: () => row.status })
        }
    },
    {
        title: '更新时间',
        key: 'updated_at',
        width: 170,
        render(row) {
            return row.updated_at ? row.updated_at.replace('T', ' ').split('.')[0] : '-'
        }
    },
    {
        title: '操作',
        key: 'actions',
        width: 150,
        fixed: 'right',
        render(row) {
            if (row.status === 'pending' || row.status === 'failed') {
                return h(
                    NButton,
                    {
                        size: 'tiny',
                        type: 'primary',
                        loading: !!executingMap.value[row.company_id],
                        onClick: () => handleExecuteSingle(row)
                    },
                    { default: () => row.status === 'failed' ? '重试' : '执行' }
                )
            }
            if (row.status === 'done') {
                return h(
                    NButton,
                    {
                        size: 'tiny',
                        tertiary: true,
                        onClick: () => viewCompanyResult(row)
                    },
                    { default: () => '查看结果' }
                )
            }
            return null
        }
    }
]

// --- Actions ---

const fetchStats = async () => {
    loading.value = true
    try {
        const res = await api.getCompanyCleaningStats()
        if (res.code === 200) {
            stats.value = res.data
        }
    } finally {
        loading.value = false
    }
}

const fetchDetail = async () => {
    detailLoading.value = true
    try {
        const res = await api.getCompanyCleaningList({
            page: pagination.page,
            page_size: pagination.pageSize,
            source: drawerSource.value || undefined,
            status: drawerStatus.value || undefined
        })
        if (res.code === 200) {
            detailData.value = res.data
            pagination.itemCount = res.total
        }
    } finally {
        detailLoading.value = false
    }
}

const openDetail = (source) => {
    drawerSource.value = source
    drawerStatus.value = null
    pagination.page = 1
    showDrawer.value = true
    fetchDetail()
}

const handleDrawerFilter = () => {
    pagination.page = 1
    fetchDetail()
}

const handlePageChange = (page) => {
    pagination.page = page
    fetchDetail()
}

const viewCompanyResult = async (row) => {
    if (row.status !== 'done') {
        message.warning('当前记录未完成清洗')
        return
    }
    try {
        const res = await api.getCompanyCleaningDetail({
            source: row.source,
            company_id: row.company_id,
            company_name: row.company_name
        })
        if (res.code === 200 && res.data) {
            const content = res.data.data || res.data
            resultJson.value = JSON.stringify(content, null, 2)
            showResultModal.value = true
        } else {
            message.warning(res.msg || '未找到公司清洗结果')
        }
    } catch (e) {
        message.error('获取公司详情失败')
    }
}

const handleAnalyze = async () => {
    if (!analyzeLimit.value || analyzeLimit.value <= 0) {
        message.warning('请先填写分析数量')
        return
    }
    try {
        analyzing.value = true
        await api.collectPendingCompanies({
            limit: analyzeLimit.value,
            source: selectedSource.value || null
        })
        message.success(`已完成数据分析，收集待处理公司 (上限 ${analyzeLimit.value} 条)`)
        await fetchStats()
    } catch (e) {
        message.error('数据分析失败')
    } finally {
        analyzing.value = false
    }
}

const handleExecuteSingle = async (row) => {
    try {
        executingMap.value[row.company_id] = true
        
        const payload = {
            source: row.source,
            company_id: row.company_id,
            max_delay_seconds: batchMaxDelay.value || 5 
        }
        if (globalProxy.value) {
            payload.proxy = globalProxy.value
        }
        
        const res = await api.runSingleCompanyCleaning(payload)
        const success = res && res.code === 200 && res.data && res.data.success
        
        if (success) {
            message.success('任务执行成功')
            await fetchDetail()
        } else {
            const detail = {
                request: payload,
                response: res
            }
            singleResultJson.value = JSON.stringify(detail, null, 2)
            showSingleResultModal.value = true
            message.error((res && res.msg) || '任务执行失败')
        }
    } catch (e) {
        message.error('执行异常: ' + e.message)
    } finally {
        executingMap.value[row.company_id] = false
    }
}

const handleExecuteBySource = async (source) => {
    if (!runLimit.value || runLimit.value <= 0) {
        message.warning('请先填写执行数量')
        return
    }
    try {
        platformRunningMap.value[source] = true
        
        const payload = {
            limit: runLimit.value,
            source: source,
            max_delay_seconds: batchMaxDelay.value || 5,
        }
        if (globalProxy.value) {
            payload.proxy = globalProxy.value
        }

        const res = await api.runPendingCompanies(payload)
        if (res.code === 200) {
            message.success(res.msg || '已触发批量任务')
            await fetchStats()
        } else {
            message.error(res.msg || '触发失败')
        }
    } catch (e) {
        message.error('触发失败: ' + e.message)
    } finally {
        platformRunningMap.value[source] = false
    }
}

const loadProxies = async () => {
    try {
        const res = await proxyApi.list({ page: 1, page_size: 100, is_active: true })
        allProxies.value = res.data || res.data?.data || []
    } catch (e) {
        allProxies.value = []
    }
}

const handleBatchActionInDrawer = () => {
    message.info('功能开发中...')
}

onMounted(() => {
    fetchStats()
    loadProxies()
})
</script>

<style scoped>
.stats-card {
    transition: all 0.3s ease;
    background-color: #fff; /* Fallback for white */
}
.stats-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
</style>
