const mapConfig = require('../../../utils/map-config.js');
const config = require('../../../config/config.js');

Page({
  data: {
    searchKeyword: '',
    searchResults: [],
    showSearchTips: true,
    showNoResults: false,
    currentCity: '乌鲁木齐市'
  },

  onLoad: function() {
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: '搜索地点'
    });

    // 获取用户当前位置和城市
    this.getUserCurrentLocation();
  },

  // 获取用户当前位置和城市
  getUserCurrentLocation: function() {
    wx.showLoading({
      title: '获取位置中...',
    });

    // 获取经纬度信息
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        const latitude = res.latitude;
        const longitude = res.longitude;

        // 通过经纬度获取城市信息
        wx.request({
          url: 'https://restapi.amap.com/v3/geocode/regeo',
          method: 'GET',
          data: {
            key: config.amapKey || mapConfig.MAP_CONFIG.amapKey,
            location: `${longitude},${latitude}`,
            extensions: 'all'
          },
          success: (regeoRes) => {

            wx.hideLoading();

            if (regeoRes.data.status === '1' && regeoRes.data.regeocode) {
              const city = regeoRes.data.regeocode.addressComponent.city ||
                          regeoRes.data.regeocode.addressComponent.province;

              if (city) {
                this.setData({
                  currentCity: city
                });

              }
            }
          },
          fail: (error) => {
            console.error('获取城市信息失败:', error);
            wx.hideLoading();
            this.setData({
              currentCity: '乌鲁木齐市'
            });
            wx.showToast({
              title: '无法获取城市信息，使用默认城市乌鲁木齐',
              icon: 'none'
            });
          }
        });
      },
      fail: (error) => {
        console.error('获取位置失败:', error);
        wx.hideLoading();
        this.setData({
          currentCity: '乌鲁木齐市'
        });
        wx.showToast({
          title: '无法获取位置信息，使用默认城市乌鲁木齐',
          icon: 'none'
        });
      }
    });
  },

  onSearchInput: function(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword,
      showSearchTips: keyword.length === 0 && this.data.searchResults.length === 0,
      showNoResults: false
    });

    if (keyword.trim()) {
      this.onSearch();
    }
  },

  // 搜索事件
  onSearch: function() {
    const keyword = this.data.searchKeyword.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }

    // 显示加载提示
    wx.showLoading({
      title: '搜索中...',
      mask: true
    });

    wx.request({
      url: 'https://restapi.amap.com/v3/place/text',
      method: 'GET',
      data: {
        key: config.amapKey || mapConfig.MAP_CONFIG.amapKey,
        keywords: keyword,
        city: this.data.currentCity,
        citylimit: true,
        offset: 20,
        extensions: 'all'
      },
      success: (res) => {

        wx.hideLoading();

        if (res.data.status === '1' && res.data.pois && res.data.pois.length > 0) {
          this.setData({
            searchResults: res.data.pois,
            showSearchTips: false,
            showNoResults: false
          });
        } else {
          this.setData({
            searchResults: [],
            showSearchTips: false,
            showNoResults: true
          });
        }
      },
      fail: (error) => {
        console.error('搜索地点失败:', error);
        wx.hideLoading();
        wx.showToast({
          title: '搜索失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 选择搜索结果中的地点
  selectLocation: function(e) {
    const { id } = e.currentTarget.dataset;
    const resultIndex = parseInt(id);
    if (this.data.searchResults[resultIndex]) {
      const selectedPoi = this.data.searchResults[resultIndex];


      console.log('选择的地点原始数据:', JSON.stringify(selectedPoi, null, 2));      console.log('地点距离:', typeof selectedPoi.distance === 'undefined' ? '无' : JSON.stringify(selectedPoi.distance));

      const locationData = {
          name: selectedPoi.name || '',
          address: selectedPoi.address || '',
          distance: Array.isArray(selectedPoi.distance) ?
            (selectedPoi.distance.length > 0 ? selectedPoi.distance[0] : '') :
            (selectedPoi.distance || ''),
          location: selectedPoi.location || '',
          type: selectedPoi.type || '',
          typecode: selectedPoi.typecode || ''
        };

        if (!locationData.name && locationData.address) {
          locationData.name = locationData.address;
        }
        if (!locationData.address && locationData.name) {
          locationData.address = locationData.name;
        }

      wx.setStorageSync('selectedPoi', locationData);

      let storedData = wx.getStorageSync('selectedPoi');

      if (JSON.stringify(storedData) !== JSON.stringify(locationData)) {
        console.warn('存储数据不匹配，重新保存...');
        wx.setStorageSync('selectedPoi', locationData);
        storedData = wx.getStorageSync('selectedPoi');

      }

      setTimeout(() => {
        const finalStoredData = wx.getStorageSync('selectedPoi');

        const pages = getCurrentPages();

        let publishPage = null;
        for (let i = pages.length - 1; i >= 0; i--) {
          if (pages[i].route === 'subpackages/media/edits/edits') {
            publishPage = pages[i];
            break;
          }
        }

        if (publishPage) {
            if (publishPage.receiveLocationData && typeof publishPage.receiveLocationData === 'function') {

              publishPage.receiveLocationData(locationData);
            } else {

              publishPage.setData({
                currentLocation: locationData.address || locationData.name || locationData.toString(),
                locationName: locationData.name || locationData.address || locationData.toString(),
                distance: locationData.distance || '',
                fullAddress: locationData.address && locationData.address !== locationData.name ? locationData.address : ''
              });
              console.log('已通过页面栈设置发布页数据:', {
                currentLocation: locationData.address || locationData.name || locationData.toString(),
                locationName: locationData.name || locationData.address || locationData.toString(),
                distance: locationData.distance || '',
                fullAddress: locationData.address && locationData.address !== locationData.name ? locationData.address : ''
              });
            }
          } else {

        }

        let delta = 1;
        for (let i = pages.length - 1; i >= 0; i--) {
          if (pages[i].route === 'subpackages/media/edits/edits') {
            delta = pages.length - 1 - i;
            break;
          }
        }

        // 返回到发布页
        wx.navigateBack({ delta: delta });

      }, 100);
    }
  },

  // 取消搜索
  onCancel: function() {
    wx.navigateBack();
  }
});
