import useModel, { City } from './model'
import { Apis } from '@/gen/Apis'
import { getApiLoading } from '@/common/libraries/apiLoading'
import { useWeAppAuthStore } from '@/common'
import config from '@/common/libraries/config'
const auth = useWeAppAuthStore()
/**
 * 搜索输入处理
 */
const onSearchInput = (e: any) => {
  useModel.searchKeyword.value = e.detail.value
}

/**
 * 清空搜索
 */
const clearSearch = () => {
  useModel.searchKeyword.value = ''
}

/**
 * 选择城市
 */
const selectCity = (city: City) => {
  console.log('选择城市:', city)
  // TODO: 返回上一页并传递选中的城市
  // 可以通过事件总线或 uni.$emit 传递数据
  auth.data.address_city = {city: city?.name || '',...city}
//   uni.$emit('citySelected', city)
  uni.navigateBack({
    delta: 1
  })
}

/**
 * 滚动到指定字母区域
 */
const scrollToSection = (letter: string) => {
  useModel.scrollToId.value = `section_${letter}`
}

/**
 * 获取定位
 */
const getLocation = () => {
  // TODO: 实际项目中调用定位API
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
      console.log('当前位置：', res)
      // 根据经纬度获取城市名称
      // 可以调用逆地理编码API获取城市信息
      // currentCity.value = { name: '深圳', pinyin: 'shenzhen', code: '440300' }
    },
    fail: (err) => {
      console.log('获取定位失败：', err)
      uni.showToast({
        title: '获取定位失败',
        icon: 'none'
      })
    }
  })
}

/**
 * 获取城市列表（从接口获取）
 */
const getCityList = () => {
  // TODO: 调用接口获取城市列表
  // const res = await Apis.City.List()
  // useModel.allCities.value = res.data
   getApiLoading(Apis.Asset.AssetHouses.GetCities, {app_id: config?.WxAppId}).then(res => {
      useModel.openCities.value = res.data || []
      console.log(res)
    })
}

export default {
  onSearchInput,
  clearSearch,
  selectCity,
  scrollToSection,
  getLocation,
  getCityList
}
