/**
 * 数据导入页面
 */
import { useState, useEffect } from 'react';
import { View, Text, Image, ScrollView, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { pageImportTask, listImportTemplate, getImportErrors, createImportTask, cancelImportTask, downloadTemplate } from '../../api/import';
import type { ImportTask, ImportTemplate, ImportError } from '../../types/import';
import './import.scss';

const STATUS_MAP: Record<string, { label: string; color: string; icon: string }> = {
  pending: { label: '等待中', color: '#999', icon: '⏳' },
  uploading: { label: '上传中', color: '#007aff', icon: '⬆️' },
  parsing: { label: '解析中', color: '#5856d6', icon: '📄' },
  validating: { label: '校验中', color: '#ff9500', icon: '✓' },
  importing: { label: '导入中', color: '#007aff', icon: '📥' },
  completed: { label: '已完成', color: '#34c759', icon: '✅' },
  failed: { label: '失败', color: '#ff3b30', icon: '❌' },
  cancelled: { label: '已取消', color: '#999', icon: '🚫' }
};

const TYPE_MAP: Record<string, { label: string; icon: string }> = {
  user: { label: '用户数据', icon: '👤' },
  product: { label: '商品数据', icon: '📦' },
  order: { label: '订单数据', icon: '📋' },
  category: { label: '分类数据', icon: '📂' },
  banner: { label: 'Banner', icon: '🎨' },
  config: { label: '配置数据', icon: '⚙️' },
  custom: { label: '自定义', icon: '📝' }
};

export default function DataImport() {
  const [tasks, setTasks] = useState<ImportTask[]>([]);
  const [total, setTotal] = useState(0);
  const [templates, setTemplates] = useState<ImportTemplate[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('task');
  const [showErrors, setShowErrors] = useState<ImportError[]>([]);
  const [showTemplate, setShowTemplate] = useState<ImportTemplate | null>(null);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      const [taskData, templateData] = await Promise.all([
        pageImportTask({ page: 1, pageSize: 20 }),
        listImportTemplate()
      ]);
      setTasks(taskData.list);
      setTotal(taskData.total);
      setTemplates(templateData);
    } catch (e) {
      console.error('加载失败', e);
    } finally {
      setLoading(false);
    }
  };

  // 查看错误详情
  const handleViewErrors = async (taskId: string) => {
    try {
      const errors = await getImportErrors(taskId);
      setShowErrors(errors);
    } catch (e) {
      Taro.showToast({ title: '加载失败', icon: 'none' });
    }
  };

  // 取消任务
  const handleCancel = async (id: string) => {
    Taro.showModal({
      title: '确认取消',
      content: '确定要取消这个导入任务吗？',
      success: async (res) => {
        if (res.confirm) {
          await cancelImportTask(id);
          Taro.showToast({ title: '已取消', icon: 'success' });
          loadData();
        }
      }
    });
  };

  // 下载模板
  const handleDownloadTemplate = (template: ImportTemplate) => {
    downloadTemplate(template.type);
  };

  // 进度百分比
  const getProgressWidth = (task: ImportTask) => {
    if (task.status === 'completed') return '100%';
    if (task.status === 'failed' || task.status === 'cancelled') return '0%';
    return `${task.progress}%`;
  };

  return (
    <View className="data-import">
      {/* Tab 切换 */}
      <View className="tab-bar">
        <View 
          className={`tab-item ${activeTab === 'task' ? 'active' : ''}`}
          onClick={() => setActiveTab('task')}
        >
          导入记录
        </View>
        <View 
          className={`tab-item ${activeTab === 'template' ? 'active' : ''}`}
          onClick={() => setActiveTab('template')}
        >
          下载模板
        </View>
      </View>

      {/* 导入记录 */}
      {activeTab === 'task' && (
        <ScrollView className="task-list" scrollY>
          {loading ? (
            <View className="loading"><Text>加载中...</Text></View>
          ) : tasks.length === 0 ? (
            <View className="empty">
              <Text>暂无导入记录</Text>
            </View>
          ) : (
            tasks.map(task => (
              <View key={task.id} className="task-card">
                <View className="task-header">
                  <View className="task-info">
                    <Text className="task-icon">{TYPE_MAP[task.type]?.icon}</Text>
                    <View className="task-meta">
                      <Text className="task-name">{task.name}</Text>
                      <Text className="task-file">{task.fileName} ({task.fileSize})</Text>
                    </View>
                  </View>
                  <View 
                    className="task-status"
                    style={{ color: STATUS_MAP[task.status]?.color }}
                  >
                    {STATUS_MAP[task.status]?.icon} {STATUS_MAP[task.status]?.label}
                  </View>
                </View>

                {/* 进度条 */}
                {['uploading', 'parsing', 'validating', 'importing'].includes(task.status) && (
                  <View className="progress-section">
                    <View className="progress-bar">
                      <View 
                        className="progress-fill"
                        style={{ width: `${task.progress}%` }}
                      />
                    </View>
                    <Text className="progress-text">{task.progress}%</Text>
                  </View>
                )}

                {/* 统计 */}
                <View className="task-stats">
                  <View className="stat-item">
                    <Text className="stat-value">{task.total}</Text>
                    <Text className="stat-label">总数</Text>
                  </View>
                  <View className="stat-item success">
                    <Text className="stat-value">{task.success}</Text>
                    <Text className="stat-label">成功</Text>
                  </View>
                  <View className="stat-item error">
                    <Text className="stat-value">{task.failed}</Text>
                    <Text className="stat-label">失败</Text>
                  </View>
                </View>

                {/* 操作 */}
                <View className="task-actions">
                  <Text className="task-time">
                    {task.startTime ? `开始: ${task.startTime.slice(0, 16)}` : `创建: ${task.createTime.slice(0, 16)}`}
                  </Text>
                  <View className="action-btns">
                    {task.errorFile && (
                      <Button className="action-btn">下载错误文件</Button>
                    )}
                    {task.failed > 0 && (
                      <Button className="action-btn" onClick={() => handleViewErrors(task.id)}>
                        查看错误
                      </Button>
                    )}
                    {['pending', 'uploading', 'parsing', 'validating', 'importing'].includes(task.status) && (
                      <Button className="action-btn cancel" onClick={() => handleCancel(task.id)}>
                        取消
                      </Button>
                    )}
                  </View>
                </View>
              </View>
            ))
          )}
        </ScrollView>
      )}

      {/* 模板下载 */}
      {activeTab === 'template' && (
        <ScrollView className="template-list" scrollY>
          {templates.map(template => (
            <View key={template.id} className="template-card">
              <View className="template-header">
                <Text className="template-icon">{TYPE_MAP[template.type]?.icon}</Text>
                <View className="template-info">
                  <Text className="template-name">{template.name}</Text>
                  <Text className="template-desc">{template.description}</Text>
                </View>
              </View>

              <View className="template-fields">
                <Text className="fields-label">字段说明</Text>
                <View className="fields-list">
                  {template.fields.slice(0, 5).map(field => (
                    <View key={field.key} className="field-item">
                      <Text className="field-name">
                        {field.name}
                        {field.required && <Text className="required">*</Text>}
                      </Text>
                      <Text className="field-type">{field.type}</Text>
                      {field.example && (
                        <Text className="field-example">例: {field.example}</Text>
                      )}
                    </View>
                  ))}
                  {template.fields.length > 5 && (
                    <Text className="more-fields">更多字段...</Text>
                  )}
                </View>
              </View>

              <View className="template-actions">
                <Button 
                  className="download-btn"
                  onClick={() => setShowTemplate(template)}
                >
                  查看详情
                </Button>
                <Button 
                  className="download-btn primary"
                  onClick={() => handleDownloadTemplate(template)}
                >
                  下载模板
                </Button>
              </View>
            </View>
          ))}
        </ScrollView>
      )}

      {/* 错误详情弹窗 */}
      {showErrors.length > 0 && (
        <View className="modal-mask" onClick={() => setShowErrors([])}>
          <View className="error-modal" onClick={(e) => e.stopPropagation()}>
            <View className="modal-header">
              <Text className="modal-title">错误详情</Text>
              <Text className="modal-close" onClick={() => setShowErrors([])}>✕</Text>
            </View>
            <ScrollView className="modal-body" scrollY>
              {showErrors.map((error, index) => (
                <View key={index} className="error-item">
                  <View className="error-row">
                    <Text className="error-label">行号</Text>
                    <Text className="error-value">{error.row}</Text>
                  </View>
                  <View className="error-row">
                    <Text className="error-label">字段</Text>
                    <Text className="error-value">{error.field}</Text>
                  </View>
                  <View className="error-row">
                    <Text className="error-label">值</Text>
                    <Text className="error-value error-val">{error.value || '(空)'}</Text>
                  </View>
                  <View className="error-row">
                    <Text className="error-label">错误</Text>
                    <Text className="error-value error-msg">{error.error}</Text>
                  </View>
                  {error.suggestion && (
                    <View className="error-row suggestion">
                      <Text className="error-label">建议</Text>
                      <Text className="error-value">{error.suggestion}</Text>
                    </View>
                  )}
                </View>
              ))}
            </ScrollView>
          </View>
        </View>
      )}

      {/* 模板详情弹窗 */}
      {showTemplate && (
        <View className="modal-mask" onClick={() => setShowTemplate(null)}>
          <View className="template-modal" onClick={(e) => e.stopPropagation()}>
            <View className="modal-header">
              <Text className="modal-title">{showTemplate.name}</Text>
              <Text className="modal-close" onClick={() => setShowTemplate(null)}>✕</Text>
            </View>
            <ScrollView className="modal-body" scrollY>
              <Text className="template-desc-full">{showTemplate.description}</Text>
              
              <View className="fields-section">
                <Text className="section-title">字段定义</Text>
                {showTemplate.fields.map(field => (
                  <View key={field.key} className="field-detail">
                    <View className="field-header">
                      <Text className="field-name">{field.name}</Text>
                      {field.required && <Text className="required-tag">必填</Text>}
                    </View>
                    <View className="field-info">
                      <Text className="field-key">字段: {field.key}</Text>
                      <Text className="field-type">类型: {field.type}</Text>
                    </View>
                    {field.options && (
                      <Text className="field-options">选项: {field.options.join(', ')}</Text>
                    )}
                    {field.maxLength && (
                      <Text className="field-length">最大长度: {field.maxLength}</Text>
                    )}
                    {field.example && (
                      <Text className="field-example">示例: {field.example}</Text>
                    )}
                  </View>
                ))}
              </View>
            </ScrollView>
            <View className="modal-footer">
              <Button className="footer-btn" onClick={() => handleDownloadTemplate(showTemplate)}>
                下载模板
              </Button>
            </View>
          </View>
        </View>
      )}
    </View>
  );
}
