<template>
  <div class="migration-page">
    <div class="page-header">
      <h2>📦 一键搬家 - 数据迁移</h2>
      <p class="desc">支持LiteMall之间互导，以及从 CRMEB / ShopXO / LikeShop 无缝迁入</p>
    </div>

    <el-tabs v-model="activeTab" class="migration-tabs">
      <!-- ====== 导出 Tab ====== -->
      <el-tab-pane label="📤 数据导出" name="export">
        <el-card shadow="never" class="section-card">
          <template #header>
            <span>导出设置</span>
          </template>
          
          <el-form label-width="140px">
            <el-form-item label="导出内容">
              <el-checkbox-group v-model="exportOptions">
                <el-checkbox label="products" checked>商品数据</el-checkbox>
                <el-checkbox label="categories" checked>分类数据</el-checkbox>
                <el-checkbox label="users">用户数据</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <el-form-item label="导出格式">
              <el-radio-group v-model="exportFormat">
                <el-radio value="json">LiteMall 标准 JSON</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="doExport" :loading="exporting" size="large">
                🚀 开始导出
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 导出结果 -->
        <el-card v-if="exportResult" shadow="never" class="section-card result-card">
          <template #header>
            <span style="color:#7C3AED">✅ 导出完成</span>
          </template>
          <div class="result-grid">
            <div class="result-item">
              <div class="result-label">商品</div>
              <div class="result-value">{{ exportResult.stats.products || 0 }}</div>
            </div>
            <div class="result-item">
              <div class="result-label">SKU</div>
              <div class="result-value">{{ exportResult.stats.skus || 0 }}</div>
            </div>
            <div class="result-item">
              <div class="result-label">分类</div>
              <div class="result-value">{{ exportResult.stats.categories || 0 }}</div>
            </div>
            <div class="result-item">
              <div class="result-label">用户</div>
              <div class="result-value">{{ exportResult.stats.users || 0 }}</div>
            </div>
          </div>
          <div style="margin-top:16px">
            <el-button type="primary" @click="downloadExport" :disabled="!exportFile">
              ⬇ 下载导出文件
            </el-button>
            <el-button @click="copyExportToClipboard">
              📋 复制JSON到剪贴板
            </el-button>
          </div>
        </el-card>
      </el-tab-pane>

      <!-- ====== 导入 Tab ====== -->
      <el-tab-pane label="📥 数据导入" name="import">
        <!-- 文件上传 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <span>📄 上传旧商城数据文件</span>
          </template>
          <el-upload
            drag
            accept=".sql,.json,.csv,.xlsx,.xls"
            :auto-upload="false"
            :show-file-list="true"
            :on-change="handleFileChange"
            :limit="1"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">拖拽文件到此处，或 <em>点击选择文件</em></div>
            <template #tip>
              <div style="color:#999;font-size:12px;margin-top:8px">
                自动识别平台，支持 .sql 数据库文件 / .xlsx Excel导出 / .json / .csv
              </div>
            </template>
          </el-upload>
        </el-card>

        <!-- 图片地址（选填） -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <span>🖼️ 商品图片下载地址（选填）</span>
          </template>
          <el-input v-model="imageBaseUrl" placeholder="https://www.旧商城域名.com" style="width:100%">
            <template #prepend>原站地址</template>
          </el-input>
          <div style="font-size:12px;color:#999;margin-top:6px">填了系统会自动下载商品图片到新商城，不填保留原地址链接</div>
        </el-card>

        <!-- 一键搬家按钮 + 状态 -->
        <div v-if="!importing && !importDone">
          <el-button
            type="primary"
            :disabled="!uploadedFile && !importJson"
            @click="simpleImport"
            size="large"
            style="width:100%;height:48px;font-size:16px"
            :loading="converting">
            🚀 {{ !uploadedFile ? '请先上传文件' : '开始搬家' }}
          </el-button>
        </div>

        <!-- 处理中 -->
        <el-card v-if="converting || importing" shadow="never" class="section-card">
          <div style="text-align:center;padding:16px">
            <el-progress :percentage="progressPct" :status="progressStatus" :stroke-width="6" />
            <div style="margin-top:8px;color:#666;font-size:14px">{{ progressText }}</div>
          </div>
        </el-card>

        <!-- 结果卡片 -->
        <el-card v-if="importDone" shadow="never" class="section-card" style="border:1px solid #7C3AED33">
          <template #header>
            <span style="color:#059669">✅ 搬家完成</span>
          </template>
          <div class="result-grid">
            <div class="result-item">
              <div class="result-label">📦 商品</div>
              <div class="result-value">{{ importStats.products || 0 }}</div>
            </div>
            <div class="result-item">
              <div class="result-label">🏷️ SKU</div>
              <div class="result-value">{{ importStats.skus || 0 }}</div>
            </div>
            <div class="result-item">
              <div class="result-label">📂 分类</div>
              <div class="result-value">{{ importStats.categories || 0 }}</div>
            </div>
            <div class="result-item">
              <div class="result-label">👤 用户</div>
              <div class="result-value">{{ importStats.users || 0 }}</div>
            </div>
          </div>
          <div style="margin-top:12px;text-align:center">
            <el-button @click="resetImport" type="primary">🔄 继续搬家</el-button>
          </div>
        </el-card>

        <!-- 搬家链路说明 -->
        <el-card v-if="importDone" shadow="never" class="section-card" style="background:#f0f7ff;border-color:#dbeafe">
          <div style="font-size:12px;line-height:2;color:#555">
            <div style="font-weight:700;color:#1e40af;margin-bottom:4px">✅ 搬家完整链路</div>
            📦 商品 → CRMEB eb_store_product(67列)<br>
            🏷️ SKU → eb_store_product_attr_value + eb_store_product_attr<br>
            📂 分类 → eb_store_category（PID自动映射）<br>
            👤 用户 → eb_user（电话去重/余额/积分/等级）<br>
            🖼️ 轮播图 → slider_image JSON.parse → 前端自动展示<br>
            📝 详情图 → CRMEB无description列，自动用轮播图填充<br>
            🎯 价格 → 结构化specs + 自动选中首个SKU → 显示SKU.price
          </div>
        </el-card>
      </el-tab-pane>

      <!-- ====== 迁移历史 Tab ====== -->
      <el-tab-pane label="📋 迁移历史" name="history">
        <el-table :data="historyList" v-loading="loadingHistory" border stripe style="width:100%">
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="type" label="类型" width="80">
            <template #default="{ row }">
              <el-tag :type="row.type === 'export' ? 'warning' : 'success'">
                {{ row.type === 'export' ? '导出' : '导入' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 'success' ? 'success' : 'danger'" size="small">
                {{ row.status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="source_platform" label="来源平台" width="120" />
          <el-table-column label="统计" min-width="200">
            <template #default="{ row }">
              <span v-if="row.stats" class="stats-text">{{ row.stats }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="时间" width="180" />
        </el-table>
      </el-tab-pane>

      <!-- ====== 支持的平台 Tab ====== -->
      <el-tab-pane label="ℹ️ 支持的平台" name="formats">
        <el-card shadow="never">
          <template #header><span>📤 导出到LiteMall格式</span></template>
          <p style="font-size:14px;color:#666;margin-bottom:12px">可以将LiteMall数据导出为标准JSON包，直接导入其他LiteMall实例</p>
          <el-table :data="formats.exportFormats" border stripe>
            <el-table-column prop="name" label="导出格式" />
            <el-table-column prop="description" label="说明" />
          </el-table>
        </el-card>

        <el-card shadow="never" style="margin-top:16px">
          <template #header><span>📥 从以下平台迁入</span></template>
          <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px;padding:4px">
            <div v-for="fmt in formats.importFormats" :key="fmt.id" class="platform-card">
              <div class="platform-icon">{{ fmt.icon || '🛒' }}</div>
              <div class="platform-name">{{ fmt.name }}</div>
              <div class="platform-desc">{{ fmt.description }}</div>
            </div>
          </div>
        </el-card>

        <el-card shadow="never" style="margin-top:16px">
          <template #header><span>🔮 即将支持（开发中）</span></template>
          <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px;padding:4px">
            <div v-for="fmt in formats.futureFormats" :key="fmt.id" class="platform-card future">
              <div class="platform-icon">🚧</div>
              <div class="platform-name">{{ fmt.name }}</div>
              <div class="platform-desc">{{ fmt.description }}</div>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'


const activeTab = ref('export')
const exportOptions = ref(['products', 'categories'])
const exportFormat = ref('json')
const exporting = ref(false)
const exportResult = ref(null)
const exportFile = ref('')
const exportJsonContent = ref('')

const importJson = ref('')
const importPreview = ref(null)
const importResult = ref(null)
const importing = ref(false)
const converting = ref(false)
const importDone = ref(false)
const importStats = ref({})
const progressPct = ref(0)
const progressStatus = ref('')
const progressText = ref('')
const conflictStrategy = ref('skip')
const uploadedFile = ref(null)
const imageBaseUrl = ref('')
const downloadImages = ref(true)
const uploadFileType = ref('json')
const detectedPlatform = ref('')

const historyList = ref([])
const loadingHistory = ref(false)
const formats = ref({
  exportFormats: [],
  importFormats: [],
  futureFormats: []
})

const API_BASE = '/migration/api'

async function api(path, options = {}) {
  try {
    const resp = await fetch(API_BASE + path, {
      method: options.method || 'GET',
      headers: { 'Content-Type': 'application/json' },
      body: options.body || undefined
    })
    const result = await resp.json()
    // portal API 返回 { code, message, data }
    if (result.code === 0 || result.code === undefined) {
      return { code: 0, data: result.data || result }
    }
    return result
  } catch (err) {
    ElMessage.error('请求失败: ' + err.message)
    return { code: 1, message: err.message }
  }
}

// ---- 导出 ----
async function doExport() {
  exporting.value = true
  exportResult.value = null
  try {
    const res = await api('/export', {
      method: 'POST',
      body: JSON.stringify({
        includeProducts: exportOptions.value.includes('products'),
        includeCategories: exportOptions.value.includes('categories'),
        includeUsers: exportOptions.value.includes('users'),
        includeOrders: false
      })
    })
    if (res.code === 0) {
      exportResult.value = res.data
      // 下载文件
      exportFile.value = res.data.downloadUrl
      // 同时获取JSON内容以便复制
      const fileResp = await fetch(res.data.downloadUrl)
      exportJsonContent.value = await fileResp.text()
      ElMessage.success(`导出成功！共 ${res.data.stats.products || 0} 个商品`)
    } else {
      ElMessage.error(res.message)
    }
  } catch (err) {
    ElMessage.error('导出失败: ' + err.message)
  } finally {
    exporting.value = false
  }
}

function downloadExport() {
  if (exportFile.value) {
    window.open(exportFile.value, '_blank')
  }
}

function copyExportToClipboard() {
  if (!exportJsonContent.value) return
  navigator.clipboard.writeText(exportJsonContent.value).then(() => {
    ElMessage.success('JSON已复制到剪贴板')
  }).catch(() => {
    // fallback
    const ta = document.createElement('textarea')
    ta.value = exportJsonContent.value
    document.body.appendChild(ta)
    ta.select()
    document.execCommand('copy')
    document.body.removeChild(ta)
    ElMessage.success('JSON已复制到剪贴板')
  })
}

// ---- 导入预览 ----
async function simpleImport() {
  // 从上传文件读取内容
  if (!uploadedFile.value && !importJson.value) {
    ElMessage.warning('请先上传数据文件')
    return
  }
  
  converting.value = true
  importing.value = false
  importDone.value = false
  progressPct.value = 10
  progressStatus.value = ''
  progressText.value = '正在读取文件...'
  
  try {
    let content, fileType
    
    if (uploadedFile.value && uploadedFile.value.raw) {
      const file = uploadedFile.value.raw
      const isBin = file.name.match(/\.xlsx?$/i)
      fileType = isBin ? 'xlsx' : (file.name.match(/\.sql$/i) ? 'sql' : file.name.match(/\.csv$/i) ? 'csv' : 'json')
      
      if (isBin) {
        const buf = await file.arrayBuffer()
        content = btoa(String.fromCharCode(...new Uint8Array(buf)))
      } else {
        content = await file.text()
      }
    } else {
      content = importJson.value
      fileType = 'json'
    }
    
    // 检测平台
    let adapter = 'crmeB'
    progressPct.value = 25
    progressText.value = '正在识别数据来源...'
    
    if (fileType === 'xlsx') {
      adapter = 'crmeB-xlsx'
    } else if (fileType !== 'sql') {
      const det = await api('/detect', {
        method: 'POST',
        body: JSON.stringify({ type: fileType, content: content.substring(0, 3000) })
      })
      if (det.code === 0 && det.data?.adapter) adapter = det.data.adapter
    }
    
    // 转换数据
    progressPct.value = 45
    progressText.value = '正在解析数据...'
    const conv = await api('/convert', {
      method: 'POST',
      body: JSON.stringify({ adapter, type: fileType, content })
    })
    
    if (conv.code !== 0) {
      ElMessage.error(conv.message || '解析失败')
      resetImport()
      return
    }
    
    const data = conv.data?.data || conv.data
    
    // 导入
    progressPct.value = 70
    progressText.value = '正在导入数据...'
    const imp = await api('/import', {
      method: 'POST',
      body: JSON.stringify({
        data,
        conflictStrategy: 'skip',
        importUsers: true,
        importCategories: true,
        importProducts: true,
        imageBaseUrl: imageBaseUrl.value
      })
    })
    
    progressPct.value = 100
    progressText.value = '导入完成！'
    
    if (imp.code === 0 || imp.data?.success) {
      importStats.value = imp.data?.imported || imp.imported || {}
      importDone.value = true
      ElMessage.success('搬家成功！')
      loadHistory()
    } else {
      ElMessage.error(imp.data?.error || imp.message || '导入失败')
      resetImport()
    }
  } catch (err) {
    ElMessage.error('搬家失败: ' + err.message)
    resetImport()
  } finally {
    converting.value = false
    importing.value = false
    progressPct.value = 0
  }
}

function resetImport() {
  importDone.value = false
  importStats.value = {}
  converting.value = false
  importing.value = false
}

async function previewImport() {
  if (uploadFileType.value === 'xlsx' && uploadedFile.value) {
    // xlsx直接走CRMEB适配器转换
    importPreview.value = null
    importResult.value = null
    try {
      const conv = await api('/adapters/convert', {
        method: 'POST',
        body: JSON.stringify({
          adapter: 'crmeB-xlsx',
          type: 'xlsx',
          content: uploadedFile.value
        })
      })
      if (conv.code === 0) {
        detectedPlatform.value = 'crmeB-xlsx'
        importPreview.value = {
          source: '📊 ' + conv.data.manifest.source,
          stats: conv.data.preview.stats
        }
        importJson.value = JSON.stringify(conv.data.data)
        ElMessage.success('识别成功: ' + conv.data.manifest.source + '，共' + conv.data.preview.stats.products + '个商品')
      } else {
        ElMessage.error(conv.message || '解析失败')
      }
    } catch (err) {
      ElMessage.error('解析失败: ' + err.message)
    }
    return
  }
  
  let data = importJson.value
  if (!data && uploadedFile.value) {
    data = uploadedFile.value
  }
  if (!data) {
    ElMessage.warning('请粘贴JSON或上传文件')
    return
  }

  importPreview.value = null
  importResult.value = null

  try {
    const res = await api('/preview', {
      method: 'POST',
      body: JSON.stringify({ content: data })
    })
    if (res.code === 0) {
      importPreview.value = { ...res.data, source: 'LiteMall' }
    } else {
      ElMessage.error(res.message)
    }
  } catch (err) {
    ElMessage.error('预览失败: ' + err.message)
  }
}

function handleFileChange(uploadFile) {
  // 保存原生File对象供simpleImport使用
  uploadedFile.value = { raw: uploadFile.raw, name: uploadFile.name }
  const ext = uploadFile.name.split('.').pop().toLowerCase()
  uploadFileType.value = ['xlsx','xls'].includes(ext) ? 'xlsx' : ext === 'sql' ? 'sql' : ext === 'csv' ? 'csv' : 'json'
  importJson.value = ''
  ElMessage.success('已选择文件: ' + uploadFile.name + '，点击"开始搬家"导入')
}

function clearUpload() {
  uploadedFile.value = null
  importJson.value = ''
  importPreview.value = null
  importResult.value = null
  uploadFileType.value = 'json'
  detectedPlatform.value = ''
}

// ---- 导入执行 ----
async function doImport() {
  let data = importJson.value
  if (!data) {
    ElMessage.warning('请先导入数据')
    return
  }

  importing.value = true
  try {
    const res = await api('/import', {
      method: 'POST',
      body: JSON.stringify({
        content: data,
        conflictStrategy: conflictStrategy.value,
        importCategories: true,
        importProducts: true,
        importUsers: true,
        downloadImages: downloadImages.value,
        imageBaseUrl: imageBaseUrl.value
      })
    })
    importResult.value = res.data || res
    if (res.code === 0) {
      ElMessage.success('导入成功！')
      loadHistory()
    } else {
      ElMessage.error(res.message)
    }
  } catch (err) {
    ElMessage.error('导入失败: ' + err.message)
  } finally {
    importing.value = false
  }
}

// ---- 历史 ----
async function loadHistory() {
  loadingHistory.value = true
  try {
    const res = await api('/history')
    if (res.code === 0) {
      historyList.value = (res.data || []).map(item => ({
        ...item,
        stats: item.stats ? (() => {
          try { return JSON.stringify(JSON.parse(item.stats)) } catch { return item.stats }
        })() : '-'
      }))
    }
  } catch (err) {
    console.error('加载历史失败:', err)
  } finally {
    loadingHistory.value = false
  }
}

// ---- 格式 ----
async function loadFormats() {
  try {
    const res = await api('/formats')
    if (res.code === 0) {
      formats.value = res.data
    }
  } catch (err) {
    console.error('加载格式失败:', err)
  }
}

onMounted(() => {
  loadHistory()
  loadFormats()
})
</script>

<style scoped>
.migration-page {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
}
.page-header h2 {
  font-size: 22px;
  color: #1a1a2e;
  margin: 0 0 6px 0;
}
.page-header .desc {
  color: #999;
  font-size: 13px;
  margin: 0;
}
.section-card {
  margin-bottom: 16px;
}
.result-card {
  border: 1px solid #7C3AED33;
}
.result-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}
.result-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}
.result-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}
.result-value {
  font-size: 24px;
  font-weight: 700;
  color: #7C3AED;
}
.stats-text {
  font-size: 12px;
  color: #666;
  word-break: break-all;
}

.platform-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  border: 1px solid #eee;
  transition: all .2s;
}
.platform-card:hover {
  border-color: #7C3AED;
  box-shadow: 0 2px 12px rgba(124,58,237,0.1);
}
.platform-card.future {
  opacity: 0.6;
}
.platform-card .platform-icon {
  font-size: 32px;
  margin-bottom: 8px;
}
.platform-card .platform-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}
.platform-card .platform-desc {
  font-size: 12px;
  color: #999;
}
</style>
