const urlImg = 'https://klmybwg.4dage.com' // 改这个公共图片地址的时候别忘记改wxparse的image和video的前缀
// const urlImg = 'https://sit-kelamayi.4dage.com' // 测试环境
const formatTime = date => {
  // 确保date是Date对象
  const dateObj = date instanceof Date ? date : new Date(date)
  
  const year = dateObj.getFullYear()
  const month = dateObj.getMonth() + 1
  const day = dateObj.getDate()
  const hour = dateObj.getHours()
  const minute = dateObj.getMinutes()
  const second = dateObj.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * 导航到webview页面
 * @param {string} path - 页面路径
 */
const navigateToWebview = (path, mode) => {
  // 检查链接中是否包含type=activity
  if (path.includes('type=activity') && !mode) {
    // 提取链接中的id参数
    const idMatch = path.match(/[?&]id=([^&]*)/);
    if (idMatch) {
      const activityId = idMatch[1];
      console.log('检测到activity类型链接，跳转到活动详情页，id:', activityId);
      wx.navigateTo({
        url: `/pages/exhibition/activeDetails/index?isFrom=weixin&id=${activityId}&type=activity`
      });
      return;
    }
  }
  
  let fullUrl;
  
  // 如果mode为'open'，直接使用原始链接
  if (mode === 'open' || path.includes('https://')) {
    fullUrl = path;
  } else {
    // 配置webview链接
    const envConfig = {
      // 开发环境和测试环境
      development: 'https://klmybwg.4dage.com/mini/#',
      // 正式环境
      production: 'https://klmybwg.4dage.com/mini/#'
    };
    
    // 获取当前环境
    const currentEnv = wx.getAccountInfoSync().miniProgram.envVersion || 'develop';
    let baseUrl = envConfig.development;
    
    if (currentEnv === 'release') {
      baseUrl = envConfig.production;
    }
    
    // 检查path中是否已经包含isFrom参数，避免重复添加
    if (path.includes('isFrom=weixin')) {
      fullUrl = `${baseUrl}${path}`;
    } else {
      const separator = path.includes('?') ? '&' : '?';
      fullUrl = `${baseUrl}${path}${separator}isFrom=weixin`;
    }
  }
  
  wx.navigateTo({
    url: `/pages/webview/index?url=${encodeURIComponent(fullUrl)}`
  });
};

module.exports = {
  urlImg,
  formatTime,
  navigateToWebview
}
