<template>
  <CommonPage title="定向数据清洗">
    <div class="h-full flex flex-col">
        <div class="mb-4 flex justify-between items-center bg-white p-4 rounded shadow-sm dark:bg-gray-800">
            <n-space>
                 <n-button type="primary" @click="showUploadModal = true">
                     <template #icon><TheIcon icon="mdi:cloud-upload" /></template>
                     上传数据
                 </n-button>
                 <n-popconfirm @positive-click="handleClear">
                     <template #trigger>
                         <n-button type="error">
                             <template #icon><TheIcon icon="mdi:delete-forever" /></template>
                             清空所有
                         </n-button>
                     </template>
                     确定要清空所有清洗任务吗？
                 </n-popconfirm>
             </n-space>
        </div>

        <CrudTable
            ref="$table"
            v-model:query-items="queryItems"
            :columns="columns"
            :get-data="api.getCleaningTasks"
        >
            <template #queryBar>
                <QueryBarItem label="状态" :label-width="60">
                    <n-select
                        v-model:value="queryItems.status"
                        :options="statusOptions"
                        placeholder="状态"
                        clearable
                        style="width: 200px"
                    />
                </QueryBarItem>
                <QueryBarItem label="清洗模式" :label-width="80">
                    <n-select
                        v-model:value="queryItems.clean_type"
                        :options="cleanTypeOptions"
                        placeholder="清洗模式"
                        clearable
                        style="width: 220px"
                    />
                </QueryBarItem>
                <QueryBarItem label="目标" :label-width="50">
                    <n-input
                        v-model:value="queryItems.target"
                        placeholder="搜索目标"
                        clearable
                        @keyup.enter="$table?.handleSearch()"
                        style="width: 260px"
                    />
                </QueryBarItem>
            </template>
        </CrudTable>

        <!-- Upload Modal -->
        <n-modal v-model:show="showUploadModal" preset="card" title="上传待清洗数据" style="width: 600px">
            <n-form label-placement="left" label-width="100">
                 <n-form-item label="清洗模式">
                    <div class="flex flex-col w-full gap-2">
                        <n-select v-model:value="uploadForm.cleanType" :options="cleanTypeOptions" />
                        <div v-if="currentExample" class="text-xs text-gray-500">
                            <n-a :href="currentExample.url" target="_blank" download class="flex items-center">
                                <TheIcon icon="mdi:download" class="mr-1" />
                                下载{{ currentExample.name }}示例文件
                            </n-a>
                        </div>
                    </div>
                </n-form-item>
                 <n-form-item label="目标平台">
                     <n-select v-model:value="uploadForm.platform" :options="platformOptions" />
                 </n-form-item>
                 <n-form-item label="代理地址">
                    <div class="flex flex-col w-full gap-2">
                        <n-select
                            v-model:value="selectedProxyId"
                            :options="proxyOptions"
                            placeholder="选择已配置的代理（可选）"
                            clearable
                            @update:value="handleProxySelect"
                        />
                        <n-input
                            v-model:value="uploadForm.proxy"
                            placeholder="例如 http://user:pass@ip:port，留空则使用默认"
                        />
                    </div>
                 </n-form-item>
                 <n-form-item label="文件">
                      <n-upload
                          directory-dnd
                          :custom-request="customUploadRequest"
                          :max="1"
                          accept=".txt,.csv,.xlsx"
                      >
                          <n-upload-dragger>
                              <div style="margin-bottom: 12px">
                                  <TheIcon icon="mdi:cloud-upload" :size="48" />
                              </div>
                              <n-text style="font-size: 16px">点击或拖动文件上传</n-text>
                              <n-p depth="3" style="margin: 8px 0 0 0">
                                支持 .txt, .csv, .xlsx 文件，每行一个目标<br>
                                请确保文件内容与选择的清洗模式和平台一致
                              </n-p>
                          </n-upload-dragger>
                      </n-upload>
                 </n-form-item>
            </n-form>
        </n-modal>
        
        <!-- Detail Modal -->
         <n-modal v-model:show="showDetailModal" preset="card" title="结果详情" style="width: 600px">
            <n-code :code="detailJson" language="json" word-wrap />
        </n-modal>
    </div>
  </CommonPage>
</template>

<script setup>
import { ref, h, reactive, computed, onMounted } from 'vue'
import { NButton, NTag, NSpace, NPopconfirm, useMessage, NSwitch, NA } from 'naive-ui'
import CommonPage from '@/components/page/CommonPage.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import api from '@/api'
import proxyApi from '@/api/proxy'
import { renderIcon } from '@/utils'

const message = useMessage()
const $table = ref(null)
const queryItems = ref({})
const showUploadModal = ref(false)
const showDetailModal = ref(false)
const detailJson = ref('')

const uploadForm = reactive({
    cleanType: 'auto',
    platform: 'auto',
    proxy: ''
})
const selectedProxyId = ref(null)
const allProxies = ref([])

const proxyOptions = computed(() => {
    if (!allProxies.value || !allProxies.value.length) return []
    const platform = uploadForm.platform
    return allProxies.value
        .filter((item) => {
            if (!item.is_active) return false
            if (platform === 'auto') return true
            return item.platform === 'all' || item.platform === platform
        })
        .map((item) => ({
            label: `${item.name} (${item.proxy_type.toUpperCase()})`,
            value: item.id
        }))
})

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 handleProxySelect = (val) => {
    selectedProxyId.value = val
    if (!val) return
    const found = allProxies.value.find((item) => item.id === val)
    if (found) {
        uploadForm.proxy = found.proxy_url
    }
}

const currentExample = computed(() => {
    const type = uploadForm.cleanType
    const platform = uploadForm.platform
    
    let url = ''
    let name = ''
    
    if (type === 'company_name') {
        name = '公司名称'
        url = '/static/examples/company_names.txt'
    } else if (type === 'company_id') {
        name = '公司ID'
        url = '/static/examples/company_ids.txt'
    } else if (type === 'clean_url') {
        name = 'URL链接'
        url = '/static/examples/boss_urls.txt'
    }
    
    // Platform specific overrides
    if (platform === 'boss') {
        if (type === 'company_id') url = '/static/examples/boss_com_ids.txt'
        if (type === 'company_name') url = '/static/examples/boss_com_names.txt'
        if (type === 'clean_url') url = '/static/examples/boss_urls.txt'
    } else if (platform === 'qcwy') {
        if (type === 'company_id') url = '/static/examples/qcwy_com_ids.txt'
        if (type === 'company_name') url = '/static/examples/qcwy_com_names.txt'
        if (type === 'clean_url') url = '/static/examples/qcwy_urls.txt'
    } else if (platform === 'zhilian') {
        if (type === 'company_id') url = '/static/examples/zhaopin_com_ids.txt'
        if (type === 'company_name') url = '/static/examples/zhaopin_com_names.txt'
        if (type === 'clean_url') url = '/static/examples/zhaopin_urls.txt'
    }
    
    if (!url) return null
    return { name, url }
})

const cleanTypeOptions = [
  { label: '自动识别', value: 'auto' },
  { label: '公司名称清洗', value: 'company_name' },
  { label: '公司ID清洗', value: 'company_id' },
  { label: 'URL清洗', value: 'clean_url' },
  { label: '公司Jobs清洗', value: 'company_jobs' }
]

const platformOptions = [
  { label: '自动识别', value: 'auto' },
  { label: 'Boss直聘', value: 'boss' },
  { label: '前程无忧', value: 'qcwy' },
  { label: '智联招聘', value: 'zhilian' }
]

const statusOptions = [
    { label: '待处理', value: 'pending' },
    { label: '处理中', value: 'processing' },
    { label: '成功', value: 'success' },
    { label: '失败', value: 'fail' }
]

const customUploadRequest = async ({ file, onFinish, onError }) => {
    const formData = new FormData()
    formData.append('file', file.file)
    formData.append('clean_type', uploadForm.cleanType)
    formData.append('platform', uploadForm.platform)
    if (uploadForm.proxy) {
        formData.append('proxy', uploadForm.proxy)
    }
    
    try {
        await api.uploadCleaningFile(formData)
        message.success('上传成功')
        showUploadModal.value = false
        $table.value?.handleSearch()
        onFinish()
    } catch (error) {
        message.error('上传失败')
        onError()
    }
}

const handleClear = async () => {
    try {
        await api.clearCleaningTasks()
        message.success('已清空')
        $table.value?.handleSearch()
    } catch (error) {
        message.error('操作失败')
    }
}

const handleProcess = async (row) => {
    try {
        row.processing = true // Optimistic UI update if possible, or just loading state
        await api.processCleaningTask(row.id)
        message.success('处理完成')
        $table.value?.handleSearch()
    } catch (error) {
        message.error('处理失败')
    } finally {
        row.processing = false
    }
}

const handleDelete = async (row) => {
    try {
        await api.deleteCleaningTask({ id: row.id })
        message.success('删除成功')
        $table.value?.handleSearch()
    } catch (error) {
        message.error('删除失败')
    }
}

const showDetail = (row) => {
    try {
        const displayData = {
            result: row.result_summary,
            original_data: row.original_data,
            error: row.error_msg
        }
        // Filter out null/undefined values for cleaner display
        const cleanData = Object.fromEntries(
            Object.entries(displayData).filter(([_, v]) => v != null)
        )
        
        detailJson.value = JSON.stringify(cleanData, null, 2)
        showDetailModal.value = true
    } catch (e) {
        detailJson.value = '{}'
    }
}

const columns = [
    { title: 'ID', key: 'id', width: 60, align: 'center' },
    { 
        title: '平台', 
        key: 'platform', 
        width: 100,
        render(row) {
             const map = {
                 'boss': 'Boss直聘',
                 'qcwy': '前程无忧',
                 'zhilian': '智联招聘',
                 'auto': '自动识别'
         }
         return map[row.platform] || row.platform
        }
    },
    { title: '目标', key: 'target', width: 200, ellipsis: { tooltip: true } },
    { title: '代理', key: 'proxy', width: 220, ellipsis: { tooltip: true } },
    { 
        title: '清洗模式', 
        key: 'clean_type', 
        width: 100,
        render(row) {
            const opt = cleanTypeOptions.find(o => o.value === row.clean_type)
            return opt ? opt.label : row.clean_type
        }
    },
    { 
        title: '状态', 
        key: 'status',
        width: 100,
        align: 'center',
        render(row) {
            const statusMap = {
                pending: { type: 'default', text: '待处理' },
                processing: { type: 'info', text: '处理中' },
                success: { type: 'success', text: '成功' },
                fail: { type: 'error', text: '失败' }
            }
            const s = statusMap[row.status] || { type: 'default', text: row.status }
            return h(NTag, { type: s.type, bordered: false }, { default: () => s.text })
        }
    },
    {
        title: '存储状态',
        key: 'storage_status',
        width: 120,
        align: 'center',
        render(row) {
             const map = {
                 saved: { type: 'success', text: '已入库' },
                 duplicate: { type: 'warning', text: '重复跳过' },
                 failed: { type: 'error', text: '入库失败' },
                 unknown: { type: 'default', text: '-' }
             }
             const s = map[row.storage_status] || { type: 'default', text: row.storage_status }
             return h(NTag, { type: s.type, bordered: false, size: 'small' }, { default: () => s.text })
        }
    },
    {
        title: '远程推送',
        key: 'remote_sent',
        width: 100,
        align: 'center',
        render(row) {
            if (row.status !== 'success') return '-'
            return row.remote_sent 
                ? h(NTag, { type: 'success', size: 'small' }, { default: () => '已发送' })
                : h(NTag, { type: 'default', size: 'small' }, { default: () => '未发送' })
        }
    },
    {
        title: '操作',
        key: 'actions',
        width: 200,
        align: 'center',
        fixed: 'right',
        render(row) {
            return h(NSpace, { justify: 'center' }, {
                default: () => [
                    h(NButton, {
                        size: 'small',
                        type: 'primary',
                        ghost: true,
                        disabled: row.status === 'processing',
                        onClick: () => handleProcess(row)
                    }, { default: () => row.status === 'success' ? '重试' : '执行' }),
                    
                    (row.status === 'success' || row.status === 'fail') ? h(NButton, {
                        size: 'small',
                        onClick: () => showDetail(row)
                    }, { default: () => '详情' }) : null,

                    h(NPopconfirm, {
                        onPositiveClick: () => handleDelete(row)
                    }, {
                        trigger: () => h(NButton, {
                            size: 'small',
                            type: 'error',
                            text: true,
                        }, { default: () => '删除', icon: renderIcon('mdi:delete', { size: 16 }) }),
                        default: () => '确定删除该任务吗？'
                    })
                ]
            })
        }
    }
]

onMounted(() => {
    loadProxies()
    $table.value?.handleSearch()
})
</script>
