<template>
  <el-dialog
    v-model="visible"
    title="批量导入资产"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-steps :active="currentStep" align-center class="steps">
      <el-step title="上传文件" />
      <el-step title="数据预览" />
      <el-step title="导入结果" />
    </el-steps>

    <div class="import-content">
      <!-- 步骤1: 上传文件 -->
      <div v-show="currentStep === 0" class="step-content">
        <el-alert
          title="请按照模板格式填写资产信息"
          type="info"
          :closable="false"
          show-icon
          class="mb-4"
        >
          <template #default>
            <div>支持文件格式：.xlsx、.xls</div>
            <div>单次最多导入1000条数据</div>
          </template>
        </el-alert>

        <div class="template-download">
          <el-button type="primary" plain @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            下载导入模板
          </el-button>
        </div>

        <el-upload
          ref="uploadRef"
          class="upload-area"
          drag
          :auto-upload="false"
          :limit="1"
          accept=".xlsx,.xls"
          :on-change="handleFileChange"
          :on-exceed="handleExceed"
          :file-list="fileList"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只支持 .xlsx 或 .xls 格式的Excel文件
            </div>
          </template>
        </el-upload>
      </div>

      <!-- 步骤2: 数据预览 -->
      <div v-show="currentStep === 1" class="step-content">
        <div class="preview-header">
          <el-alert
            :title="`共 ${previewData.length} 条数据，其中 ${errorCount} 条有错误`"
            :type="errorCount > 0 ? 'warning' : 'success'"
            :closable="false"
            show-icon
          />
        </div>

        <el-table
          :data="previewData"
          border
          max-height="400"
          :row-class-name="getRowClassName"
        >
          <el-table-column type="index" label="行号" width="60" />
          <el-table-column prop="assetCode" label="资产编码" width="150" />
          <el-table-column prop="assetName" label="资产名称" min-width="150" />
          <el-table-column prop="deviceTypeName" label="设备类型" width="120" />
          <el-table-column prop="brandName" label="品牌" width="120" />
          <el-table-column prop="modelName" label="型号" width="120" />
          <el-table-column prop="serialNumber" label="序列号" width="140" />
          <el-table-column prop="orgName" label="所属网点" width="120" />
          <el-table-column prop="errors" label="错误信息" min-width="200">
            <template #default="{ row }">
              <span v-if="row.errors && row.errors.length" class="error-text">
                {{ row.errors.join('; ') }}
              </span>
              <span v-else class="success-text">数据正常</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 步骤3: 导入结果 -->
      <div v-show="currentStep === 2" class="step-content">
        <div v-if="importResult" class="result-summary">
          <el-result
            :icon="importResult.failed === 0 ? 'success' : 'warning'"
            :title="importResult.failed === 0 ? '导入成功' : '导入完成（部分失败）'"
          >
            <template #sub-title>
              <div class="statistics">
                <div class="stat-item">
                  <div class="stat-value">{{ importResult.total }}</div>
                  <div class="stat-label">总计</div>
                </div>
                <div class="stat-item success">
                  <div class="stat-value">{{ importResult.success }}</div>
                  <div class="stat-label">成功</div>
                </div>
                <div class="stat-item error">
                  <div class="stat-value">{{ importResult.failed }}</div>
                  <div class="stat-label">失败</div>
                </div>
              </div>
            </template>
            <template #extra>
              <div v-if="importResult.errors && importResult.errors.length" class="error-list">
                <el-divider content-position="left">失败明细</el-divider>
                <el-table :data="importResult.errors" border max-height="300">
                  <el-table-column prop="row" label="行号" width="80" />
                  <el-table-column prop="message" label="错误信息" />
                </el-table>
                <el-button
                  type="danger"
                  plain
                  class="mt-3"
                  @click="exportErrorLog"
                >
                  <el-icon><Download /></el-icon>
                  导出错误日志
                </el-button>
              </div>
            </template>
          </el-result>
        </div>

        <div v-if="importing" class="importing-status">
          <el-progress
            :percentage="importProgress"
            :status="importProgress === 100 ? 'success' : undefined"
          />
          <p class="progress-text">{{ importProgressText }}</p>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          v-if="currentStep > 0"
          @click="handlePrevious"
        >
          上一步
        </el-button>
        <el-button
          v-if="currentStep < 2"
          type="primary"
          :disabled="!canNext"
          @click="handleNext"
        >
          下一步
        </el-button>
        <el-button
          v-if="currentStep === 1 && errorCount === 0"
          type="primary"
          :loading="importing"
          @click="handleImport"
        >
          开始导入
        </el-button>
        <el-button
          v-if="currentStep === 2"
          type="primary"
          @click="handleClose"
        >
          完成
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, UploadFilled } from '@element-plus/icons-vue'
import { importAssets } from '@/api/assets'
import type { UploadFile, UploadUserFile } from 'element-plus'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const currentStep = ref(0)
const uploadRef = ref()
const fileList = ref<UploadUserFile[]>([])
const previewData = ref<any[]>([])
const importResult = ref<any>(null)
const importing = ref(false)
const importProgress = ref(0)
const importProgressText = ref('')

// 错误数量
const errorCount = computed(() => {
  return previewData.value.filter(row => row.errors && row.errors.length > 0).length
})

// 是否可以下一步
const canNext = computed(() => {
  if (currentStep.value === 0) {
    return fileList.value.length > 0
  }
  if (currentStep.value === 1) {
    return true
  }
  return false
})

// 文件变化
const handleFileChange = (file: UploadFile) => {
  fileList.value = [file]
  // 解析Excel文件
  parseExcel(file.raw as File)
}

// 文件超出限制
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件')
}

// 解析Excel文件（模拟）
const parseExcel = async (file: File) => {
  // TODO: 实际应该使用xlsx库解析
  // 这里先模拟数据
  setTimeout(() => {
    previewData.value = [
      {
        assetCode: 'ASSET-20250124-0001',
        assetName: '联想台式机',
        deviceTypeName: '计算机',
        brandName: '联想',
        modelName: '启天M540',
        serialNumber: 'SN20240101001',
        orgName: '天河网点',
        errors: []
      },
      {
        assetCode: 'ASSET-20250124-0002',
        assetName: 'Dell笔记本',
        deviceTypeName: '计算机',
        brandName: 'Dell',
        modelName: 'Latitude 5420',
        serialNumber: 'SN20240101002',
        orgName: '天河网点',
        errors: ['设备类型不存在']
      },
      {
        assetCode: 'ASSET-20250124-0003',
        assetName: 'HP打印机',
        deviceTypeName: '打印机',
        brandName: 'HP',
        modelName: ' LaserJet Pro',
        serialNumber: 'SN20240101003',
        orgName: '越秀网点',
        errors: []
      }
    ]
  }, 500)
}

// 获取行类名
const getRowClassName = ({ row }: { row: any }) => {
  return row.errors && row.errors.length > 0 ? 'error-row' : ''
}

// 下载模板
const downloadTemplate = () => {
  // TODO: 实际应该从后端下载模板
  ElMessage.success('模板下载功能开发中')
}

// 导出错误日志
const exportErrorLog = () => {
  // TODO: 导出错误日志
  ElMessage.success('错误日志导出功能开发中')
}

// 下一步
const handleNext = () => {
  if (currentStep.value < 2) {
    currentStep.value++
  }
}

// 上一步
const handlePrevious = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 执行导入
const handleImport = async () => {
  if (!fileList.value[0]) {
    ElMessage.warning('请先上传文件')
    return
  }

  importing.value = true
  importProgress.value = 0
  importProgressText.value = '正在导入...'

  try {
    const file = fileList.value[0].raw as File
    const result = await importAssets(file, (percent) => {
      importProgress.value = percent
      importProgressText.value = `正在导入... ${percent}%`
    })

    importResult.value = result
    currentStep.value = 2

    if (result.failed === 0) {
      ElMessage.success('导入成功')
      emit('success')
    } else {
      ElMessage.warning(`导入完成，成功${result.success}条，失败${result.failed}条`)
    }
  } catch (error) {
    ElMessage.error('导入失败')
  } finally {
    importing.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  // 重置状态
  setTimeout(() => {
    currentStep.value = 0
    fileList.value = []
    previewData.value = []
    importResult.value = null
    importProgress.value = 0
  }, 300)
}
</script>

<style scoped lang="scss">
.steps {
  margin-bottom: 24px;
}

.import-content {
  min-height: 400px;

  .step-content {
    padding: 20px 0;
  }
}

.template-download {
  margin-bottom: 20px;
}

.upload-area {
  margin-top: 20px;
}

.preview-header {
  margin-bottom: 16px;
}

.error-text {
  color: #f56c6c;
}

.success-text {
  color: #67c23a;
}

:deep(.error-row) {
  background-color: #fef0f0;
}

.result-summary {
  .statistics {
    display: flex;
    justify-content: center;
    gap: 40px;
    margin: 20px 0;

    .stat-item {
      text-align: center;

      .stat-value {
        font-size: 32px;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
      }

      &.success .stat-value {
        color: #67c23a;
      }

      &.error .stat-value {
        color: #f56c6c;
      }
    }
  }

  .error-list {
    margin-top: 20px;
  }
}

.importing-status {
  padding: 40px 20px;

  .progress-text {
    text-align: center;
    margin-top: 16px;
    color: #606266;
  }
}

.mb-4 {
  margin-bottom: 16px;
}

.mt-3 {
  margin-top: 12px;
}
</style>
