export type WorkerUser = {
  workerId: number
  username: string
  displayName: string
  phone: string
  status: string
  workerType: string
  reviewNote: string
  freezeReason: string
  frozenAt: string | null
  inviteCode: string
  /** 个人追加免押额度；null 表示未追加。 */
  personalDepositFreeAmount: number | null
  /** 打手等级带来的免押额度。 */
  levelDepositFreeAmount: number
  /** 当前实际生效的免押额度。 */
  effectiveDepositFreeAmount: number
  inviter: null | {
    workerId: number
    username: string
    displayName: string
  }
  level: null | {
    levelId: number
    levelKey: string
    name: string
    permissions: {
      depositFreeAmount: number
      maxActiveOrders: number
      upgradeThreshold: number
      autoAcceptWithoutEvidence: boolean
      visibleDelaySeconds: number
    }
  }
  wallet: {
    availableAmount: number
    frozenDepositAmount: number
    pendingUnfreezeAmount: number
    totalCreditedAmount: number
    totalSettledAmount: number
  }
  timeoutOrderCount?: number
  createdAt: string
  updatedAt: string
  reviewedAt: string | null
  /** 剩余改名卡数量，注册默认 1 张 */
  renameCards: number
  lastRenamedAt: string | null
  /** 上次改名后的一年锁定期结束时间 */
  renameUnlockedAt: string | null
}

export type WorkerSessionDevice = {
  sessionId: string
  deviceId: string
  deviceType: string
  deviceName: string
  userAgent: string
  ipAddress: string
  issuedAt: string
  lastSeenAt: string
  expiresAt: string
  current: boolean
}

export type WorkerProfileSummary = {
  acceptedOrderCount: number
  activeOrderCount: number
  timeoutOrderCount: number
  pendingWithdrawAmount: number
  approvedWithdrawAmount: number
  pendingRechargeAmount: number
}

export type WorkerLevelProgress = {
  currentThreshold: number
  nextThreshold: number | null
  progressPercent: number
}

export type WorkerWalletLedger = {
  ledgerId: number
  ledgerType: string
  amount: number
  balanceAfter: number
  frozenAfter: number
  relatedWorkOrderId: number | null
  relatedPlatformOrderId: string | null
  auditStatus: string
  note: string
  payload: Record<string, unknown>
  createdAt: string
}

/** 押金/报酬待解冻记录；status: pending 待到期 / released 已到账 / deducted 已扣减。 */
export type WorkerDepositUnfreeze = {
  id: number
  workerId: number
  workOrderId: number
  amount: number
  fundType: 'deposit' | 'reward' | 'legacy_combined' | string
  status: string
  unfreezeAt: string | null
  releasedAt: string | null
  createdAt: string | null
}

/** 管理端打手详情聚合数据。 */
export type AdminWorkerDetail = {
  worker: WorkerUser
  summary: {
    activeOrderCount: number
    acceptedOrderCount: number
    timeoutOrderCount: number
  }
  orderOverview: Array<{
    status: string
    orderCount: number
    settlementAmount: number
    vipEvidencePendingCount: number
    vipEvidencePendingSettlementAmount: number
  }>
}

export type WorkerFinanceRequest = {
  requestId: number
  requestType: string
  status: string
  amount: number
  accountChannel: string
  accountName: string
  accountNo: string
  note: string
  reviewedNote: string
  payload: Record<string, unknown>
  createdAt: string
  updatedAt: string
  reviewedAt: string | null
  worker: null | {
    workerId: number
    username: string
    displayName: string
    phone: string
    workerType: 'internal' | 'external'
    levelKey: string
    levelName: string
    withdrawRequestCount: number
    totalWithdrawAmount: number
  }
}

export type WorkerCancelRequest = {
  requestId: number
  workOrderId: number
  shareId: number | null
  workerId: number
  platformOrderId: string
  shopName: string
  workerName: string
  shareQuantity: number | null
  reason: string
  status: 'pending' | 'approved' | 'rejected' | string
  reviewNote: string
  reviewedBy: string
  createdAt: string
  reviewedAt: string | null
}

export type WorkerCancelRequestRisk = {
  dailyUsed: number
  dailyLimit: number
  approvedTotal: number
  nextPenaltyAt: number
  remainingToPenalty: number
}

export type WorkerOrderFeedback = {
  feedbackId: number
  workOrderId: number
  shareId: number | null
  workerId: number
  workOrderNo: string
  productName: string
  shopName: string
  workerName: string
  shareQuantity: number | null
  content: string
  status: 'pending' | 'resolved' | string
  reply: string
  handledBy: string
  createdAt: string
  handledAt: string | null
}

export type WorkerAfterSalesCase = {
  caseId: number
  caseNo: string
  workOrderId: number
  shareId: number | null
  workerId: number
  workOrderNo: string
  platformOrderId: string
  productName: string
  shopName: string
  workerName: string
  shareQuantity: number | null
  problemType: string
  complaintNote: string
  complaintFiles: UploadedFile[]
  acceptanceSnapshot: Record<string, unknown>
  status: 'awaiting_worker_response' | 'under_review' | 'recovery_pending' | 'closed' | string
  workerResponse: string
  workerResponseFiles: UploadedFile[]
  respondedAt: string | null
  resolutionAction: 'not_upheld' | 'remedied' | 'upheld' | string
  resolutionNote: string
  recoveryAmount: number
  pendingDepositDeductionAmount: number
  availableDeductionAmount: number
  debtAmount: number
  refundedAmount: number
  refundedAt: string | null
  refundedBy: string
  createdBy: string
  resolvedBy: string
  resolvedAt: string | null
  createdAt: string
  updatedAt: string
}

export type WorkerAfterSalesCaseEvent = {
  eventId: number
  actorType: string
  actorId: string
  eventType: string
  payload: Record<string, unknown>
  createdAt: string
}

export type WorkerFinanceConfig = {
  depositUnfreezeDays: number
  rewardUnfreezeEnabled: boolean
  recharge: {
    enabled: boolean
    channelName: string
    accountName: string
    accountNo: string
    qrCodeImage: UploadedFile | null
    instructions: string
  }
  adminContact: {
    wechatQrCodeImage: UploadedFile | null
  }
  withdraw: {
    enabled: boolean
    instructions: string
  }
}

export type WorkerPlatformNotificationEventKey =
  | 'withdraw_requested'
  | 'recharge_requested'
  | 'acceptance_submitted'
  | 'acceptance_reminded'
  | 'material_required'
  | 'cancel_requested'
  | 'feedback_submitted'

export type WorkerPlatformNotificationConfig = {
  events: Record<
    WorkerPlatformNotificationEventKey,
    {
      todoEnabled: boolean
      soundEnabled: boolean
      externalPushEnabled: boolean
    }
  >
}

export type WorkerProductMatchConfig = {
  legacyFallbackEnabled: boolean
}

export type WorkerAnnouncementConfig = {
  enabled: boolean
  content: string
}

export type WorkerHallConfig = {
  maxVisibleOrders: number
  categoryMaxVisibleOrders: Record<string, number>
  visibleOrderCount: number
  queuedOrderCount: number
}

export type WorkerWithdrawalAccount = {
  accountChannel: string
  accountName: string
  accountNoMasked: string
  alipayQrCodeImage: UploadedFile | null
  wechatQrCodeImage: UploadedFile | null
  createdAt: string | null
}

export type AdminWorkerWithdrawalAccount = {
  accountChannel: string
  accountName: string
  accountNo: string
  alipayQrCodeImage: UploadedFile | null
  wechatQrCodeImage: UploadedFile | null
  createdAt: string
}

export type WorkerProfileResponse = {
  worker: WorkerUser
  permissions: Record<string, unknown>
  summary: WorkerProfileSummary
  levelProgress: WorkerLevelProgress | null
  financeConfig: WorkerFinanceConfig
  withdrawalAccounts: WorkerWithdrawalAccount[]
  /** 打手端订单详情是否展示流转记录（后台配置开关，默认关闭） */
  orderTimelineVisible?: boolean
}

export type WorkerLevel = {
  levelId: number
  levelKey: string
  name: string
  sortOrder: number
  status: string
  depositFreeAmount: number
  maxActiveOrders: number
  upgradeThreshold: number
  autoAcceptWithoutEvidence: boolean
  visibleDelaySeconds: number
  createdAt: string
  updatedAt: string
}

export type WorkCategory = {
  categoryId: number
  categoryKey: string
  name: string
  sortOrder: number
  status: string
  createdAt: string
  updatedAt: string
}

export type WorkProductRule = {
  ruleId: number
  ruleKey: string
  provider: string
  platform: string
  shopId: string
  skuCode: string
  productName: string
  matchType: 'contains' | 'exact' | string
  match: {
    sellerId: string
    itemId: string
    relItemId: string
    skuId: string
    relSkuId: string
    itemTitle: string
    skuNick: string
    itemTitleMatchType: 'contains' | 'exact'
    skuNickMatchType: 'contains' | 'exact'
  }
  categoryId: number | null
  categoryName: string
  enabled: boolean
  autoCreate: boolean
  rewardAmount: number
  unitPriceFen: number
  sharing?: WorkOrderSharingConfig
  requirement: {
    fields: CollectField[]
  }
  timeoutMinutes?: number
  timeoutPolicy?: 'reopen' | 'cancel_release' | 'cancel_deduct' | string
  /** 验收模式：standard / friend_gift */
  acceptanceMode?: 'standard' | 'friend_gift' | string
  /** 好友赠送冷却小时数（默认 72） */
  giftCooldownHours?: number
  /** 好友赠送按分钟配置时的总分钟数；非零时使用分钟单位。 */
  giftCooldownMinutes?: number
  sortOrder: number
  createdAt: string
  updatedAt: string
}

export type WorkProductRuleMapping = {
  mappingId: number
  ruleId: number
  ruleKey: string
  productName: string
  sellerIds: string[]
  sellerId: string
  relItemId: string
  itemTitle: string
  relSkuId: string
  skuNick: string
  skuMatchMode: 'fuzzy' | 'exact'
  mappingType: 'product_default' | 'sku_exact' | 'sku_series'
  enabled: boolean
  createdAt: string
  updatedAt: string
}

export type KuaishouMatchSource = {
  sellerId: string
  relItemId: string
  itemTitle: string
  relSkuId: string
  skuNick: string
  sampleOid: string
  lastSeenAt: string
  seenCount: number
  rawPayload: Record<string, unknown>
}

export type WorkProductMatchLog = {
  logId: number
  orderId: number | null
  orderItemId: number | null
  source: string
  sellerId: string
  relItemId: string
  itemTitle: string
  relSkuId: string
  skuNick: string
  status: 'matched' | 'unmatched' | 'ambiguous' | string
  ruleId: number | null
  mappingId: number | null
  ruleKey: string
  productName: string
  candidates: Array<{ ruleKey?: string; score?: number; mappingId?: number | null }>
  rawPayload: Record<string, unknown>
  createdAt: string
}

export type UploadedFile = {
  objectKey: string
  url: string
  thumbnailUrl: string
  mediumUrl: string
  filename: string
  contentType: string
  size: number
}

export type WorkOrderStatus =
  | 'pending_material'
  | 'unassigned'
  | 'open'
  | 'in_progress'
  | 'pending_acceptance'
  | 'problem'
  | 'accepted'
  | 'cancelled'
  | string

export type WorkOrderSharingConfig = {
  enabled: boolean
  totalQuantity: number
  unitReward: number
  autoFromOrder?: boolean
}

export type WorkerAcceptance = {
  note?: string
  files?: UploadedFile[]
  imageUrls?: string[]
  submittedAt?: string
  updatedAt?: string
  reviewMode?: 'vip_auto' | string
  evidenceStatus?: 'pending' | 'complete' | string
  evidenceDueAt?: string | null
  evidenceSupplementedAt?: string | null
  [key: string]: unknown
}

export type WorkOrderShare = {
  shareId: number
  workOrderId: number
  workerId: number
  quantity: number
  unitReward: number
  shareReward: number
  shareDeposit: number
  status: string
  acceptance: WorkerAcceptance
  draftAcceptance?: WorkerAcceptance
  submittedAt: string | null
  acceptedAt: string | null
  createdAt: string
  updatedAt: string
  worker: null | {
    workerId: number
    username: string
    displayName: string
  }
}

export type WorkOrderGiftPhase =
  | 'material_required'
  | 'material_submitted'
  | 'friend_countdown'
  | 'gift_ready'
  | string

/** 好友赠送验收模式的打手本人资料 */
export type BoosterMaterial = {
  fields: Record<string, string>
  screenshots: UploadedFile[]
  note: string
  submittedAt: string
}

/** 好友赠送验收模式进度；phase 含实时计算的 gift_ready */
export type WorkOrderGiftProgress = {
  phase: WorkOrderGiftPhase
  rawPhase: string
  cooldownHours: number
  cooldownMinutes: number
  friendAddedAt: string | null
  giftAvailableAt: string | null
  boosterMaterial: BoosterMaterial
}

export type WorkOrder = {
  workOrderId: number
  orderId?: number | null
  orderItemId?: number | null
  workOrderNo: string
  platformOrderId: string
  productName: string
  categoryId?: number | null
  categoryName: string
  status: WorkOrderStatus
  rawStatus?: WorkOrderStatus
  hallAvailable?: boolean
  /** 订单进入抢单大厅的时间；实时广播携带，客户端按打手等级可见延迟推迟展示。 */
  hallQueuedAt?: string | null
  /** 验收模式：standard 标准验收 / friend_gift 好友赠送 */
  acceptanceMode?: 'standard' | 'friend_gift' | string
  /** 好友赠送模式进度；仅 acceptanceMode = friend_gift 时返回 */
  gift?: WorkOrderGiftProgress
  capabilities?: {
    canEdit: boolean
    canConfigureSharing: boolean
    canAssign: boolean
    canPin: boolean
    canUnpublish: boolean
    canUpdateMaterial: boolean
    canAccept: boolean
    canMarkProblem: boolean
    canDelete: boolean
    canReopen: boolean
    canPublish: boolean
    canCancel: boolean
    canCancelSharing?: boolean
    canResolveProblem: boolean
    canDeduct: boolean
    canConfirmFriend?: boolean
    canCompleteGiftCooldown?: boolean
    canResetGiftFlow?: boolean
  }
  rewardAmount: number
  /** 当前打手生效的免押额度，仅打手端订单数据返回。 */
  depositFreeAmount?: number
  requiredDepositAmount?: number
  depositThresholdAmount?: number
  freezeDepositAmount?: number
  sharing?: WorkOrderSharingConfig
  myShare?: WorkOrderShare | null
  sharingProgress?: {
    joinedQuantity: number
    pendingSubmissionCount: number
    remainingQuantity?: number
    filled?: boolean
  }
  pendingUnfreezeAmount?: number
  timeoutMinutes?: number
  timeoutPolicy?: 'reopen' | 'cancel_release' | 'cancel_deduct' | string
  deadlineAt?: string | null
  material: Record<string, unknown>
  requirement: Record<string, unknown>
  acceptance: WorkerAcceptance
  /** 暂存的验收草稿（未提交时保存于此，刷新不丢失；提交后清空） */
  draftAcceptance: WorkerAcceptance
  /** 后台客服维护的工单备注。 */
  adminNote?: string
  workerNote?: string
  /** 打手本人尚未点击查看或操作过该工单。 */
  isUnread?: boolean
  problemNote: string
  /** 问题单分组来源角标：平台标记 / 退单审核中 / 反馈处理中 / 资料已更新。 */
  problemMarked?: boolean
  pendingCancelRequest?: boolean
  pendingFeedback?: boolean
  materialUpdated?: boolean
  /** 取消信息，仅已取消工单返回。 */
  cancel?: {
    reason: string
    source: string
    actorType: string
    actorName: string
    cancelledAt: string | null
  } | null
  worker: null | {
    workerId: number
    username: string
    displayName: string
  }
  /** 拼单订单的当前参与打手，普通整单不返回该字段。 */
  sharingWorkers?: Array<{
    workerId: number
    username: string
    displayName: string
    quantity: number
  }>
  publishedAt: string | null
  /** 置顶时间；非空表示该工单在抢单大厅置顶展示 */
  pinnedAt?: string | null
  assignedAt: string | null
  submittedAt: string | null
  acceptedAt: string | null
  createdAt: string
  updatedAt: string
}

export type WorkOrderStatistics = {
  totalCount: number
  userPaymentAmount: number
  rewardAmount: number
  refundAmount: number
  statusCounts: Record<string, number>
}

/** 工单流转事件（订单详情中的操作日志） */
export type WorkOrderEvent = {
  id: number
  time: string
  actorType: string
  actorName: string
  eventType: string
  fromStatus: string
  toStatus: string
  payload: Record<string, unknown>
  worker?: {
    workerId: number
    displayName: string
    username: string
    workerType: string
    levelName: string
    status: string
  }
}

export type Pagination = {
  page: number
  pageSize: number
  total: number
}

export type WorkerLoginResponse = {
  token: string
  expiresAt: string
  worker: WorkerUser
  passwordWeak?: boolean
}

export type WorkerListResponse<T> = {
  items: T[]
  pagination: Pagination
}

export type WorkerOrderOverviewItem = {
  status: string
  orderCount: number
  settlementAmount: number
}

export type WorkerOrderOverviewResponse = {
  items: WorkerOrderOverviewItem[]
}

export type WorkerHallOrdersResponse = {
  items: WorkOrder[]
  pagination: Pagination
  categories: WorkCategory[]
  visibleDelaySeconds?: number
}

export type WorkerLeaderboardEntry = {
  rank: number
  workerId: number
  displayName: string
  levelName: string
  acceptedOrderCount: number
}

export type WorkerLeaderboardPeriod = 'all' | 'daily'

export type WorkerLeaderboardResponse = {
  items: WorkerLeaderboardEntry[]
  current: {
    rank: number | null
    acceptedOrderCount: number
  }
}

export type CollectField = {
  key: string
  label: string
  required: boolean
  type?: 'text' | 'select'
  options?: string[]
}

export type CollectLookupOrder = {
  workOrderId: number
  workOrderNo: string
  platformOrderId: string
  productName: string
  status: string
  fields: CollectField[]
  values?: Record<string, string>
  screenshots?: UploadedFile[]
}

export type CollectLookupResponse = {
  order: Pick<
    WorkOrder,
    'workOrderId' | 'workOrderNo' | 'platformOrderId' | 'productName' | 'status'
  >
  fields: CollectField[]
  orders: CollectLookupOrder[]
  pendingCount: number
}
