const api = require('../../../../utils/api')

Page({
  data: {
    statusBarHeight: 20,
    navBarHeight: 44,
    totalNavHeight: 64,
    swiperHeight: 400,
    sliderIndex: 0,
    sliderList: [

      { id: 'listening', src: 'https://ai-c.maimanji.com/images/cooperation/slider_listening.png' },
      { id: 'eldercare', src: 'https://ai-c.maimanji.com/images/cooperation/slider_eldercare.png' },
      { id: 'highend', src: 'https://ai-c.maimanji.com/images/cooperation/slider_highend.png' }
    ],
    entryList: [
      {
        id: 'entertainment',
        title: '休闲娱乐',
        subTitle: '精选活动 精彩人生',
        icon: '/subpackages/cooperation/images/icon_entertainment.png'
      },
      {
        id: 'eldercare',
        title: '智慧养老',
        subTitle: '科技赋能 安享晚年',
        icon: '/subpackages/cooperation/images/icon_eldercare.png'
      }
    ]
  },

  onLoad() {
    const sys = wx.getSystemInfoSync();
    const menu = wx.getMenuButtonBoundingClientRect();
    const statusBarHeight = sys.statusBarHeight || 20;
    const navBarHeight = menu.height + (menu.top - statusBarHeight) * 2;
    this.setData({
      statusBarHeight,
      navBarHeight,
      totalNavHeight: statusBarHeight + navBarHeight
    });
    this.loadBanners();
    this.loadEntries();
  },

  /**
   * 处理图片URL，如果是相对路径则拼接域名，并设置清晰度为85
   */
  processImageUrl(url) {
    if (!url) return ''
    let fullUrl = url
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      const baseUrl = 'https://ai-c.maimanji.com'
      fullUrl = baseUrl + (url.startsWith('/') ? '' : '/') + url
    }
    
    // 添加清晰度参数 q=85
    if (fullUrl.includes('?')) {
      if (!fullUrl.includes('q=')) {
        fullUrl += '&q=85'
      }
    } else {
      fullUrl += '?q=85'
    }
    return fullUrl
  },

  /**
   * 轮播图图片加载完成，自适应高度
   */
  onBannerLoad(e) {
    if (this.data.swiperHeight !== 400) return; // 只计算一次
    const { width, height } = e.detail;
    const sysInfo = wx.getSystemInfoSync();
    // 减去左右padding (24rpx * 2) - 根据 cooperation.wxss 的 .slider-card
    const swiperWidth = sysInfo.windowWidth - (24 * 2 / 750 * sysInfo.windowWidth);
    const ratio = width / height;
    const swiperHeight = swiperWidth / ratio;
    const swiperHeightRpx = swiperHeight * (750 / sysInfo.windowWidth);
    
    this.setData({
      swiperHeight: swiperHeightRpx
    });
  },

  /**
   * 加载合作页Banner
   */
  async loadBanners() {
    try {
      const res = await api.pageAssets.getCooperationBanners()
      console.log('合作页Banner API响应:', res)
      
      if (res.success && res.data && res.data.length > 0) {
        const sliderList = res.data.map(item => ({
          id: item.id,
          src: this.processImageUrl(item.asset_url),
          link: item.description // 假设描述字段存放跳转链接
        }))
        this.setData({ sliderList })
      }
    } catch (err) {
      console.error('加载合作页Banner失败', err)
    }
  },

  /**
   * 加载合作页入口图标
   */
  async loadEntries() {
    try {
      // 合作页的入口图标与服务页的服务图标共用 service_icons 分组
      const res = await api.pageAssets.getAssets('service_icons')
      console.log('合作页入口图标 API响应:', res)
      
      if (res.success && res.data) {
        const icons = res.data
        const { entryList } = this.data
        
        const updatedEntryList = entryList.map(item => {
          // 尝试匹配图标，例如 id='medical' 对应 icons['medical']
          const iconUrl = icons[item.id]
          if (iconUrl) {
            return {
              ...item,
              icon: this.processImageUrl(iconUrl)
            }
          }
          return item
        })
        
        this.setData({ entryList: updatedEntryList })
      }
    } catch (err) {
      console.error('加载合作页入口图标失败', err)
    }
  },

  onBack() {
    wx.navigateBack({ delta: 1 });
  },

  onSwiperChange(e) {
    this.setData({ sliderIndex: Number(e.detail.current || 0) });
  },

  onTapSwiper(e) {
    const index = e.currentTarget.dataset.index
    const item = this.data.sliderList[index]
    if (item && item.link) {
      wx.navigateTo({ url: item.link })
    }
  },

  onTapEntry(e) {
    const id = e.currentTarget.dataset.id;
    // Find link from data
    const entry = this.data.entryList.find(x => x.id === id);
    if (entry && entry.link) {
      wx.navigateTo({ url: entry.link });
      return;
    }

    // Fallback logic if link missing but id matches known routes
    const routes = {
      entertainment: '/pages/entertainment-apply/entertainment-apply',
      medical: '/pages/medical-apply/medical-apply',
      housekeeping: '/pages/housekeeping-apply/housekeeping-apply',
      eldercare: '/pages/eldercare-apply/eldercare-apply'
    };
    const url = routes[id];
    if (url) {
      wx.navigateTo({ url });
    } else {
      wx.showToast({ title: '敬请期待', icon: 'none' });
    }
  },

  onTapOrders() {
    wx.navigateTo({ url: '/pages/orders/orders' });
  }
});
