<template>
  <el-dialog
    v-model="visible"
    title="用户导入"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-steps :active="step" finish-status="success" align-center style="margin-bottom: 20px">
      <el-step title="上传文件" />
      <el-step title="列映射设置" />
      <el-step title="导入结果" />
    </el-steps>

    <!-- Step 1: Upload -->
    <div v-if="step === 0" class="upload-container">
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :limit="1"
        accept=".xlsx,.xls,.csv"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 .xlsx, .xls, .csv 格式文件
          </div>
        </template>
      </el-upload>
    </div>

    <!-- Step 2: Mapping -->
    <div v-if="step === 1" class="mapping-container">
      <div class="preview-header">
        <el-form inline>
          <el-form-item label="数据开始行">
            <el-input-number v-model="startRow" :min="1" />
          </el-form-item>
        </el-form>
      </div>

      <el-alert title="请选择Excel列与系统字段的对应关系" type="info" :closable="false" style="margin-bottom: 10px" />

      <el-form label-width="120px">
        <el-form-item label="手机号 (必填)">
          <el-select v-model="mapping.mobile" placeholder="选择列">
            <el-option
              v-for="(header, index) in headers"
              :key="index"
              :label="`列 ${header}`"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名">
          <el-select v-model="mapping.name" placeholder="选择列">
            <el-option
              v-for="(header, index) in headers"
              :key="index"
              :label="`列 ${header}`"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="英文名">
          <el-select v-model="mapping.english_name" placeholder="选择列">
            <el-option
              v-for="(header, index) in headers"
              :key="index"
              :label="`列 ${header}`"
              :value="index"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div class="data-preview">
        <h4>数据预览 (前10行)</h4>
        <el-table :data="previewData" border height="200" size="small">
          <el-table-column
            v-for="(header, index) in headers"
            :key="index"
            :label="header"
            min-width="100"
          >
            <template #default="scope">
              {{ scope.row[index] }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- Step 3: Result -->
    <div v-if="step === 2" class="result-container">
      <div class="result-summary">
        <el-result
          :icon="importResult.fail_count > 0 ? 'warning' : 'success'"
          :title="importResult.fail_count > 0 ? '导入完成 (有失败)' : '导入成功'"
          :sub-title="`总计: ${importResult.total_count}, 成功: ${importResult.success_count}, 失败: ${importResult.fail_count}`"
        >
          <template #extra>
             <el-button type="primary" @click="downloadSuccessRecords" v-if="importResult.success_count > 0">导出成功记录(含密码)</el-button>
             <el-button type="danger" @click="downloadFailLog" v-if="importResult.fail_count > 0">导出失败日志</el-button>
          </template>
        </el-result>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose" v-if="step !== 2">取消</el-button>
        <el-button @click="handleClose" v-if="step === 2">关闭</el-button>
        
        <el-button type="primary" @click="uploadAndPreview" v-if="step === 0" :disabled="!selectedFile">
          下一步
        </el-button>
        
        <el-button type="primary" @click="executeImport" v-if="step === 1" :loading="importing">
          开始导入
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request' // Assuming request utility exists

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(props.modelValue)
const step = ref(0)
const selectedFile = ref<File | null>(null)
const headers = ref<string[]>([])
const previewData = ref<any[]>([])
const startRow = ref(2) // Default start row 2 (assuming row 1 is header)
const importing = ref(false)

const mapping = reactive({
  mobile: null as number | null,
  name: null as number | null,
  english_name: null as number | null
})

const importResult = ref({
  total_count: 0,
  success_count: 0,
  fail_count: 0,
  result_data: [] as any[]
})

// Watch prop change
import { watch } from 'vue'
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    reset()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

const reset = () => {
  step.value = 0
  selectedFile.value = null
  headers.value = []
  previewData.value = []
  startRow.value = 2
  mapping.mobile = null
  mapping.name = null
  mapping.english_name = null
  importResult.value = { total_count: 0, success_count: 0, fail_count: 0, result_data: [] }
}

const handleFileChange = (file: any) => {
  selectedFile.value = file.raw
}

const uploadAndPreview = async () => {
  if (!selectedFile.value) return

  const formData = new FormData()
  formData.append('file', selectedFile.value)

  try {
    const res = await request.post('/users/import/preview', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    headers.value = res.data.headers
    previewData.value = res.data.preview_data
    
    // Auto guess mapping if headers match
    // Simplified logic: If header row exists in preview data
    // But preview endpoint returns data including header row usually? 
    // Backend logic: "pd.read_excel(..., header=None)". So row 0 is likely headers.
    
    step.value = 1
  } catch (error) {
    ElMessage.error('文件解析失败')
    console.error(error)
  }
}

const executeImport = async () => {
  if (mapping.mobile === null) {
    ElMessage.warning('请至少映射手机号列')
    return
  }

  importing.value = true
  const formData = new FormData()
  if (selectedFile.value) {
    formData.append('file', selectedFile.value)
  }
  formData.append('start_row', startRow.value.toString())
  
  // Filter out nulls
  const cleanMapping: any = { mobile: mapping.mobile }
  if (mapping.name !== null) cleanMapping.name = mapping.name
  if (mapping.english_name !== null) cleanMapping.english_name = mapping.english_name
  
  formData.append('mapping', JSON.stringify(cleanMapping))

  try {
    const res = await request.post('/users/import', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    importResult.value = res.data
    step.value = 2
    emit('success')
  } catch (error) {
    ElMessage.error('导入失败')
  } finally {
    importing.value = false
  }
}

const handleClose = () => {
  visible.value = false
}

// Download helpers
const downloadSuccessRecords = () => {
  const successes = importResult.value.result_data.filter((r: any) => r.status === 'success')
  if (successes.length === 0) return
  
  // Create CSV content
  const header = ['Row', 'Mobile', 'Name', 'English Name', 'Initial Password']
  const rows = successes.map((r: any) => [
    r.row, 
    r.mobile, 
    r.name, 
    r.english_name, 
    r.initial_password
  ])
  
  downloadCSV(header, rows, `import_success_${new Date().getTime()}.csv`)
}

const downloadFailLog = () => {
  const fails = importResult.value.result_data.filter((r: any) => r.status === 'fail')
  if (fails.length === 0) return
  
  const header = ['Row', 'Error Message']
  const rows = fails.map((r: any) => [r.row, r.error])
  
  downloadCSV(header, rows, `import_fail_${new Date().getTime()}.csv`)
}

const downloadCSV = (header: string[], rows: any[][], filename: string) => {
  let csvContent = "data:text/csv;charset=utf-8,\uFEFF" // Add BOM
  csvContent += header.join(",") + "\r\n"
  
  rows.forEach(rowArray => {
    const row = rowArray.map(field => {
        const str = String(field || '')
        // Escape quotes
        if (str.includes(',') || str.includes('"') || str.includes('\n')) {
            return `"${str.replace(/"/g, '""')}"`
        }
        return str
    }).join(",")
    csvContent += row + "\r\n"
  })
  
  const encodedUri = encodeURI(csvContent)
  const link = document.createElement("a")
  link.setAttribute("href", encodedUri)
  link.setAttribute("download", filename)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<style scoped>
.upload-container {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}
.mapping-container {
  margin-top: 20px;
}
.preview-header {
  margin-bottom: 20px;
}
.data-preview {
  margin-top: 20px;
}
.result-container {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}
</style>

