/**
 * 通用的 Mapbox 搜索地点函数
 * @param {string} cityName - 城市名称，比如 '上海'
 * @param {string} keyword - 搜索关键词，比如 '星巴克'，如果为空则搜索城市本身
 * @returns {Promise<Array<{ name: string, fullAddress: string, longitude: number, latitude: number }>>}
 */
export async function searchPlacesInCity(country,cityName, keyword = '') {
  const accessToken = 'pk.eyJ1IjoiYWxleDkwMTIiLCJhIjoiY2xtOGw4NHdkMGFndTNjcnFkeWZncGc2dyJ9.lVrAdPHE0Dg5zoWFidfj4Q'; // TODO: 换成你的实际token

  // 先根据城市名称获取中心点
  const cityUrl = `https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(cityName)}.json?country=${country}&access_token=${accessToken}&limit=1&language=zh`;

  const cityCenter = await new Promise((resolve, reject) => {
    uni.request({
      url: cityUrl,
      method: 'GET',
      success: (res) => {
        const data = res.data;
        if (data && data.features && data.features.length > 0) {
			console.log(data)
          const [lng, lat] = data.features[0].center;
		  const bbox = data.features[0].bbox.join(',')
          resolve({ lng, lat,bbox });
        } else {
          reject(new Error('未找到城市中心'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });

  let language = country=='JP'?'ja':'en'
  // 根据城市中心点+关键词搜索附近地点
  const searchQuery = encodeURIComponent(keyword);
  const searchUrl = `https://api.mapbox.com/search/searchbox/v1/forward?q=${encodeURIComponent(searchQuery)}&bbox=${cityCenter.bbox}&access_token=${accessToken}&limit=10&country=${country}&language=${language}`;
  const places = await new Promise((resolve, reject) => {
    uni.request({
      url: searchUrl,
      method: 'GET',
      success: (res) => {
        const data = res.data;
        if (data && data.features && data.features.length > 0) {
          const results = data.features.map(item => ({
            name: item.properties.name,
            fullAddress: item.properties.full_address,
			placeFormat:item.properties.place_formatted,
			type:item.properties.feature_type,
            longitude: item.geometry.coordinates[0],
            latitude: item.geometry.coordinates[1],
          }));
          resolve(results);
        } else {
          resolve([]);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });

  return places;
}
