import {useEffect} from "react";
import Taro from '@tarojs/taro'
import {addShopUserAddress} from "@/api/shop/shopUserAddress";
import { getCurrentLngLat } from "@/utils/location";

const WxAddress = () => {
  /**
   * 从微信API获取用户收货地址
   * 调用微信原生地址选择界面，获取成功后保存到服务器并刷新列表
   */
  const getWeChatAddress = () => {
    Taro.chooseAddress()
      .then(async res => {
        const loc = await getCurrentLngLat()
        if (!loc) {
          // Avoid leaving the user on an empty page.
          setTimeout(() => Taro.navigateBack(), 300)
          return
        }

        // 格式化微信返回的地址数据为后端所需格式
        const addressData = {
          name: res.userName,
          phone: res.telNumber,
          country: res.nationalCode || '中国',
          province: res.provinceName,
          city: res.cityName,
          region: res.countyName,
          address: res.detailInfo,
          postalCode: res.postalCode,
          lng: loc.lng,
          lat: loc.lat,
          isDefault: false
        }
        console.log(res, 'addrs..')
        // 调用保存地址的API（假设存在该接口）
        addShopUserAddress(addressData)
          .then((msg) => {
            console.log(msg)
            Taro.showToast({
              title: `${msg}`,
              icon: 'none'
            })
            setTimeout(() => {
              // 保存成功后返回
              Taro.navigateBack()
            }, 1000)
          })
          .catch(error => {
            console.error('保存地址失败:', error)
            Taro.showToast({title: '保存地址失败', icon: 'error'})
          })
      })
      .catch(err => {
        console.error('获取微信地址失败:', err)
        // 处理用户拒绝授权的情况
        if (err.errMsg.includes('auth deny')) {
          Taro.showModal({
            title: '授权失败',
            content: '请在设置中允许获取地址权限',
            showCancel: false
          })
        }
      })
  }

  useEffect(() => {
    getWeChatAddress()
  }, []);

  return (
    <>
    </>
  );
};

export default WxAddress;
