/**
 * 工具函数模块
 */

/**
 * 格式化价格（保留两位小数）
 * @param {number|string} price 
 * @returns {string}
 */
function formatPrice(price) {
  const num = parseFloat(price);
  if (isNaN(num)) return '0.00';
  return num.toFixed(2);
}

/**
 * 格式化日期
 * @param {string|Date} dateStr 
 * @param {string} format - 格式模板，默认 'YYYY-MM-DD HH:mm:ss'
 * @returns {string}
 */
function formatDate(dateStr, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;
  
  const pad = (n) => String(n).padStart(2, '0');
  const map = {
    'YYYY': date.getFullYear(),
    'MM': pad(date.getMonth() + 1),
    'DD': pad(date.getDate()),
    'HH': pad(date.getHours()),
    'mm': pad(date.getMinutes()),
    'ss': pad(date.getSeconds())
  };
  
  return format.replace(/YYYY|MM|DD|HH|mm|ss/g, matched => map[matched]);
}

/**
 * 相对时间（如：3分钟前、2小时前、昨天）
 * @param {string} dateStr 
 * @returns {string}
 */
function timeAgo(dateStr) {
  if (!dateStr) return '';
  const now = Date.now();
  const date = new Date(dateStr).getTime();
  const diff = now - date;
  const seconds = Math.floor(diff / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);

  if (days > 30) return formatDate(dateStr, 'MM月DD日');
  if (days > 7) return Math.floor(days / 7) + '周前';
  if (days > 0) return days + '天前';
  if (hours > 0) return hours + '小时前';
  if (minutes > 0) return minutes + '分钟前';
  return '刚刚';
}

/**
 * 订单状态中文映射
 */
const ORDER_STATUS = {
  'pending_pay': { label: '待付款', color: '#ee0a24', tag: 'danger' },
  'pending_ship': { label: '待发货', color: '#FF8A00', tag: 'warning' },
  'shipped': { label: '已发货', color: '#4A7CF7', tag: 'primary' },
  'received': { label: '待评价', color: '#00B578', tag: 'success' },
  'completed': { label: '已完成', color: '#999999', tag: 'gray' },
  'closed': { label: '已关闭', color: '#999999', tag: 'gray' },
  'refunding': { label: '退款中', color: '#ee0a24', tag: 'danger' },
};

function getOrderStatusInfo(status) {
  return ORDER_STATUS[status] || { label: status, color: '#999', tag: 'gray' };
}

/**
 * 格式化手机号（中间四位隐藏）
 * @param {string} phone 
 * @returns {string}
 */
function maskPhone(phone) {
  if (!phone) return '';
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

/**
 * 图片加载失败占位图
 * @param {object} e - binderror 事件
 */
function handleImageError(e) {
  const dataset = e.currentTarget.dataset || {};
  const errSrc = dataset.errsrc || '/assets/images/placeholder.png';
  e.target.src = errSrc;
}

/**
 * 防抖
 */
function debounce(fn, delay = 300) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

/**
 * 节流
 */
function throttle(fn, delay = 300) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last >= delay) {
      last = now;
      fn.apply(this, args);
    }
  };
}

module.exports = {
  formatPrice,
  formatDate,
  timeAgo,
  getOrderStatusInfo,
  maskPhone,
  handleImageError,
  debounce,
  throttle
};
