import { t } from '@/utils/i18n'
/**
 * 页面跳转
 * @param {string} path - 要跳转的页面路径
 */
export const onPageJump = (path: string) => {
  uni.navigateTo({
    url: path
  })
}

/**
 * 页面返回
 */
export const onPageBack = () => {
  uni.navigateBack()
}

/**
 * 拨打电话
 * @param {string} phoneNumber - 要拨打的电话号码
 * @param {string} title - 拨打电话提示的标题，默认值为空字符串
 */
export const makePhoneCall = (phoneNumber: string, title: string = t('global.call')) => {
  uni.showModal({
    title: title,
    content: phoneNumber,
    confirmText: t('common.confirm'),
    cancelText: t('common.cancel'),
    success: (res: any) => {
      if (res.confirm) {
        uni.makePhoneCall({
          phoneNumber: phoneNumber,
          success: () => {
            console.log('拨打电话成功')
          },
          fail: (error: any) => {
            console.error('拨打电话失败:', error)
          }
        })
      }
    }
  })
}

/**
 * 复制到剪贴板
 * @param {string} content - 要复制的内容
 * @param {string} title - 复制成功提示的标题，默认值为空字符串
 */
export const copyToClipboard = (content: string, title: string = '') => {
  uni.setClipboardData({
    data: content,
    success: () => {
      uni.showToast({
        title: title + t('user.copySuccess'),
        icon: 'none'
      })
    },
    fail: (error: any) => {
      console.error('复制失败:', error)
    }
  })
}

/**
 * 计算最低价格
 * @param {object} priceData - 价格数据对象，键为价格类型，值为价格
 * @returns {object} - 包含最低价格的键值对，{ key: 价格类型, value: 最低价格 }
 */
export const calculateLowestPrice = (priceData: object): { key: string, value: number } => {
  const validEntries = Object.entries(priceData)
        .filter(([, value]) => typeof value === 'number' && value !== 0);
    
    if (validEntries.length === 0) {
        throw new Error('No valid non-zero price found in the data');
    }
    
    const [minKey, minValue] = validEntries.reduce((min, curr) => 
        curr[1] < min[1] ? curr : min
    );
    
    return { key: minKey, value: minValue };
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time: any, cFormat: string) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key as keyof typeof formatObj]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value as number] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * 获取文件扩展名
 * @param {string} url - 文件的URL
 * @returns {string} - 文件的扩展名（不包含点号），如果没有扩展名则返回空字符串
 */
export function getFileExtension(url: string) {
  // 移除查询参数和hash
  const cleanUrl = url.split(/[?#]/)[0];
  
  // 获取文件名
  const filename = cleanUrl.split('/').pop();
  
  // 提取扩展名（支持多个点的情况）
  const parts = filename?.split('.');
  
  if (parts?.length && parts.length <= 1) {
    return ''; // 没有扩展名
  }
  
  // 返回最后一个点之后的部分
  return parts?.pop() || '';
}