import type { ToastOptions, ModalOptions } from '@/types'

/**
 * 格式化日期时间
 */
export function formatDate(date: string | number | Date, format = 'YYYY-MM-DD HH:mm'): string {
  if (!date) return '-'
  const d = date instanceof Date ? date : new Date(date)
  if (isNaN(d.getTime())) return '-'

  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  const second = String(d.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', String(year))
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second)
}

/**
 * 相对时间描述
 */
export function formatRelativeTime(value: string | number | Date): string {
  if (!value) return '-'
  const date = value instanceof Date ? value : new Date(value)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour

  if (diff < 0) return formatDate(value, 'MM-DD HH:mm')
  if (diff < minute) return '刚刚'
  if (diff < hour) return `${Math.floor(diff / minute)}分钟前`
  if (diff < day) return `${Math.floor(diff / hour)}小时前`
  if (diff < 7 * day) return `${Math.floor(diff / day)}天前`
  return formatDate(value, 'YYYY-MM-DD')
}

/**
 * 显示 Toast 提示
 */
export function showToast(options: ToastOptions | string): void {
  const opts: ToastOptions = typeof options === 'string' ? { title: options } : options
  uni.showToast({
    title: opts.title,
    icon: opts.icon || 'none',
    duration: opts.duration || 2000,
    mask: opts.mask ?? false
  })
}

/**
 * 隐藏 Toast
 */
export function hideToast(): void {
  uni.hideToast()
}

/**
 * 显示加载中
 */
export function showLoading(title = '加载中...'): void {
  uni.showLoading({ title, mask: true })
}

/**
 * 隐藏加载中
 */
export function hideLoading(): void {
  uni.hideLoading()
}

/**
 * 显示确认弹窗（简化版，返回 boolean）
 */
export function showConfirm(title: string, content?: string): Promise<boolean> {
  return new Promise((resolve) => {
    uni.showModal({
      title,
      content: content || '',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        resolve(res.confirm)
      }
    })
  })
}

/**
 * 显示确认弹窗
 */
export function showModal(options: ModalOptions | string): Promise<{ confirm: boolean; cancel: boolean }> {
  const opts: ModalOptions = typeof options === 'string' ? { content: options } : options
  return new Promise((resolve) => {
    uni.showModal({
      title: opts.title || '提示',
      content: opts.content,
      showCancel: opts.showCancel ?? true,
      cancelText: opts.cancelText || '取消',
      confirmText: opts.confirmText || '确定',
      success: (res) => {
        opts.success?.(res)
        resolve(res)
      }
    })
  })
}

/**
 * 本地存储
 */
export const storage = {
  get<T = unknown>(key: string, defaultValue?: T): T | undefined {
    try {
      const value = uni.getStorageSync(key)
      return value === '' ? defaultValue : (value as T)
    } catch {
      return defaultValue
    }
  },
  set(key: string, value: unknown): void {
    uni.setStorageSync(key, value)
  },
  remove(key: string): void {
    uni.removeStorageSync(key)
  },
  clear(): void {
    uni.clearStorageSync()
  }
}

/**
 * 模拟延迟
 */
export function delay(ms = 500): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

/**
 * 生成唯一 ID
 */
export function generateId(prefix = 'id'): string {
  return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`
}

/**
 * 深拷贝
 */
export function deepClone<T>(obj: T): T {
  return JSON.parse(JSON.stringify(obj))
}

/**
 * 页面导航
 */
export function navigateTo(url: string): void {
  uni.navigateTo({ url })
}

export function redirectTo(url: string): void {
  uni.redirectTo({ url })
}

export function switchTab(url: string): void {
  uni.switchTab({ url })
}

export function goBack(delta = 1): void {
  uni.navigateBack({ delta })
}

/**
 * 任务状态文本
 */
export function getStatusText(status: string): string {
  const statusMap: Record<string, string> = {
    pending: '待确认',
    confirmed: '待排班',
    scheduled: '待出车',
    departed: '已出车',
    arrived: '已到达',
    constructing: '施工中',
    inspecting: '待验收',
    completed: '已完成',
    cancelled: '已取消',
    rejected: '已驳回'
  }
  return statusMap[status] || status
}

/**
 * 任务状态颜色
 */
export function getStatusColor(status: string): string {
  const colorMap: Record<string, string> = {
    pending: '#f59e0b',
    confirmed: '#2563eb',
    scheduled: '#2563eb',
    departed: '#8b5cf6',
    arrived: '#10b981',
    constructing: '#2563eb',
    inspecting: '#f59e0b',
    completed: '#10b981',
    cancelled: '#ef4444',
    rejected: '#ef4444'
  }
  return colorMap[status] || '#6b7280'
}

/**
 * 任务状态背景色
 */
export function getStatusBgColor(status: string): string {
  const bgMap: Record<string, string> = {
    pending: '#fff7ed',
    confirmed: '#eff6ff',
    scheduled: '#eff6ff',
    departed: '#f3e8ff',
    arrived: '#ecfdf5',
    constructing: '#eff6ff',
    inspecting: '#fff7ed',
    completed: '#ecfdf5',
    cancelled: '#fef2f2',
    rejected: '#fef2f2'
  }
  return bgMap[status] || '#f5f5f5'
}

/**
 * 紧急程度文本
 */
export function getUrgentText(urgent: string): string {
  return urgent === 'high' ? '加急' : '普通'
}

/**
 * 任务类型文本
 */
export function getTypeText(type: string): string {
  const typeMap: Record<string, string> = {
    regular: '常规',
    emergency: '应急'
  }
  return typeMap[type] || type
}

/**
 * 角色文本
 */
export function getRoleText(role: string): string {
  const roleMap: Record<string, string> = {
    sales: '销售',
    dispatch: '调度',
    construction: '施工'
  }
  return roleMap[role] || role
}

/**
 * 车辆状态文本
 */
export function getVehicleStatusText(status: string): string {
  const map: Record<string, string> = {
    available: '可用',
    in_use: '使用中',
    maintenance: '维修中'
  }
  return map[status] || status
}

/**
 * 人员状态文本
 */
export function getPersonnelStatusText(status: string): string {
  const map: Record<string, string> = {
    idle: '空闲',
    working: '工作中',
    rest: '休息中',
    standby: '应急待命'
  }
  return map[status] || status
}

/**
 * 项目类型文本
 */
export function getProjectTypeText(type: string): string {
  const map: Record<string, string> = {
    包年: '包年',
    单次: '单次',
    季度: '季度',
    月付: '月付'
  }
  return map[type] || type
}

/**
 * 项目状态文本
 */
export function getProjectStatusText(status: string): string {
  const map: Record<string, string> = {
    pending: '待确认',
    confirmed: '已确认',
    processing: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

/**
 * 通知类型文本
 */
export function getNotificationTypeText(type: string): string {
  const map: Record<string, string> = {
    system: '系统',
    task: '任务',
    audit: '审核'
  }
  return map[type] || type
}

/**
 * 客户状态文本（1 合作中 / 0 已停用 / 2 潜在客户）
 */
export function getCustomerStatusText(status: number | string): string {
  const map: Record<string, string> = {
    1: '合作中',
    0: '已停用',
    2: '潜在客户'
  }
  return map[String(status)] || '-'
}

export function getCustomerStatusColor(status: number | string): string {
  const map: Record<string, string> = {
    1: '#10b981',
    2: '#2563eb',
    0: '#6b7280'
  }
  return map[String(status)] || '#6b7280'
}

export function getCustomerStatusBgColor(status: number | string): string {
  const map: Record<string, string> = {
    1: '#ecfdf5',
    2: '#eff6ff',
    0: '#f3f4f6'
  }
  return map[String(status)] || '#f3f4f6'
}

/**
 * 合同状态文本
 */
export function getContractStatusText(status: string): string {
  const map: Record<string, string> = {
    draft: '草稿',
    pending: '待生效',
    active: '生效中',
    expired: '已过期',
    terminated: '已终止'
  }
  return map[status] || status || '-'
}

export function getContractStatusColor(status: string): string {
  const map: Record<string, string> = {
    draft: '#6b7280',
    pending: '#f59e0b',
    active: '#10b981',
    expired: '#ef4444',
    terminated: '#ef4444'
  }
  return map[status] || '#6b7280'
}

export function getContractStatusBgColor(status: string): string {
  const map: Record<string, string> = {
    draft: '#f3f4f6',
    pending: '#fff7ed',
    active: '#ecfdf5',
    expired: '#fef2f2',
    terminated: '#fef2f2'
  }
  return map[status] || '#f3f4f6'
}

/**
 * 付款方式文本
 */
export function getPaymentMethodText(method: string): string {
  const map: Record<string, string> = {
    lump_sum: '一次性',
    installment: '分期'
  }
  return map[method] || method || '-'
}

/**
 * 金额格式化（元，保留两位）
 */
export function formatMoney(amount: number | string | undefined | null): string {
  if (amount === undefined || amount === null || amount === '') return '-'
  const num = typeof amount === 'string' ? Number(amount) : amount
  if (isNaN(num)) return '-'
  return `¥${num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}
