import cityData from '../../utils/city.js';
import homeApiService from '../../utils/home-api.js';
import activityApiService from '../../utils/activity-api.js';

Page({
  data: {
    banners: [],
    loadingBanners: true,
    types: [
      { type: 'bus', name: '大巴拼车' },
      { type: 'business', name: '商务车' },
      { type: 'charter', name: '包车' }
    ],
    selectedType: 'bus',
    
    // 出发地数据
    fromCityRange: [[], [], []],
    fromCityIndex: [0, 0, 0],
    fromCityText: '',
    
    // 目的地数据
    toCityRange: [[], [], []],
    toCityIndex: [0, 0, 0],
    toCityText: '',
    
    date: '',
    
    
    // 热门路线
    hotRoutes: [],
    loadingHotRoutes: true
  },
  
  onLoad() {
    this.initCityData();
    this.setData({
      date: this.getToday()
    });
    this.loadHomeData();
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      });
    }
    // 每次显示时刷新数据
    this.loadHomeData();
  },

  // 加载首页数据
  async loadHomeData() {
    try {
      // 并行加载海报、热门路线和活动数据
      const [banners, hotRoutes, activities] = await Promise.all([
        homeApiService.getBanners(),
        homeApiService.getHotRoutes(),
        activityApiService.getAllActivities()
      ]);

      // 将活动数据转换为热门路线格式
      const activityRoutes = activities.map(activity => ({
        id: `activity_${activity.id}`,
        name: activity.name,
        from: activity.city,
        to: activity.venue,
        price: '活动专线',
        duration: '活动期间',
        tags: activity.tags || [],
        activityId: activity.id,
        activityName: activity.name,
        startDate: activity.startDate,
        endDate: activity.endDate
      }));

      this.setData({
        banners,
        hotRoutes: [...hotRoutes, ...activityRoutes],
        loadingBanners: false,
        loadingHotRoutes: false
      });
    } catch (error) {
      console.error('加载首页数据失败:', error);
      this.setData({
        loadingBanners: false,
        loadingHotRoutes: false
      });
    }
  },

  // 刷新首页数据
  async refreshHomeData() {
    this.setData({
      loadingBanners: true,
      loadingHotRoutes: true
    });
    
    try {
      const { banners, hotRoutes } = await homeApiService.refreshData();
      this.setData({
        banners,
        hotRoutes,
        loadingBanners: false,
        loadingHotRoutes: false
      });
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('刷新首页数据失败:', error);
      this.setData({
        loadingBanners: false,
        loadingHotRoutes: false
      });
      wx.showToast({
        title: '刷新失败',
        icon: 'none'
      });
    }
  },
  
  // 初始化城市数据
  initCityData() {
    const provinces = cityData.province_list;
    const firstProvince = provinces[0]; // 北京市
    const cities = cityData.city_list[firstProvince] || [];
    const firstCity = cities[0] || '';
    const districts = cityData.district_list[firstCity] || [];
    
    this.setData({
      fromCityRange: [provinces, cities, districts],
      toCityRange: [provinces, cities, districts]
    });
  },
  onTypeChange(e) {
    this.setData({ selectedType: e.currentTarget.dataset.type });
  },
  
  // 出发地选择器列变化
  onFromCityColumnChange(e) {
    const { column, value } = e.detail;
    const { fromCityRange, fromCityIndex } = this.data;
    
    fromCityIndex[column] = value;
    
    if (column === 0) {
      // 省份变化，更新市列表
      const provinceName = fromCityRange[0][value];
      const cities = cityData.city_list[provinceName] || [];
      fromCityRange[1] = cities;
      fromCityRange[2] = [];
      fromCityIndex[1] = 0;
      fromCityIndex[2] = 0;
      
      if (cities.length > 0) {
        const firstCityName = cities[0];
        const districts = cityData.district_list[firstCityName] || [];
        fromCityRange[2] = districts;
      }
    } else if (column === 1) {
      // 市变化，更新区列表
      const cityName = fromCityRange[1][value];
      const districts = cityData.district_list[cityName] || [];
      fromCityRange[2] = districts;
      fromCityIndex[2] = 0;
    }
    
    this.setData({
      fromCityRange,
      fromCityIndex
    });
  },
  
  // 出发地选择确认
  onFromCityChange(e) {
    const index = e.detail.value;
    const { fromCityRange } = this.data;
    const province = fromCityRange[0][index[0]] || '';
    const city = fromCityRange[1][index[1]] || '';
    const district = fromCityRange[2][index[2]] || '';
    
    this.setData({
      fromCityIndex: index,
      fromCityText: `${province}${city}${district}`
    });
  },
  
  // 目的地选择器列变化
  onToCityColumnChange(e) {
    const { column, value } = e.detail;
    const { toCityRange, toCityIndex } = this.data;
    
    toCityIndex[column] = value;
    
    if (column === 0) {
      // 省份变化，更新市列表
      const provinceName = toCityRange[0][value];
      const cities = cityData.city_list[provinceName] || [];
      toCityRange[1] = cities;
      toCityRange[2] = [];
      toCityIndex[1] = 0;
      toCityIndex[2] = 0;
      
      if (cities.length > 0) {
        const firstCityName = cities[0];
        const districts = cityData.district_list[firstCityName] || [];
        toCityRange[2] = districts;
      }
    } else if (column === 1) {
      // 市变化，更新区列表
      const cityName = toCityRange[1][value];
      const districts = cityData.district_list[cityName] || [];
      toCityRange[2] = districts;
      toCityIndex[2] = 0;
    }
    
    this.setData({
      toCityRange,
      toCityIndex
    });
  },
  
  // 目的地选择确认
  onToCityChange(e) {
    const index = e.detail.value;
    const { toCityRange } = this.data;
    const province = toCityRange[0][index[0]] || '';
    const city = toCityRange[1][index[1]] || '';
    const district = toCityRange[2][index[2]] || '';
    
    this.setData({
      toCityIndex: index,
      toCityText: `${province}${city}${district}`
    });
  },
  
  // 交换出发地和目的地
  swapCity() {
    const { fromCityIndex, fromCityText, toCityIndex, toCityText, fromCityRange, toCityRange } = this.data;
    
    this.setData({
      fromCityIndex: toCityIndex,
      fromCityText: toCityText,
      fromCityRange: toCityRange,
      toCityIndex: fromCityIndex,
      toCityText: fromCityText,
      toCityRange: fromCityRange
    });
  },
  onDateChange(e) { 
    this.setData({ date: e.detail.value }); 
  },
  
  searchSchedules() {
    if (!this.data.fromCityText || !this.data.toCityText) {
      wx.showToast({ title: '请选择出发地和目的地', icon: 'none' });
      return;
    }
    
    
    wx.navigateTo({
      url: `/pages/select-activity/select-activity?type=${this.data.selectedType}&from=${this.data.fromCityText}&to=${this.data.toCityText}&date=${this.data.date}`
    });
  },
  
  
  // 海报点击事件
  onBannerTap(e) {
    const { index } = e.currentTarget.dataset;
    const banner = this.data.banners[index];
    
    if (banner && banner.link) {
      // 统计点击
      homeApiService.trackBannerClick(banner.id);
      
      // 跳转到对应页面
      if (banner.link.startsWith('/pages/')) {
        wx.navigateTo({
          url: banner.link
        });
      } else {
        wx.showToast({
          title: banner.title || '海报',
          icon: 'none'
        });
      }
    }
  },

  // 热门路线点击事件
  async selectRoute(e) {
    const { index } = e.currentTarget.dataset;
    const route = this.data.hotRoutes[index];
    
    if (route) {
      // 统计点击
      await homeApiService.trackRouteClick(route.id);
      
      if (route.link && route.link.startsWith('/pages/')) {
        // 跳转到对应页面
        wx.navigateTo({
          url: route.link
        });
      } else {
        // 使用路线信息填充搜索表单
        this.fillSearchForm(route);
        wx.showToast({ 
          title: `已选择${route.name}`, 
          icon: 'success' 
        });
      }
    }
  },

  // 使用热门路线信息填充搜索表单
  fillSearchForm(route) {
    if (route.from && route.to) {
      this.setData({
        fromCityText: route.from,
        toCityText: route.to
      });
    }
  },
  getToday() {
    const d = new Date();
    return `${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2,'0')}-${d.getDate().toString().padStart(2,'0')}`;
  }
});