import config from '@/config'
const mapKey = config.mapKey;
const appName = config.appName;
// const QQMapWX = require('./qqmap-wx-jssdk.js')
import QQMapWX from './qqmap-wx-jssdk.js'



/**
 * 腾讯位置服务地图选点
 */
const chooseLocationInit = (data,addressData) => {
	console.log("TCL: chooseLocationInit -> addressData", addressData)
  // const key = mapKey; //使用在腾讯位置服务申请的key
  // const referer = appName; //调用插件的app的名称
  // wx.navigateTo({
  //   url: `plugin://chooseLocation/index?key=${key}&referer=${referer}`,
  // });
  return new Promise((resolve, reject) => { 
    
    wx.chooseLocation({
      ...data,
      success: function(res){
        console.log('111',res);
        if(res.address){
          const result = splitAddress(res.address);
					console.log("TCL: chooseLocationInit -> result", result)
          const handlecityData = getCityCode([result.province,result.city,result.district].join(' '),addressData)
					console.log("TCL: chooseLocationInit -> handlecityData", handlecityData,{...res,cityCode:handlecityData})
          resolve({...res,cityCode:handlecityData})
        }else{
          resolve(data)
        }
        
        },
        fail: function(res){
          console.log('fail',res);
          reject();
        }
    })
  })
}

/**
 * 腾讯位置服务城市选择器
 * @param {*} city 城市名称
 */
const citySelectorNavigateTo = (city) => {
  const key = mapKey; // 使用在腾讯位置服务申请的key
  const referer = appName; // 调用插件的app的名称
  const hotCitys = '重庆'; // 用户自定义的的热门城市

  // wx.navigateTo({
  //   url: `plugin://citySelector/index?key=${key}&referer=${referer}&hotCitys=${hotCitys}`,
  // })

  // wx.choosePoi({
  //   success: function(res){
  //   // address: "重庆市永川区文昌西路南"
  //   // errMsg: "choosePoi:ok"
  //   // latitude: 0
  //   // longitude: 0
  //   // name: "中国人民大学文化科技园"
  //   // type: 2
  //     console.log('111',res);
      
  //   },
  //   fail: function(res){
  //     console.log('fail',res);
      
  //   }
  // })

  // return new Promise((resolve, reject) => { 
  //   wx.chooseLocation({
  //     success: function(res){
  //         console.log('111',res);
  //         resolve(res)
  //       },
  //       fail: function(res){
  //         console.log('fail',res);
  //         reject();
  //       }
  //   })
  // })


}

function locateTheCurrentAddress(ad_array){
  return new Promise((resolve, reject) => { 
      wx.getFuzzyLocation({
        type: 'gcj02',
        success: function (res) {
          const { latitude, longitude } =res;
          const qqmapsdk = new QQMapWX({ key: mapKey });
          qqmapsdk.reverseGeocoder({ 
            location: [latitude,longitude].join(','), // GCJ-02经纬度（纬度在前，经度在后）
            success: (res) => {
              console.log(res.result);
              const {address_component,formatted_addresses} =  res.result;
              const {province,city,district} = address_component;
              const handlecityData = getCityCode([province,city,district].join(' '),ad_array)
              resolve({
                name:formatted_addresses.standard_address,
                cityCode:handlecityData,
                latitude,
                longitude
              })
            },
            fail: (err) => { console.error(err);reject();  }
          });
          console.log('111', res,);

        },
        fail: function (res) {
          console.log('fail', res);
          reject();
        }
      })
  })
}

function splitAddress(address) {
  // 处理直辖市（如北京市朝阳区）
  const directCityRegex = /^(北京|天津|上海|重庆)(市)?(.+?(区|县))/;
	console.log("TCL: splitAddress -> directCityRegex", directCityRegex)
  const directMatch = address.match(directCityRegex);
	console.log("TCL: splitAddress -> directMatch", directMatch)
  if (directMatch) {
    return {
      province: directMatch[1],
      city: directMatch[1] + '市',
      district: directMatch[3],
      detail: address.replace(directCityRegex, '')
    }
  }

  // 常规拆分逻辑 
  const provinceRegex = /(.+?(省|自治区|行政区|特别行政区))/;
  const cityRegex = /(.+?(市|自治州|州|盟))/;

  const province = address.match(provinceRegex)?.[1] || '';
  const city = address.replace(province, '').match(cityRegex)?.[1] || '';
  const remaining = address.replace(province + city, '');
  const district = remaining.match(/(.+?( 区|县|市|旗))/)?.[1] || '';
  const detail = remaining.replace(district, '').trim();

  return { province, city, district, detail };
}


function normalizeAddress(str) {
  return str.replace(/(市|区|省)/g, '').trim();
}
/**
 * 根据地址字符串返回 name 数组、code 数组、index 路径
 * @param {string} address 例如："重庆 重庆市 永川区"
 * @returns {Object|null} 包含 data/name、code、index 的对象
 */
const getCityCode = (address,addressData) => {
	console.log("TCL: getCityCode -> address", address)
  if(!addressData) return null;
   //address:重庆市永川区人民大道191号
  const names = address.split(/\s+/)
  const result = {
    data: [],
    code: [],
    index: []
  }

  // 查找省份
  const provinceIndex = addressData.findIndex(p => p.name.includes(names[0]))
	console.log("TCL: getCityCode -> provinceIndex", provinceIndex)
  if (provinceIndex === -1) return null

  const province = addressData[provinceIndex]
  result.data.push(province.name)
  result.code.push(province.regionCode)
  result.index.push(provinceIndex)

  if (names.length < 2) return result

  // 查找城市
  const cityIndex = province.children.findIndex(c => c.name.includes(names[1]))
  if (cityIndex === -1) return result

  const city = province.children[cityIndex]
  result.data.push(city.name)
  result.code.push(city.regionCode)
  result.index.push(cityIndex)

  if (names.length < 3) return result

  // 查找区县
  const districtIndex = city.children.findIndex(d => d.name.includes(names[2]))
  if (districtIndex === -1) return result

  const district = city.children[districtIndex]
  result.data.push(district.name)
  result.code.push(district.regionCode)
  result.index.push(districtIndex)
	console.log("TCL: getCityCode -> result", result)

  return result


}
export {
  chooseLocationInit,
  citySelectorNavigateTo,
  splitAddress,
  getCityCode,
  locateTheCurrentAddress
}
