// utils/util.js - 通用工具函数
/**
 * 格式化日期
 * @param {Date|string|number} date 日期
 * @param {string} format 格式 'YYYY-MM-DD HH:mm:ss'
 */
export function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) return ''
  
  const d = 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 hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

/**
 * 格式化金额
 * @param {number|string} amount 金额
 * @param {number} decimals 小数位数
 */
export function formatMoney(amount, decimals = 2) {
  if (!amount && amount !== 0) return '0.00'
  
  const num = parseFloat(amount)
  if (isNaN(num)) return '0.00'
  
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals
  })
}

/**
 * 防抖函数
 * @param {Function} func 要防抖的函数
 * @param {number} delay 延迟时间（毫秒）
 */
export function debounce(func, delay = 300) {
  let timeoutId
  return function (...args) {
    const context = this
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(context, args), delay)
  }
}

/**
 * 节流函数
 * @param {Function} func 要节流的函数
 * @param {number} limit 限制时间（毫秒）
 */
export function throttle(func, limit = 300) {
  let inThrottle
  return function (...args) {
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

/**
 * 手机号脱敏
 * @param {string} phone 手机号
 */
export function maskPhone(phone) {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

/**
 * 身份证号脱敏
 * @param {string} idCard 身份证号
 */
export function maskIdCard(idCard) {
  if (!idCard || idCard.length < 6) return idCard
  return idCard.replace(/(\d{4})\d+(\d{4})/, '$1**********$2')
}

/**
 * 验证手机号
 * @param {string} phone 手机号
 */
export function validatePhone(phone) {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(phone)
}

/**
 * 验证身份证号
 * @param {string} idCard 身份证号
 */
export function validateIdCard(idCard) {
  const idCardRegex = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/
  return idCardRegex.test(idCard)
}

/**
 * 获取文件扩展名
 * @param {string} filename 文件名
 */
export function getFileExtension(filename) {
  if (!filename) return ''
  const lastDot = filename.lastIndexOf('.')
  return lastDot === -1 ? '' : filename.substring(lastDot + 1).toLowerCase()
}

/**
 * 格式化文件大小
 * @param {number} bytes 字节数
 */
export function formatFileSize(bytes) {
  if (!bytes || bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 生成随机字符串
 * @param {number} length 长度
 */
export function generateRandomString(length = 8) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

/**
 * 深拷贝
 * @param {any} obj 要拷贝的对象
 */
export function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (obj instanceof Object) {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

/**
 * 获取查询参数
 * @param {string} url URL地址
 */
export function getQueryParams(url) {
  const params = {}
  const queryString = url.split('?')[1]
  if (queryString) {
    queryString.split('&').forEach(param => {
      const [key, value] = param.split('=')
      params[decodeURIComponent(key)] = decodeURIComponent(value || '')
    })
  }
  return params
}

/**
 * 保险状态映射
 */
export const INSURANCE_STATUS = {
  pending: { text: '待审核', color: '#faad14' },
  approved: { text: '已通过', color: '#52c41a' },
  rejected: { text: '已拒绝', color: '#f5222d' },
  under_review: { text: '审核中', color: '#1890ff' }
}

export const POLICY_STATUS = {
  active: { text: '有效', color: '#52c41a' },
  expired: { text: '已过期', color: '#8c8c8c' },
  cancelled: { text: '已取消', color: '#f5222d' },
  suspended: { text: '暂停', color: '#faad14' }
}

export const CLAIM_STATUS = {
  pending: { text: '待处理', color: '#faad14' },
  reviewing: { text: '审核中', color: '#1890ff' },
  approved: { text: '已批准', color: '#52c41a' },
  rejected: { text: '已拒绝', color: '#f5222d' },
  paid: { text: '已赔付', color: '#722ed1' }
}

/**
 * 获取状态显示信息
 * @param {string} status 状态值
 * @param {string} type 类型 'insurance' | 'policy' | 'claim'
 */
export function getStatusInfo(status, type) {
  const statusMap = {
    insurance: INSURANCE_STATUS,
    policy: POLICY_STATUS,
    claim: CLAIM_STATUS
  }
  
  return statusMap[type]?.[status] || { text: status, color: '#8c8c8c' }
}

export default {
  formatDate,
  formatMoney,
  debounce,
  throttle,
  maskPhone,
  maskIdCard,
  validatePhone,
  validateIdCard,
  getFileExtension,
  formatFileSize,
  generateRandomString,
  deepClone,
  getQueryParams,
  getStatusInfo,
  INSURANCE_STATUS,
  POLICY_STATUS,
  CLAIM_STATUS
}