import { defineStore } from 'pinia'
import { getConfig } from '@/api/app'
import { isWeixinClient } from '@/utils/client'
// #ifdef H5
import { getLocation } from '@/hooks/wechat'
// #endif
import { getGeocoderCoordinate } from '@/api/app'

interface City {
    name: string | null | undefined
    city_id: number | null | undefined | string
    latitude: string | null | undefined
    longitude: string | null | undefined
}

interface AppSate {
    config: Record<string, any>
    cityInfo: City
    sysInfo: Record<string, any>
}
export const useAppStore = defineStore({
    id: 'appStore',
    state: (): AppSate => ({
        // 公共配置
        config: {},
        // 城市信息
        cityInfo: {
            name: '选择',
            city_id: '',
            latitude: '',
            longitude: ''
        },
        // 系统信息
        sysInfo: {}
    }),
    getters: {
        getWebsiteConfig: (state) => state.config.website || {},
        getLoginConfig: (state) => state.config.login || {},
        getTabbarConfig: (state) => state.config.tabbar || [],
        getStyleConfig: (state) => state.config.style || {},
        getH5Config: (state) => state.config.h5 || {},
        cityData: (state) => state.cityInfo
    },
    actions: {
        getImageUrl(url: string) {
            return url ? `${this.config.domain}${url}` : ''
            // return url || ''
        },
        async getConfig() {
            const data = await getConfig()
            this.config = data
        },

        setCityInfo(city: City) {
            this.cityInfo = city
            uni.$emit('refreshhome')
        },

        // 获取系统信息
        getSystemInfoFn() {
            uni.getSystemInfo({
                success: (res) => {
                    const { statusBarHeight, platform }: any = res
                    let navHeight
                    if (platform == 'ios' || platform == 'devtools') {
                        navHeight = statusBarHeight + 44
                    } else {
                        navHeight = statusBarHeight + 48
                    }
                    this.sysInfo = {
                        ...res,
                        navHeight
                    }
                    console.log('获取系统信息', res)
                },
                fail(err) {
                    console.log(err)
                }
            })
        },

        // 初始化获取位置
        async getLocationFunc() {
            let res: any
            const slef = <any>this
            try {
                if (isWeixinClient()) {
                    console.log('----')

                    try {
                        res = await getLocation()

                        slef.initCityFunc(res.latitude, res.longitude)
                        console.log('获取位置成功：', res)
                    } catch (e) {
                        console.log('获取位置失败：', e)
                    }
                } else {
                    console.log('===')
                    uni.getLocation({
                        // #ifndef APP
                        type: 'gcj02',
                        // #endif
                        success(res) {
                            slef.initCityFunc(res.latitude, res.longitude)
                        },
                        fail(result) {
                            console.log(result)
                            // #ifdef MP
                            if (!slef.sysInfo.locationEnabled) {
                                return uni.showModal({
                                    title: '温馨提示',
                                    content: '您的手机定位还未开启后，开启后重新进入小程序或刷新'
                                })
                            }
                            slef.getAuthorizeFunc()
                            // #endif
                        }
                    })
                }
            } catch (err) {
                console.log('失败原因：', err)
            }
        },

        // 小程序未开启定位或拒绝授权
        async getAuthorizeFunc() {
            const data: any = await uni.showModal({
                title: '您已拒绝地理位置权限',
                content: '是否进入权限管理，调整授权？'
            })
            if (data.confirm) {
                const data: any = await uni.openSetting()
                if (data.authSetting['scope.userLocation']) this.getLocationFunc()
            }
        },

        // 逆解析地址
        async initCityFunc(latitude: string, longitude: string) {
            try {
                const res1 = await getGeocoderCoordinate({
                    lat: latitude,
                    lng: longitude
                })
                const obj = {
                    name: res1.amapGenCoderResponse.amapAddressComponent.city, // 市
                    city_id: res1.cityId,
                    latitude,
                    longitude
                }
                this.setCityInfo(obj)
            } catch (error) {
                console.log('逆解析地址：', error)
            }
        }
    }
})
