<template>
  <div class="crawler-page">
    <div class="page-header">
      <div class="header-content">
        <div class="header-icon">
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"/>
            <path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
          </svg>
        </div>
        <div class="header-text">
          <h1>数据爬虫</h1>
          <p>从网页自动采集数据，用于构建训练数据集</p>
        </div>
      </div>
    </div>

    <div class="crawler-content">
      <!-- Crawler Config Card -->
      <div class="config-card">
        <h2>爬取配置</h2>

        <el-form :model="form" label-position="top">
          <el-form-item label="目标网址">
            <el-input
              v-model="form.url"
              placeholder="https://example.com"
              :prefix-icon="Link"
            >
              <template #prepend>
                <el-select v-model="form.method" style="width: 100px">
                  <el-option label="GET" value="GET" />
                  <el-option label="POST" value="POST" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="选择项目">
            <el-select v-model="form.projectId" placeholder="选择目标项目" style="width: 100%">
              <el-option
                v-for="project in projects"
                :key="project.id"
                :label="project.name"
                :value="project.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="爬取规则">
            <div class="rule-options">
              <el-checkbox v-model="form.extractTitle">提取标题</el-checkbox>
              <el-checkbox v-model="form.extractContent">提取正文内容</el-checkbox>
              <el-checkbox v-model="form.extractLinks">提取所有链接</el-checkbox>
              <el-checkbox v-model="form.extractImages">提取图片链接</el-checkbox>
            </div>
          </el-form-item>

          <el-form-item label="CSS 选择器 (可选)">
            <el-input
              v-model="form.cssSelector"
              placeholder="如: article.content, .post-body"
            />
          </el-form-item>

          <el-form-item label="爬取深度">
            <el-slider v-model="form.depth" :min="1" :max="5" show-input />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              :loading="crawling"
              @click="startCrawl"
              class="start-btn"
            >
              <el-icon><Crawler /></el-icon>
              {{ crawling ? '爬取中...' : '开始爬取' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- Results Card -->
      <div class="results-card">
        <div class="results-header">
          <h2>爬取结果</h2>
          <span class="result-count" v-if="results.length">{{ results.length }} 条</span>
        </div>

        <div class="results-content" v-loading="crawling">
          <div v-if="!crawling && results.length === 0" class="empty-results">
            <el-icon class="empty-icon"><Link /></el-icon>
            <p>配置完成后点击"开始爬取"</p>
          </div>

          <div v-else class="results-list">
            <div
              v-for="(item, index) in results"
              :key="index"
              class="result-item"
            >
              <div class="result-title">{{ item.title || '无标题' }}</div>
              <div class="result-url">{{ item.url }}</div>
              <div class="result-preview" v-if="item.content">
                {{ item.content.substring(0, 150) }}...
              </div>
              <div class="result-meta">
                <el-tag size="small" v-if="item.images?.length">
                  {{ item.images.length }} 张图片
                </el-tag>
                <el-tag size="small" v-if="item.links?.length">
                  {{ item.links.length }} 个链接
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <div class="results-actions" v-if="results.length > 0">
          <el-button @click="exportResults">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button type="primary" @click="saveToProject">
            <el-icon><FolderAdd /></el-icon>
            保存到项目
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Link, Download, FolderAdd } from '@element-plus/icons-vue'
import { projectApi } from '@/core/api'

const router = useRouter()

const projects = ref([])
const crawling = ref(false)
const results = ref([])

const form = ref({
  url: '',
  method: 'GET',
  projectId: '',
  extractTitle: true,
  extractContent: true,
  extractLinks: false,
  extractImages: false,
  cssSelector: '',
  depth: 1
})

const fetchProjects = async () => {
  try {
    const res = await projectApi.list()
    projects.value = res.items || res || []
  } catch (error) {
    projects.value = []
  }
}

const startCrawl = async () => {
  if (!form.value.url) {
    ElMessage.warning('请输入目标网址')
    return
  }

  if (!form.value.projectId) {
    ElMessage.warning('请选择目标项目')
    return
  }

  crawling.value = true
  results.value = []

  try {
    // Simulate crawling - in production this would call the backend API
    await new Promise(resolve => setTimeout(resolve, 2000))

    // Demo results
    results.value = [
      {
        title: '示例页面标题',
        url: form.value.url,
        content: '这是从网页中提取的内容示例。爬虫会解析HTML结构，提取文本、图片链接和其他有价值的数据。',
        images: ['https://example.com/image1.jpg'],
        links: ['https://example.com/page1', 'https://example.com/page2']
      },
      {
        title: '子页面标题 1',
        url: form.value.url + '/page1',
        content: '这是子页面的内容...',
        images: [],
        links: []
      }
    ]

    ElMessage.success('爬取完成')
  } catch (error) {
    ElMessage.error('爬取失败: ' + error.message)
  } finally {
    crawling.value = false
  }
}

const exportResults = () => {
  const data = JSON.stringify(results.value, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'crawler-results.json'
  a.click()
  URL.revokeObjectURL(url)
}

const saveToProject = () => {
  ElMessage.success('数据已保存到项目')
}

onMounted(() => fetchProjects())
</script>

<style scoped>
.crawler-page {
  min-height: 100vh;
  padding: 40px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 40px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-icon {
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--accent-primary-muted);
  border-radius: var(--radius-lg);
  color: var(--accent-primary);
}

.header-text h1 {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 4px;
}

.header-text p {
  color: var(--text-secondary);
}

.crawler-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.config-card,
.results-card {
  background: var(--bg-secondary);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-lg);
  padding: 24px;
}

.config-card h2,
.results-card h2 {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
}

.rule-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.start-btn {
  width: 100%;
  padding: 14px;
  font-size: 15px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.result-count {
  font-size: 14px;
  color: var(--text-secondary);
  background: var(--accent-primary-muted);
  padding: 4px 12px;
  border-radius: 100px;
}

.results-content {
  min-height: 300px;
}

.empty-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: var(--text-tertiary);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.3;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.result-item {
  padding: 16px;
  background: var(--bg-tertiary);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-subtle);
}

.result-title {
  font-weight: 600;
  margin-bottom: 4px;
}

.result-url {
  font-size: 12px;
  color: var(--accent-primary);
  margin-bottom: 8px;
}

.result-preview {
  font-size: 13px;
  color: var(--text-secondary);
  margin-bottom: 8px;
  line-height: 1.5;
}

.result-meta {
  display: flex;
  gap: 8px;
}

.results-actions {
  display: flex;
  gap: 12px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--border-subtle);
}

@media (max-width: 900px) {
  .crawler-content {
    grid-template-columns: 1fr;
  }
}
</style>
