<template>
  <div>
    <el-card>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="接口配置" name="config">
          <el-form :model="apiConfig" label-width="120px" style="max-width:600px">
            <el-form-item label="接口服务商">
              <el-select v-model="apiConfig.type">
                <el-option label="一号通" value="yihaotong" />
                <el-option label="99采集" value="99cai" />
              </el-select>
            </el-form-item>
            <el-form-item label="App Key"><el-input v-model="apiConfig.app_key" placeholder="输入 API Key" /></el-form-item>
            <el-form-item label="App Secret" ><el-input v-model="apiConfig.app_secret" /></el-form-item>
            <el-form-item label="API地址"><el-input v-model="apiConfig.api_url" placeholder="采集API接口地址，留空使用默认" /></el-form-item>
            <el-form-item><el-button type="primary" @click="saveConfig" :loading="saving">保存配置</el-button></el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="商品采集" name="collect">
          <el-form :model="collectForm" label-width="100px" inline>
            <el-form-item label="目标平台">
              <el-select v-model="collectForm.platform">
                <el-option label="淘宝/天猫" value="taobao" />
                <el-option label="1688" value="1688" />
                <el-option label="拼多多" value="pinduoduo" />
                <el-option label="京东" value="jd" />
              </el-select>
            </el-form-item>
            <el-form-item label="采集方式">
              <el-radio-group v-model="collectForm.type">
                <el-radio :label="1">链接采集</el-radio>
                <el-radio :label="2">关键词采集</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="采集内容" style="width:100%">
              <el-input type="textarea" v-model="collectForm.content" :rows="4" :placeholder="collectForm.type===1?'输入商品链接，每行一个':'输入搜索关键词'" />
            </el-form-item>
            <el-form-item label="采集选项">
              <el-checkbox v-model="collectForm.local_image">图片下载到本地</el-checkbox>
              <el-checkbox v-model="collectForm.import_spec">导入商品规格</el-checkbox>
            </el-form-item>
            <el-form-item><el-button type="success" @click="startCollect" :loading="collecting">开始采集</el-button></el-form-item>
          </el-form>

          <el-progress v-if="collecting||progress===100" :percentage="progress" :status="progress===100?'success':''" style="margin:20px 0" />

          <el-table :data="collectResults" border v-loading="collecting" style="margin-top:20px">
            <el-table-column type="selection" width="55" />
            <el-table-column label="图片" width="80">
              <template #default="{row}"><el-image :src="row.images?.[0]" style="width:50px;height:50px" fit="cover" /></template>
            </el-table-column>
            <el-table-column prop="title" label="商品名称" show-overflow-tooltip />
            <el-table-column label="规格数" width="80"><template #default="{row}">{{row.specs?.length||0}}</template></el-table-column>
            <el-table-column prop="origin_price" label="参考价" width="120" />
          </el-table>

          <div style="margin-top:20px;text-align:right" v-if="collectResults.length">
            <el-button type="primary" @click="batchImport">批量导入选中商品</el-button>
            <el-tag type="warning" style="margin-left:10px">提示: 采集价格默认为0，需在商品列表手动修改后上架</el-tag>
          </div>
        </el-tab-pane>

        <el-tab-pane label="采集日志" name="logs">
          <el-table :data="collectLogs" border empty-text="暂无采集记录">
            <el-table-column label="任务ID" prop="task_id" width="180" />
            <el-table-column label="平台" prop="platform" width="80" />
            <el-table-column label="计划/成功/失败" width="150">
              <template #default="{row}">{{row.total_num}}/{{row.success_num}}/{{row.fail_num}}</template>
            </el-table-column>
            <el-table-column label="状态" width="80">
              <template #default="{row}"><el-tag :type="row.status===1?'success':row.status===2?'danger':'warning'" size="small">{{{0:'进行中',1:'完成',2:'异常'}[row.status]}}</el-tag></template>
            </el-table-column>
            <el-table-column label="时间" prop="create_time" width="160" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const activeTab = ref('config')
const saving = ref(false)
const collecting = ref(false)
const progress = ref(0)
const apiConfig = reactive({ type: 'yihaotong', app_key: '', app_secret: '', api_url: '' })
const collectForm = reactive({ platform: 'taobao', type: 1, content: '', local_image: true, import_spec: true })
const collectResults = ref([])
const collectLogs = ref([])

onMounted(async () => {
  try { const res = await request.get('/collect/config'); Object.assign(apiConfig, res) } catch(e) {}
  try { const res = await request.get('/collect/logs'); collectLogs.value = res || [] } catch(e) {}
})

const saveConfig = async () => {
  saving.value = true
  await request.post('/collect/config', apiConfig)
  ElMessage.success('配置保存成功')
  saving.value = false
}

const startCollect = async () => {
  if (!collectForm.content.trim()) return ElMessage.warning('请输入采集内容')
  collecting.value = true; progress.value = 0; collectResults.value = []
  try {
    const lines = collectForm.content.trim().split('\n').filter(l => l.trim())
    for (let i = 0; i < lines.length; i++) {
      const res = await request.post('/collect/execute', { ...collectForm, content: lines[i] })
      console.log('[采集] 返回结果:', res)
      if (res) collectResults.value.push(res)
      progress.value = Math.round(((i+1) / lines.length) * 100)
    }
    ElMessage.success('采集完成，请预览结果')
  } catch(e) {
    ElMessage.error('采集出错: ' + e.message)
  }
  collecting.value = false
}

const batchImport = async () => {
  ElMessage.success('已提交批量导入请求，请在商品列表中查看')
}
</script>
