/**
 * 数据导入/导出 API
 */
import Taro from '@tarojs/taro';
import type { ImportTask, ImportTemplate, ImportField, ImportError, ExportTask, ExportFormat, ExportType, ImportType } from '../types/import';

// 模拟数据
const mockImportTasks: ImportTask[] = [
  {
    id: '1',
    name: '商品批量导入',
    type: 'product',
    status: 'completed',
    total: 500,
    success: 485,
    failed: 15,
    progress: 100,
    fileName: 'products_20260412.xlsx',
    fileSize: '1.2MB',
    errorFile: '/downloads/import_error_1.xlsx',
    creatorId: '1',
    creatorName: '张三',
    startTime: '2026-04-12 10:00:00',
    endTime: '2026-04-12 10:05:30',
    createTime: '2026-04-12 09:58:00'
  },
  {
    id: '2',
    name: '用户数据迁移',
    type: 'user',
    status: 'importing',
    total: 2000,
    success: 1200,
    failed: 0,
    progress: 60,
    fileName: 'users_migration.csv',
    fileSize: '3.5MB',
    creatorId: '1',
    creatorName: '张三',
    startTime: '2026-04-12 14:00:00',
    createTime: '2026-04-12 13:55:00'
  },
  {
    id: '3',
    name: '订单历史导入',
    type: 'order',
    status: 'validating',
    total: 10000,
    success: 0,
    failed: 0,
    progress: 25,
    fileName: 'orders_history.xlsx',
    fileSize: '8.2MB',
    creatorId: '1',
    creatorName: '张三',
    startTime: '2026-04-12 15:00:00',
    createTime: '2026-04-12 14:50:00'
  }
];

const mockExportTasks: ExportTask[] = [
  {
    id: '1',
    name: '月度订单导出',
    type: 'order',
    status: 'completed',
    format: 'xlsx',
    filters: { month: '2026-03' },
    total: 5680,
    fileName: 'orders_202603.xlsx',
    fileSize: '2.8MB',
    downloadUrl: '/downloads/orders_202603.xlsx',
    expiresAt: '2026-04-19 15:00:00',
    creatorId: '1',
    creatorName: '张三',
    createTime: '2026-04-12 10:00:00',
    completeTime: '2026-04-12 10:02:30'
  },
  {
    id: '2',
    name: '用户数据导出',
    type: 'user',
    status: 'processing',
    format: 'csv',
    filters: { registeredAfter: '2026-01-01' },
    total: 0,
    creatorId: '1',
    creatorName: '张三',
    createTime: '2026-04-12 14:30:00'
  }
];

// 导入模板字段定义
const mockTemplates: ImportTemplate[] = [
  {
    id: 't1',
    name: '商品导入模板',
    type: 'product',
    description: '用于批量导入商品信息，支持商品名称、价格、库存等字段',
    downloadUrl: '/templates/product_import.xlsx',
    fields: [
      { key: 'name', name: '商品名称', type: 'string', required: true, maxLength: 100, example: 'iPhone 15 Pro' },
      { key: 'price', name: '价格', type: 'number', required: true, example: '8999.00' },
      { key: 'stock', name: '库存', type: 'number', required: true, example: '100' },
      { key: 'category', name: '分类', type: 'select', required: true, options: ['手机', '电脑', '配件', '其他'], example: '手机' },
      { key: 'description', name: '描述', type: 'string', required: false, maxLength: 500, example: '最新款苹果手机' },
      { key: 'status', name: '状态', type: 'select', required: true, options: ['上架', '下架'], example: '上架' },
      { key: 'images', name: '图片URL', type: 'string', required: false, example: 'https://example.com/img.jpg' }
    ],
    rules: [
      { field: 'name', rule: 'required', message: '商品名称不能为空' },
      { field: 'price', rule: 'range', message: '价格必须大于0', params: { min: 0.01 } },
      { field: 'stock', rule: 'required', message: '库存不能为空' }
    ],
    exampleUrl: '/templates/product_example.xlsx',
    createTime: '2026-01-01'
  },
  {
    id: 't2',
    name: '用户导入模板',
    type: 'user',
    description: '用于批量导入用户信息，包含用户名、手机、邮箱等',
    downloadUrl: '/templates/user_import.xlsx',
    fields: [
      { key: 'username', name: '用户名', type: 'string', required: true, maxLength: 50, example: 'zhangsan' },
      { key: 'phone', name: '手机号', type: 'string', required: true, pattern: '^1[3-9]\\d{9}$', example: '13800138000' },
      { key: 'email', name: '邮箱', type: 'string', required: false, pattern: '^\\w+@\\w+\\.\\w+$', example: 'user@example.com' },
      { key: 'nickname', name: '昵称', type: 'string', required: false, maxLength: 30, example: '小张' },
      { key: 'role', name: '角色', type: 'select', required: true, options: ['user', 'admin'], example: 'user' }
    ],
    rules: [
      { field: 'username', rule: 'unique', message: '用户名已存在' },
      { field: 'phone', rule: 'pattern', message: '手机号格式不正确' }
    ],
    createTime: '2026-01-01'
  },
  {
    id: 't3',
    name: '订单导入模板',
    type: 'order',
    description: '用于导入历史订单数据',
    downloadUrl: '/templates/order_import.xlsx',
    fields: [
      { key: 'orderNo', name: '订单号', type: 'string', required: true, example: 'ORD202604120001' },
      { key: 'userId', name: '用户ID', type: 'string', required: true, example: '10001' },
      { key: 'amount', name: '订单金额', type: 'number', required: true, example: '299.00' },
      { key: 'status', name: '订单状态', type: 'select', required: true, options: ['pending', 'paid', 'shipped', 'completed', 'cancelled'], example: 'completed' },
      { key: 'createTime', name: '创建时间', type: 'date', required: true, example: '2026-04-01 10:30:00' }
    ],
    rules: [],
    createTime: '2026-01-01'
  }
];

/**
 * 获取导入任务列表
 */
export async function pageImportTask(params: {
  type?: ImportType;
  status?: string;
  page?: number;
  pageSize?: number;
}): Promise<{ list: ImportTask[]; total: number }> {
  const { type, status, page = 1, pageSize = 10 } = params;
  
  let filtered = [...mockImportTasks];
  if (type) filtered = filtered.filter(t => t.type === type);
  if (status) filtered = filtered.filter(t => t.status === status);
  
  const start = (page - 1) * pageSize;
  return { list: filtered.slice(start, start + pageSize), total: filtered.length };
}

/**
 * 获取导入任务详情
 */
export async function getImportTaskDetail(id: string): Promise<ImportTask | null> {
  return mockImportTasks.find(t => t.id === id) || null;
}

/**
 * 获取导入错误详情
 */
export async function getImportErrors(id: string): Promise<ImportError[]> {
  return [
    { row: 15, field: 'price', value: '-100', error: '价格不能为负数', suggestion: '请输入正数' },
    { row: 28, field: 'name', value: '', error: '商品名称不能为空', suggestion: '请填写商品名称' },
    { row: 56, field: 'stock', value: 'abc', error: '库存必须是数字', suggestion: '请输入整数' }
  ];
}

/**
 * 获取导入模板列表
 */
export async function listImportTemplate(): Promise<ImportTemplate[]> {
  return mockTemplates;
}

/**
 * 获取模板字段详情
 */
export async function getTemplateFields(type: ImportType): Promise<ImportField[]> {
  const template = mockTemplates.find(t => t.type === type);
  return template?.fields || [];
}

/**
 * 创建导入任务
 */
export async function createImportTask(data: {
  name: string;
  type: ImportType;
  fileName: string;
  fileSize: string;
}): Promise<ImportTask> {
  const task: ImportTask = {
    id: String(Date.now()),
    name: data.name,
    type: data.type,
    status: 'uploading',
    total: 0,
    success: 0,
    failed: 0,
    progress: 0,
    fileName: data.fileName,
    fileSize: data.fileSize,
    creatorId: '1',
    creatorName: '张三',
    startTime: new Date().toISOString().replace('T', ' ').slice(0, 19),
    createTime: new Date().toISOString().replace('T', ' ').slice(0, 19)
  };
  
  mockImportTasks.unshift(task);
  return task;
}

/**
 * 取消导入任务
 */
export async function cancelImportTask(id: string): Promise<void> {
  const task = mockImportTasks.find(t => t.id === id);
  if (task) task.status = 'cancelled';
}

/**
 * 删除导入任务
 */
export async function deleteImportTask(id: string): Promise<void> {
  const index = mockImportTasks.findIndex(t => t.id === id);
  if (index > -1) mockImportTasks.splice(index, 1);
}

/**
 * 获取导出任务列表
 */
export async function pageExportTask(params: {
  type?: ExportType;
  status?: string;
  page?: number;
  pageSize?: number;
}): Promise<{ list: ExportTask[]; total: number }> {
  const { type, status, page = 1, pageSize = 10 } = params;
  
  let filtered = [...mockExportTasks];
  if (type) filtered = filtered.filter(t => t.type === type);
  if (status) filtered = filtered.filter(t => t.status === status);
  
  const start = (page - 1) * pageSize;
  return { list: filtered.slice(start, start + pageSize), total: filtered.length };
}

/**
 * 创建导出任务
 */
export async function createExportTask(data: {
  name: string;
  type: ExportType;
  format: ExportFormat;
  filters?: Record<string, any>;
}): Promise<ExportTask> {
  const task: ExportTask = {
    id: String(Date.now()),
    name: data.name,
    type: data.type,
    status: 'pending',
    format: data.format,
    filters: data.filters || {},
    total: 0,
    creatorId: '1',
    creatorName: '张三',
    createTime: new Date().toISOString().replace('T', ' ').slice(0, 19)
  };
  
  mockExportTasks.unshift(task);
  return task;
}

/**
 * 删除导出任务
 */
export async function deleteExportTask(id: string): Promise<void> {
  const index = mockExportTasks.findIndex(t => t.id === id);
  if (index > -1) mockExportTasks.splice(index, 1);
}

/**
 * 下载导入模板
 */
export function downloadTemplate(type: ImportType): void {
  const template = mockTemplates.find(t => t.type === type);
  if (template) {
    Taro.showToast({ title: '开始下载模板', icon: 'success' });
    console.log(`Downloading: ${template.downloadUrl}`);
  }
}

/**
 * 导出账单
 */
export async function exportBill(params: {
  startDate: string;
  endDate: string;
  format: ExportFormat;
}): Promise<ExportTask> {
  return createExportTask({
    name: `账单导出 ${params.startDate} ~ ${params.endDate}`,
    type: 'bill',
    format: params.format,
    filters: { startDate: params.startDate, endDate: params.endDate }
  });
}
