import type { MockMethod, MockRequest } from './types'

// 日期工具
function getToday(): string { return new Date().toISOString().slice(0, 10) }
function daysAgo(n: number): string { const d = new Date(); d.setDate(d.getDate() - n); return d.toISOString().slice(0, 10) }

// 计算日期范围天数
function getDays(startDate: string, endDate: string): number {
  return Math.max(1, Math.round((new Date(endDate).getTime() - new Date(startDate).getTime()) / 86400000) + 1)
}

// 不同日期范围的数据倍率（模拟不同日期的数据差异）
function getMultiplier(startDate: string, endDate: string): number {
  const today = getToday()
  if (startDate === today && endDate === today) return 1.0       // 今日
  if (startDate === daysAgo(1) && endDate === daysAgo(1)) return 0.92 // 昨日
  if (startDate === daysAgo(2) && endDate === today) return 0.95      // 近3天
  if (startDate === daysAgo(6) && endDate === today) return 0.93      // 近7天
  return 0.88                                                          // 自定义
}

const baseMachineRank = [
  { rank: 1, machineId: 1, machineName: '西-1.8', program: '1566.NC', quantity: 580, status: 1 },
  { rank: 2, machineId: 2, machineName: '西-1.10', program: 'O123.NC', quantity: 420, status: 1 },
  { rank: 3, machineId: 3, machineName: '东-2.0', program: 'A456.NC', quantity: 380, status: 1 },
  { rank: 4, machineId: 4, machineName: '东-2.5', program: 'B789.NC', quantity: 310, status: 0 },
  { rank: 5, machineId: 5, machineName: '南-3.1', program: 'C012.NC', quantity: 290, status: 1 },
  { rank: 6, machineId: 6, machineName: '南-3.2', program: 'D345.NC', quantity: 240, status: 1 },
  { rank: 7, machineId: 7, machineName: '北-4.0', program: 'E678.NC', quantity: 210, status: 1 },
  { rank: 8, machineId: 8, machineName: '北-4.1', program: 'F901.NC', quantity: 180, status: 0 },
  { rank: 9, machineId: 9, machineName: '西-1.5', program: 'G234.NC', quantity: 150, status: 1 },
  { rank: 10, machineId: 10, machineName: '东-2.8', program: 'H567.NC', quantity: 87, status: 1 },
]

const baseWorkerRank = [
  { rank: 1, workerId: 1, workerName: '张三', machineCount: 3, totalQuantity: 1240 },
  { rank: 2, workerId: 2, workerName: '李四', machineCount: 2, totalQuantity: 980 },
  { rank: 3, workerId: 3, workerName: '王五', machineCount: 4, totalQuantity: 870 },
  { rank: 4, workerId: 4, workerName: '赵六', machineCount: 2, totalQuantity: 650 },
  { rank: 5, workerId: 5, workerName: '孙七', machineCount: 3, totalQuantity: 520 },
]

const baseWorkshopProduction = [
  { workshopName: 'A栋', quantity: 1280, machineCount: 80, avgQuantity: 16.0 },
  { workshopName: 'B栋', quantity: 860, machineCount: 45, avgQuantity: 19.1 },
  { workshopName: 'C栋', quantity: 707, machineCount: 35, avgQuantity: 20.2 },
]

const mock: MockMethod[] = [
  {
    url: '/mock-api/admin/dashboard/summary',
    method: 'get',
    response: {
      code: 0,
      data: {
        onlineCount: 142,
        totalMachines: 160,
        todayProduction: 2847,
        activeAlerts: 3,
        collectSuccessRate: 99.2,
        todayCuttingTime: 580,
        runningMachines: 128,
        dataMissingMachines: 3,
      },
    },
  },
  {
    url: '/mock-api/admin/collector/status',
    method: 'get',
    response: {
      code: 0,
      data: {
        status: 'running',
        uptimeSeconds: 316800,
        lastCollectTime: '2026-04-25T17:36:38',
        successCount: 1280,
        failCount: 5,
      },
    },
  },
  {
    url: '/mock-api/admin/dashboard/machine-rank',
    method: 'get',
    response: (req: MockRequest) => {
      const m = getMultiplier(req.query.startDate, req.query.endDate)
      const days = getDays(req.query.startDate, req.query.endDate)
      return {
        code: 0,
        data: {
          items: baseMachineRank.map(r => ({ ...r, quantity: Math.round(r.quantity * m * days) })),
        },
      }
    },
  },
  {
    url: '/mock-api/admin/dashboard/worker-rank',
    method: 'get',
    response: (req: MockRequest) => {
      const m = getMultiplier(req.query.startDate, req.query.endDate)
      const days = getDays(req.query.startDate, req.query.endDate)
      return {
        code: 0,
        data: {
          items: baseWorkerRank.map(r => ({ ...r, totalQuantity: Math.round(r.totalQuantity * m * days) })),
        },
      }
    },
  },
  // ===== 新增：产量趋势(近7天) =====
  {
    url: '/mock-api/admin/dashboard/trend',
    method: 'get',
    response: {
      code: 0,
      data: {
        items: [
          { date: '2026-04-19', quantity: 3120 },
          { date: '2026-04-20', quantity: 2980 },
          { date: '2026-04-21', quantity: 3450 },
          { date: '2026-04-22', quantity: 3310 },
          { date: '2026-04-23', quantity: 3080 },
          { date: '2026-04-24', quantity: 3260 },
          { date: '2026-04-25', quantity: 2847 },
        ],
      },
    },
  },
  // ===== 新增：车间平均单机产量 =====
  {
    url: '/mock-api/admin/dashboard/workshop-production',
    method: 'get',
    response: (req: MockRequest) => {
      const m = getMultiplier(req.query.startDate, req.query.endDate)
      const days = getDays(req.query.startDate, req.query.endDate)
      return {
        code: 0,
        data: {
          items: baseWorkshopProduction.map(w => {
            const totalQty = Math.round(w.quantity * m * days)  // 多天总量 = 单天 × 天数
            const avgQty = Math.round(totalQty / days / w.machineCount * 10) / 10  // 日均单机产量
            return { ...w, quantity: totalQty, avgQuantity: avgQty }
          }),
        },
      }
    },
  },
  // ===== 新增：机床状态分布 =====
  {
    url: '/mock-api/admin/dashboard/machine-status-distribution',
    method: 'get',
    response: {
      code: 0,
      data: { online: 142, offline: 10, disabled: 8 },
    },
  },
  // ===== 新增：最新告警 =====
  {
    url: '/mock-api/admin/dashboard/recent-alerts',
    method: 'get',
    response: {
      code: 0,
      data: {
        items: [
          { id: 101, createdAt: '2026-04-25 17:30:00', alertType: 'collect_fail', machineName: '西-1.8', title: '连续采集失败5次', isResolved: false },
          { id: 100, createdAt: '2026-04-25 17:25:00', alertType: 'data_missing', machineName: '东-2.0', title: '数据缺失', isResolved: false },
          { id: 99, createdAt: '2026-04-25 16:50:00', alertType: 'device_offline', machineName: '北-4.1', title: '设备离线超30分钟', isResolved: false },
          { id: 98, createdAt: '2026-04-25 15:10:00', alertType: 'collect_fail', machineName: '东-2.5', title: '采集超时', isResolved: true },
          { id: 97, createdAt: '2026-04-25 14:30:00', alertType: 'new_device', machineName: '未知设备', title: '发现未注册设备device_99', isResolved: false },
        ],
      },
    },
  },
  // ===== 采集服务控制 =====
  {
    url: '/mock-api/admin/collector/start',
    method: 'post',
    response: () => {
      // 模拟启动后修改状态为running
      const statusMock = mock.find(m => m.url === '/mock-api/admin/collector/status')
      if (statusMock && typeof statusMock.response === 'object') {
        statusMock.response.data.status = 'running'
        statusMock.response.data.uptimeSeconds = 0
      }
      return { code: 0, message: 'success', data: null }
    },
  },
  {
    url: '/mock-api/admin/collector/stop',
    method: 'post',
    response: () => {
      const statusMock = mock.find(m => m.url === '/mock-api/admin/collector/status')
      if (statusMock && typeof statusMock.response === 'object') {
        statusMock.response.data.status = 'stopped'
      }
      return { code: 0, message: 'success', data: null }
    },
  },
  {
    url: '/mock-api/admin/collector/refresh',
    method: 'post',
    response: () => ({ code: 0, message: 'success', data: null }),
  },
]

export default mock
