/**
 * 账单管理/导出页面
 */
import { useState, useEffect } from 'react';
import { View, Text, ScrollView, Button, Picker } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { pageExportTask, exportBill, deleteExportTask } from '../../api/import';
import type { ExportTask, ExportFormat, ExportType } from '../../types/import';
import './bills.scss';

const STATUS_MAP: Record<string, { label: string; color: string; icon: string }> = {
  pending: { label: '等待中', color: '#999', icon: '⏳' },
  processing: { label: '生成中', color: '#007aff', icon: '⚙️' },
  completed: { label: '已完成', color: '#34c759', icon: '✅' },
  failed: { label: '失败', color: '#ff3b30', icon: '❌' }
};

const FORMAT_MAP: Record<string, { label: string; icon: string }> = {
  xlsx: { label: 'Excel', icon: '📊' },
  csv: { label: 'CSV', icon: '📋' },
  json: { label: 'JSON', icon: '📄' },
  pdf: { label: 'PDF', icon: '📕' }
};

const TYPE_MAP: Record<string, { label: string; icon: string }> = {
  user: { label: '用户数据', icon: '👤' },
  order: { label: '订单数据', icon: '📋' },
  product: { label: '商品数据', icon: '📦' },
  bill: { label: '账单数据', icon: '💰' },
  log: { label: '日志数据', icon: '📝' },
  custom: { label: '自定义', icon: '⚙️' }
};

export default function BillExport() {
  const [tasks, setTasks] = useState<ExportTask[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [showExport, setShowExport] = useState(false);
  
  // 导出表单
  const [formData, setFormData] = useState({
    type: 'order' as ExportType,
    format: 'xlsx' as ExportFormat,
    startDate: '2026-01-01',
    endDate: '2026-04-12'
  });

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

  const loadTasks = async () => {
    setLoading(true);
    try {
      const data = await pageExportTask({ page: 1, pageSize: 20 });
      setTasks(data.list);
      setTotal(data.total);
    } catch (e) {
      console.error('加载失败', e);
    } finally {
      setLoading(false);
    }
  };

  // 创建导出任务
  const handleExport = async () => {
    try {
      const task = await exportBill({
        startDate: formData.startDate,
        endDate: formData.endDate,
        format: formData.format
      });
      
      Taro.showToast({ title: '导出任务已创建', icon: 'success' });
      setShowExport(false);
      loadTasks();
    } catch (e) {
      Taro.showToast({ title: '创建失败', icon: 'none' });
    }
  };

  // 下载
  const handleDownload = (task: ExportTask) => {
    if (task.downloadUrl) {
      Taro.showToast({ title: '开始下载...', icon: 'loading' });
      console.log(`Downloading: ${task.downloadUrl}`);
    }
  };

  // 删除任务
  const handleDelete = async (id: string) => {
    Taro.showModal({
      title: '确认删除',
      content: '确定要删除这个导出任务吗？',
      success: async (res) => {
        if (res.confirm) {
          await deleteExportTask(id);
          Taro.showToast({ title: '已删除', icon: 'success' });
          loadTasks();
        }
      }
    });
  };

  // 格式化时间
  const formatTime = (time: string) => {
    return time.slice(0, 16).replace('T', ' ');
  };

  // 判断是否过期
  const isExpired = (task: ExportTask) => {
    if (!task.expiresAt) return false;
    return new Date(task.expiresAt) < new Date();
  };

  return (
    <View className="bill-export">
      {/* 导出按钮 */}
      <View className="export-banner">
        <View className="banner-info">
          <Text className="banner-title">账单导出</Text>
          <Text className="banner-desc">支持 Excel、CSV、PDF 格式导出</Text>
        </View>
        <Button className="export-btn" onClick={() => setShowExport(true)}>
          新建导出
        </Button>
      </View>

      {/* 导出记录 */}
      <View className="section-header">
        <Text className="section-title">导出记录</Text>
        <Text className="section-count">共 {total} 条</Text>
      </View>

      <ScrollView className="task-list" scrollY>
        {loading ? (
          <View className="loading"><Text>加载中...</Text></View>
        ) : tasks.length === 0 ? (
          <View className="empty">
            <Text>暂无导出记录</Text>
            <Button className="empty-btn" onClick={() => setShowExport(true)}>
              立即导出
            </Button>
          </View>
        ) : (
          tasks.map(task => (
            <View key={task.id} className={`task-card ${isExpired(task) ? 'expired' : ''}`}>
              <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>
                    <View className="task-tags">
                      <Text className="tag">{FORMAT_MAP[task.format]?.icon} {FORMAT_MAP[task.format]?.label}</Text>
                      <Text className="tag count">{task.total} 条</Text>
                    </View>
                  </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>

              {task.status === 'completed' && task.downloadUrl && (
                <View className="download-section">
                  <View className="file-info">
                    <Text className="file-name">{task.fileName}</Text>
                    <Text className="file-size">{task.fileSize}</Text>
                    {task.expiresAt && (
                      <Text className="expires-info">
                        过期时间: {formatTime(task.expiresAt)}
                        {isExpired(task) && <Text className="expired-tag"> 已过期</Text>}
                      </Text>
                    )}
                  </View>
                  <View className="download-actions">
                    {!isExpired(task) && (
                      <Button 
                        className="download-btn"
                        onClick={() => handleDownload(task)}
                      >
                        下载
                      </Button>
                    )}
                  </View>
                </View>
              )}

              <View className="task-footer">
                <Text className="task-time">创建于 {formatTime(task.createTime)}</Text>
                <View className="footer-actions">
                  {task.status === 'completed' && (
                    <Button 
                      className="action-btn delete"
                      onClick={() => handleDelete(task.id)}
                    >
                      删除
                    </Button>
                  )}
                </View>
              </View>
            </View>
          ))
        )}
      </ScrollView>

      {/* 导出弹窗 */}
      {showExport && (
        <View className="modal-mask" onClick={() => setShowExport(false)}>
          <View className="export-modal" onClick={(e) => e.stopPropagation()}>
            <View className="modal-header">
              <Text className="modal-title">导出账单</Text>
              <Text className="modal-close" onClick={() => setShowExport(false)}>✕</Text>
            </View>
            
            <ScrollView className="modal-body" scrollY>
              <View className="form-item">
                <Text className="form-label">导出类型</Text>
                <View className="type-selector">
                  {[
                    { value: 'bill', label: '账单数据', icon: '💰' },
                    { value: 'order', label: '订单数据', icon: '📋' },
                    { value: 'user', label: '用户数据', icon: '👤' }
                  ].map(item => (
                    <View
                      key={item.value}
                      className={`type-option ${formData.type === item.value ? 'active' : ''}`}
                      onClick={() => setFormData({ ...formData, type: item.value as ExportType })}
                    >
                      <Text className="option-icon">{item.icon}</Text>
                      <Text className="option-label">{item.label}</Text>
                    </View>
                  ))}
                </View>
              </View>

              <View className="form-item">
                <Text className="form-label">导出格式</Text>
                <View className="format-selector">
                  {[
                    { value: 'xlsx', label: 'Excel', icon: '📊' },
                    { value: 'csv', label: 'CSV', icon: '📋' },
                    { value: 'pdf', label: 'PDF', icon: '📕' }
                  ].map(item => (
                    <View
                      key={item.value}
                      className={`format-option ${formData.format === item.value ? 'active' : ''}`}
                      onClick={() => setFormData({ ...formData, format: item.value as ExportFormat })}
                    >
                      <Text className="format-icon">{item.icon}</Text>
                      <Text className="format-label">{item.label}</Text>
                    </View>
                  ))}
                </View>
              </View>

              <View className="form-item">
                <Text className="form-label">时间范围</Text>
                <View className="date-range">
                  <View className="date-picker">
                    <Text className="date-label">开始日期</Text>
                    <Picker 
                      mode="date" 
                      value={formData.startDate}
                      onChange={(e) => setFormData({ ...formData, startDate: e.detail.value })}
                    >
                      <View className="picker-value">{formData.startDate}</View>
                    </Picker>
                  </View>
                  <Text className="date-separator">至</Text>
                  <View className="date-picker">
                    <Text className="date-label">结束日期</Text>
                    <Picker 
                      mode="date" 
                      value={formData.endDate}
                      onChange={(e) => setFormData({ ...formData, endDate: e.detail.value })}
                    >
                      <View className="picker-value">{formData.endDate}</View>
                    </Picker>
                  </View>
                </View>
              </View>

              <View className="tip-box">
                <Text className="tip-icon">💡</Text>
                <Text className="tip-text">
                  导出文件将在 24 小时后过期，请及时下载。
                  大数据量导出可能需要几分钟时间。
                </Text>
              </View>
            </ScrollView>
            
            <View className="modal-footer">
              <Button className="cancel-btn" onClick={() => setShowExport(false)}>取消</Button>
              <Button className="submit-btn" onClick={handleExport}>开始导出</Button>
            </View>
          </View>
        </View>
      )}
    </View>
  );
}
