import { getSignature } from '@/api/index.js';
// #ifdef H5
import wx from 'weixin-js-sdk';
import { h5Url } from '@/common/config.js';
// #endif
import locationService from '@/utils/location.js';

const DEFAULT_JS_API_LIST = ['openAddress', 'getLocation', 'openLocation'];

class AddressService {
    isWeChatBrowser() {
        // #ifdef H5
        return typeof navigator !== 'undefined' && /micromessenger/i.test(navigator.userAgent);
        // #endif
        // #ifndef H5
        return false;
        // #endif
    }

    isWebPlatform() {
        return uni.getSystemInfoSync().uniPlatform === 'web';
    }

    /**
     * 初始化微信 JSSDK（地址相关接口）
     * @param {string[]} jsApiList
     */
    async initWxJssdk(jsApiList = DEFAULT_JS_API_LIST) {
        // #ifdef H5
        if (!this.isWeChatBrowser() || typeof wx === 'undefined') return false;
        try {
            const url = typeof window !== 'undefined'
                ? window.location.href.split('#')[0]
                : `${h5Url}/`;
            const res = await getSignature({ url });
            const config = res.data || {};
            return new Promise((resolve) => {
                wx.config({
                    debug: false,
                    appId: config.appId,
                    timestamp: config.timestamp,
                    nonceStr: config.nonceStr,
                    signature: config.sign || config.signature,
                    jsApiList,
                });
                wx.ready(() => resolve(true));
                wx.error(() => resolve(false));
            });
        } catch (e) {
            console.error('微信 JSSDK 初始化失败', e);
            return false;
        }
        // #endif
        // #ifndef H5
        return false;
        // #endif
    }

    /**
     * 将微信 openAddress 返回值格式化为项目通用结构
     */
    formatWxAddress(data = {}) {
        const detail = data.detailInfo || '';
        const region = [
            data.provinceName,
            data.cityName,
            data.countryName,
        ].filter(Boolean).join('');
        return {
            userName: data.userName || '',
            phone: data.telNumber || '',
            province: data.provinceName || '',
            city: data.cityName || '',
            district: data.countryName || '',
            address: detail,
            atlasAdd: detail,
            name: detail || region,
            fullAddress: `${region}${detail}`,
            postalCode: data.postalCode || '',
            nationalCode: data.nationalCode || '',
        };
    }

    /**
     * 调起微信收货地址（仅微信内置浏览器 H5）
     * @returns {Promise<Object>}
     */
    openAddress() {
        return new Promise(async (resolve, reject) => {
            if (!this.isWeChatBrowser()) {
                reject(new Error('仅支持微信内置浏览器'));
                return;
            }
            const inited = await this.initWxJssdk(['openAddress']);
            if (!inited) {
                reject(new Error('微信 JSSDK 初始化失败'));
                return;
            }
            // #ifdef H5
            wx.openAddress({
                success: (res) => resolve(this.formatWxAddress(res)),
                cancel: () => reject({ cancelled: true, message: '用户取消选择地址' }),
                fail: (err) => reject(err),
            });
            // #endif
        });
    }

    /**
     * 微信 H5：通过 getLocation + 逆地理编码获取当前位置地址
     */
    async getWxCurrentAddress() {
        const gpsResult = await locationService.getWxGPSLocation();
        if (gpsResult.status !== 'success') {
            throw gpsResult.error || new Error('获取位置失败');
        }
        await locationService.updateGeocode();
        const positioning = uni.getStorageSync('positioning') || {};
        const name = positioning.formattedAddress || positioning.cityName || '';
        const address = positioning.formattedAddress || positioning.cityName || '';
        return {
            name,
            address,
            latitude: positioning.latitude,
            longitude: positioning.longitude,
        };
    }

    /**
     * 选择地图位置（统一入口）
     * 微信 H5：getLocation + 逆地理编码；其他平台：uni.chooseLocation
     */
    chooseLocation() {
        return new Promise(async (resolve, reject) => {
            if (this.isWebPlatform() && this.isWeChatBrowser()) {
                try {
                    const result = await this.getWxCurrentAddress();
                    resolve(result);
                } catch (err) {
                    reject(err);
                }
                return;
            }
            uni.chooseLocation({
                success: resolve,
                fail: reject,
            });
        });
    }

    /**
     * 打开地图查看位置
     */
    openLocation({ latitude, longitude, name = '', address = '', scale = 16 }) {
        return new Promise(async (resolve, reject) => {
            if (!latitude || !longitude) {
                reject(new Error('缺少经纬度'));
                return;
            }
            if (this.isWebPlatform() && this.isWeChatBrowser()) {
                const inited = await this.initWxJssdk(['openLocation']);
                if (!inited) {
                    reject(new Error('微信 JSSDK 初始化失败'));
                    return;
                }
                // #ifdef H5
                wx.openLocation({
                    latitude: Number(latitude),
                    longitude: Number(longitude),
                    name,
                    address,
                    scale,
                    success: resolve,
                    fail: reject,
                });
                // #endif
                return;
            }
            uni.openLocation({
                latitude: Number(latitude),
                longitude: Number(longitude),
                name,
                address,
                scale,
                success: resolve,
                fail: reject,
            });
        });
    }
}

export { AddressService };
export default new AddressService();
