import useUserStore from '@/store/modules/user'
import SafeStorage, { AppStorageKey } from '@/utils/safeStorage'

/** 列表行与后端 FeedbackTicket 对齐：含 status / creator_id / assignee_id */
export interface FeedbackTicketRow {
  status?: string
  creator_id?: number
  assignee_id?: number
}

function numId(v: unknown): number {
  if (v === null || v === undefined || v === '') return 0
  const n = Number(v)
  return Number.isFinite(n) ? n : 0
}

/**
 * 当前登录用户 ID（与 JWT / GetUserInfo 一致）。
 * 取自登录接口 details，写入 Pinia `user.userInfo` 与 SafeStorage USER_INFO（含 user_id）。
 */
export function getFeedbackCurrentUserId(): number {
  const userStore = useUserStore()
  let payload = userStore.$state.userInfo as Record<string, unknown> | undefined | null
  if (!payload || typeof payload !== 'object') {
    payload = SafeStorage.get(AppStorageKey.USER_INFO) as Record<string, unknown> | undefined | null
  }
  if (payload && typeof payload === 'object') {
    return numId(payload.user_id ?? payload.id)
  }
  return 0
}

function assigneeId(row: FeedbackTicketRow): number {
  return numId(row.assignee_id)
}

function creatorId(row: FeedbackTicketRow): number {
  return numId(row.creator_id)
}

function isClosedOrCancelled(status: string | undefined): boolean {
  return status === 'closed' || status === 'cancelled'
}

/** 已解决或已关闭：列表操作仅保留「详情」「评论」 */
export function isTicketResolvedOrClosed(status: string | undefined): boolean {
  return status === 'resolved' || status === 'closed'
}

export function canAcceptTicket(row: FeedbackTicketRow, me: number): boolean {
  if (row.status !== 'pending') return false
  const aid = assigneeId(row)
  if (aid > 0) return me > 0 && aid === me
  return true
}

export function canTransferTicket(row: FeedbackTicketRow, me: number): boolean {
  if (isClosedOrCancelled(row.status)) return false
  const aid = assigneeId(row)
  return me > 0 && aid > 0 && aid === me
}

export function canCancelTicket(row: FeedbackTicketRow, me: number): boolean {
  if (isClosedOrCancelled(row.status)) return false
  return me > 0 && creatorId(row) === me
}

export function canSuspendTicket(row: FeedbackTicketRow, me: number): boolean {
  if (isClosedOrCancelled(row.status)) return false
  if (row.status === 'suspended') return false
  const aid = assigneeId(row)
  return me > 0 && aid > 0 && aid === me
}

export function canResumeTicket(row: FeedbackTicketRow, me: number): boolean {
  if (row.status !== 'suspended') return false
  const aid = assigneeId(row)
  return me > 0 && aid > 0 && aid === me
}

export function canResolveTicket(row: FeedbackTicketRow, me: number): boolean {
  if (isClosedOrCancelled(row.status)) return false
  const aid = assigneeId(row)
  return me > 0 && aid > 0 && aid === me
}

export function canCloseTicket(row: FeedbackTicketRow, me: number): boolean {
  if (row.status === 'closed') return false
  if (row.status === 'cancelled') return false
  if (me <= 0) return false
  return creatorId(row) === me || assigneeId(row) === me
}

/** 仅创建人、且待接单（pending）时可编辑（产品约定） */
export function canEditTicket(row: FeedbackTicketRow, me: number): boolean {
  if (isClosedOrCancelled(row.status)) return false
  if (row.status !== 'pending') return false
  if (me <= 0) return false
  return creatorId(row) === me
}

export function reasonEditTicket(row: FeedbackTicketRow, me: number): string {
  if (isClosedOrCancelled(row.status)) return '工单已关闭或撤回，不允许修改'
  if (row.status !== 'pending') return '仅待接单状态下可由创建人编辑'
  if (me <= 0) return '无法识别当前用户'
  if (creatorId(row) !== me) return '只有创建人可在待接单时编辑工单'
  return ''
}

export function canDeleteTicket(row: FeedbackTicketRow, me: number): boolean {
  return me > 0 && creatorId(row) === me
}

/** 禁用时的原因文案（与后端错误信息对齐，便于用户理解） */
export function reasonAcceptTicket(row: FeedbackTicketRow, me: number): string {
  if (row.status !== 'pending') return '工单状态不是待接单，无法接单'
  const aid = assigneeId(row)
  if (aid > 0 && aid !== me) return '该工单已指定其他处理人'
  return ''
}

export function reasonTransferTicket(row: FeedbackTicketRow, me: number): string {
  if (isClosedOrCancelled(row.status)) return '工单已关闭或撤回，无法转交'
  const aid = assigneeId(row)
  if (aid <= 0 || aid !== me) return '只有当前处理人可以转交工单'
  return ''
}

export function reasonSuspendTicket(row: FeedbackTicketRow, me: number): string {
  if (isClosedOrCancelled(row.status)) return '工单已关闭或撤回，无法挂起'
  if (row.status === 'suspended') return '工单已经是挂起状态'
  const aid = assigneeId(row)
  if (aid <= 0 || aid !== me) return '只有处理人可以挂起工单'
  return ''
}

export function reasonResumeTicket(row: FeedbackTicketRow, me: number): string {
  if (row.status !== 'suspended') return '工单不是挂起状态，无法重启'
  const aid = assigneeId(row)
  if (aid <= 0 || aid !== me) return '只有处理人可以重启工单'
  return ''
}

export function reasonResolveTicket(row: FeedbackTicketRow, me: number): string {
  if (isClosedOrCancelled(row.status)) return '工单已关闭或撤回'
  const aid = assigneeId(row)
  if (aid <= 0 || aid !== me) return '只有处理人可以解决工单'
  return ''
}

export function reasonCloseTicket(row: FeedbackTicketRow, me: number): string {
  if (row.status === 'closed') return '工单已关闭'
  if (row.status === 'cancelled') return '工单已撤回，无法关闭'
  if (creatorId(row) !== me && assigneeId(row) !== me) return '只有创建人或处理人可以关闭工单'
  return ''
}

export function reasonCancelTicket(row: FeedbackTicketRow, me: number): string {
  if (isClosedOrCancelled(row.status)) return '工单已关闭或撤回'
  if (creatorId(row) !== me) return '只有创建人可以撤回工单'
  return ''
}

export function reasonDeleteTicket(row: FeedbackTicketRow, me: number): string {
  if (creatorId(row) !== me) return '只有创建人可以删除工单'
  return ''
}
