/** 任务工单 · 原型 mock 数据与里程进度计算 */

export const CURRENT_USER = { id: 'u_wang', name: '王业管', dept: '业务管理部' };

export const TASK_TYPE_META = {
  mileage: { label: '里程履约', color: 'blue' },
  maintenance: { label: '维保履约', color: 'cyan' },
  policy: { label: '政策兑现', color: 'purple' },
  payment: { label: '付款节点', color: 'gold' },
  penalty: { label: '条款跟进', color: 'orange' },
  general: { label: '通用临时', color: 'default' },
};

export const TASK_STATUS_META = {
  pending: { label: '待处理', color: 'default' },
  in_progress: { label: '进行中', color: 'processing' },
  completed: { label: '已完成', color: 'success' },
  overdue: { label: '已超时', color: 'error' },
  closed: { label: '已关闭', color: 'default' },
};

export const MOCK_PURCHASE_CONTRACTS = [
  {
    id: 'pc-001',
    code: 'HT-CG-2026-0088',
    supplierName: '东风商用车有限公司',
    vehicleModel: '苏龙18T氢能重卡',
    quantity: 5,
    signDate: '2026-03-15',
    clauses: {
      mileage: '采购车辆交付后首年每月单车行驶里程不低于 6,000 km；未达标需说明原因。',
      maintenance: '首保周期 2 万 km 或 24 个月（以先到为准）；易损件由运维按合同标准执行。',
      policy: '帕力安18T里程优惠政策：月里程≥6000km 可享受次月减免，具体按采购附件执行。',
      payment: '预付 30%，到货验收合格后 60%，质保期满 10%。',
      penalty: '逾期交付按 5000 元/次承担违约金；质量不符按合同第八条处理。',
    },
  },
  {
    id: 'pc-002',
    code: 'HT-CG-2026-0102',
    supplierName: '福田智蓝新能源',
    vehicleModel: '智蓝氢能轻卡 4.5T',
    quantity: 8,
    signDate: '2026-04-02',
    clauses: {
      mileage: '交付后 36 个月内累计里程不低于 15 万 km（单车）。',
      maintenance: '按厂家保养手册执行；乙方提供 3 年质保期内免费上门巡检 1 次/季。',
      policy: '享免政策：帕力安4.5T里程优惠政策（详见附件）。',
      payment: '货到票到 45 天内付款。',
      penalty: '标准违约条款（业管可见，执行人不可见金额细节）。',
    },
  },
];

export const MOCK_VEHICLES = [
  { id: 'v1', plateNo: '浙A10001', brand: '东风', model: '苏龙18T氢能重卡', vin: 'LFV2BJCH8K3123456', mileage: 4680, mileageSource: '车机', contractId: 'pc-001' },
  { id: 'v2', plateNo: '浙A10002', brand: '东风', model: '苏龙18T氢能重卡', vin: 'LFV2BJCH8K3123457', mileage: 5210, mileageSource: '车机', contractId: 'pc-001' },
  { id: 'v3', plateNo: '浙A10003', brand: '东风', model: '苏龙18T氢能重卡', vin: 'LFV2BJCH8K3123458', mileage: 3890, mileageSource: 'GPS', contractId: 'pc-001' },
  { id: 'v4', plateNo: '沪B20001', brand: '福田', model: '智蓝氢能轻卡', vin: 'LZYTBACR2M1234567', mileage: 124000, mileageSource: '车机', contractId: 'pc-002' },
  { id: 'v5', plateNo: '沪B20002', brand: '福田', model: '智蓝氢能轻卡', vin: 'LZYTBACR2M1234568', mileage: 118500, mileageSource: '车机', contractId: 'pc-002' },
];

export const MOCK_OWNERS = [
  { id: 'u_zhang', name: '张三', dept: '运维一部' },
  { id: 'u_li', name: '李四', dept: '运维二部' },
  { id: 'u_zhao', name: '赵敏', dept: '客户服务部' },
  { id: 'u_chen', name: '陈高伟', dept: '运维主管' },
];

function daysBetween(start, end, today = '2026-07-10') {
  const s = new Date(start);
  const e = new Date(end);
  const t = new Date(today);
  return Math.max(0, Math.ceil((e - t) / 86400000));
}

export function computeMileageProgress(task, vehicles = MOCK_VEHICLES) {
  if (task.taskType !== 'mileage' || !task.mileageTarget) return null;
  const ids = task.vehicleIds || [];
  const bound = vehicles.filter((v) => ids.includes(v.id));
  if (!bound.length) return { percent: 0, current: 0, target: task.mileageTarget, label: '未绑车' };

  if (task.mileageMode === 'cumulative') {
    const current = bound.reduce((s, v) => s + (v.mileage || 0), 0);
    const target = task.mileageTarget * bound.length;
    const percent = Math.min(100, Math.round((current / target) * 100));
    return { percent, current, target, label: `累计 ${current.toLocaleString()} / ${target.toLocaleString()} km`, vehicles: bound };
  }

  const avg = bound.reduce((s, v) => s + (v.mileage || 0), 0) / bound.length;
  const percent = Math.min(100, Math.round((avg / task.mileageTarget) * 100));
  return {
    percent,
    current: Math.round(avg),
    target: task.mileageTarget,
    label: `周期内均值 ${Math.round(avg).toLocaleString()} / ${task.mileageTarget.toLocaleString()} km`,
    vehicles: bound,
    remainDays: task.periodEnd ? daysBetween(task.periodStart, task.periodEnd) : null,
  };
}

export function buildInitialTasks() {
  return [
    {
      id: 'wo-001',
      code: 'WO-2026-0001',
      taskType: 'mileage',
      title: '月里程≥6000km 履约跟踪',
      requirement: '本周期内单车月度行驶里程不低于 6,000 km；未达标需记录原因并上传说明。',
      source: 'contract',
      contractId: 'pc-001',
      contractCode: 'HT-CG-2026-0088',
      vehicleIds: ['v1', 'v2', 'v3'],
      periodStart: '2026-07-01',
      periodEnd: '2026-07-31',
      mileageTarget: 6000,
      mileageMode: 'period_avg',
      initiatorId: 'u_wang',
      accountableOwnerId: 'u_chen',
      currentOwnerId: 'u_zhang',
      status: 'in_progress',
      createdAt: '2026-07-01 09:00',
      feedbacks: [{ at: '2026-07-08 14:20', by: '张三', note: '浙A10003 雨天停运 3 天', attachments: ['停运说明.pdf'] }],
      timeline: [
        { at: '2026-07-01 09:00', action: '发布任务', operator: '王业管', remark: '自采购合同 HT-CG-2026-0088 发起' },
        { at: '2026-07-02 10:15', action: '指派执行', operator: '王业管', remark: '执行人：张三' },
        { at: '2026-07-08 14:20', action: '提交反馈', operator: '张三', remark: '浙A10003 雨天停运 3 天' },
      ],
      syncWorkbench: true,
    },
    {
      id: 'wo-002',
      code: 'WO-2026-0002',
      taskType: 'maintenance',
      title: '首保 2万km/24月 到期提醒',
      requirement: '按采购合同维保条款，在 2 万 km 或 24 个月内完成首保；上传保养单与里程截图。',
      source: 'contract',
      contractId: 'pc-001',
      contractCode: 'HT-CG-2026-0088',
      vehicleIds: ['v1'],
      periodStart: '2026-03-15',
      periodEnd: '2028-03-14',
      initiatorId: 'u_wang',
      accountableOwnerId: 'u_chen',
      currentOwnerId: 'u_zhang',
      status: 'pending',
      createdAt: '2026-07-05 11:30',
      feedbacks: [],
      timeline: [{ at: '2026-07-05 11:30', action: '发布任务', operator: '王业管' }],
      syncWorkbench: true,
    },
    {
      id: 'wo-003',
      code: 'WO-2026-0003',
      taskType: 'mileage',
      title: '36个月累计15万km 长期跟踪',
      requirement: '交付后 36 个月内单车累计里程不低于 150,000 km；每季度汇总进度。',
      source: 'contract',
      contractId: 'pc-002',
      contractCode: 'HT-CG-2026-0102',
      vehicleIds: ['v4', 'v5'],
      periodStart: '2026-04-01',
      periodEnd: '2029-03-31',
      mileageTarget: 150000,
      mileageMode: 'cumulative',
      initiatorId: 'u_wang',
      accountableOwnerId: 'u_chen',
      currentOwnerId: 'u_li',
      status: 'in_progress',
      createdAt: '2026-04-05 08:00',
      feedbacks: [],
      timeline: [{ at: '2026-04-05 08:00', action: '发布任务', operator: '王业管' }],
      syncWorkbench: true,
    },
    {
      id: 'wo-004',
      code: 'WO-2026-0004',
      taskType: 'general',
      title: '跨部门协调：加氢证办理加急',
      requirement: '协调加氢站完成 2 台新车加氢证办理，7 月 20 日前完成。',
      source: 'standalone',
      contractId: 'pc-001',
      contractCode: 'HT-CG-2026-0088',
      vehicleIds: ['v2', 'v3'],
      periodStart: '2026-07-10',
      periodEnd: '2026-07-20',
      initiatorId: 'u_wang',
      accountableOwnerId: 'u_wang',
      currentOwnerId: 'u_zhao',
      status: 'in_progress',
      createdAt: '2026-07-10 08:30',
      feedbacks: [],
      timeline: [{ at: '2026-07-10 08:30', action: '独立新增', operator: '王业管', remark: '反向关联 HT-CG-2026-0088' }],
      syncWorkbench: true,
    },
    {
      id: 'wo-005',
      code: 'WO-2026-0005',
      taskType: 'policy',
      title: '帕力安18T里程政策兑现核对',
      requirement: '核对本月达标车辆清单，提交享免政策兑现说明（执行人不可见合同金额）。',
      source: 'contract',
      contractId: 'pc-001',
      contractCode: 'HT-CG-2026-0088',
      vehicleIds: ['v1', 'v2'],
      periodStart: '2026-07-01',
      periodEnd: '2026-07-31',
      initiatorId: 'u_wang',
      accountableOwnerId: 'u_chen',
      currentOwnerId: 'u_li',
      status: 'overdue',
      createdAt: '2026-07-01 09:30',
      feedbacks: [],
      timeline: [
        { at: '2026-07-01 09:30', action: '发布任务', operator: '王业管' },
        { at: '2026-07-09 16:00', action: '催办', operator: '王业管', remark: '请尽快提交核对结果' },
      ],
      syncWorkbench: true,
    },
  ];
}

export function ownerName(id, owners = MOCK_OWNERS) {
  return owners.find((o) => o.id === id)?.name || '—';
}

export function vehicleSummary(ids, vehicles = MOCK_VEHICLES) {
  const list = vehicles.filter((v) => (ids || []).includes(v.id));
  if (!list.length) return '—';
  if (list.length === 1) return list[0].plateNo;
  return `${list.length} 台（${list[0].plateNo} 等）`;
}
