/* eslint-disable prettier/prettier */
import { defineStore } from 'pinia'
import { apiConfig } from '@/api/app'
import { isWeixinClient } from '@/utils/client'
// #ifdef H5
import { getLocation } from '@/hooks/wechat'
// #endif
import { getGeocoderCoordinate } from '@/api/app'
import { apiUpdateLocation } from '@/api/user'

import { USER_INFO } from '@/enums/cacheEnums'
import cache from '@/utils/cache'
import { TOKEN_KEY, CONFIG } from '@/enums/cacheEnums'

// 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>
    isFirstLogin: boolean
    locationTimer: any
    selectedList: number[]
}
export const useAppStore = defineStore({
    id: 'appStore',
    state: (): AppSate => ({
        // 公共配置
        config: cache.get(CONFIG) || {},
        // 城市信息
        // cityInfo: {
        //     name: '选择',
        //     city_id: '',
        //     latitude: '',
        //     longitude: ''
        // },
        // 系统信息
        sysInfo: {},
        //第一次登录进来系统后，检修员和维修员角色需要获取定位权限
        isFirstLogin: false,
        locationTimer: null,
        selectedList: []
    }),
    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,
        firstLogin: state => state.isFirstLogin
    },
    actions: {
        getImageUrl(url: string) {
            return url ? `${this.config.domain}${url}` : ''
            // return url || ''
        },
        // async getConfig() {
        //     const data = await apiConfig()
        //     this.config = data
        //     cache.set(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() {
            return new Promise(async resolve => {
                let res: any
                const slef = <any>this
                try {
                    // eslint-disable-next-line prettier/prettier
                    if (isWeixinClient()) {
                        try {
                            res = await getLocation()
                            slef.initCityFunc(res.latitude, res.longitude)
                            console.log('获取位置成功：', res)
                        } catch (e) {
                            console.log('获取位置失败：', e)
                        }
                    } else {
                        const flag = await this._checkAuthByLocation()
                        if (flag) {
                            resolve(true)
                            return
                        }
                        uni.getLocation({
                            // #ifndef APP
                            type: 'gcj02',
                            // #endif
                            success(res) {
                                resolve(true)
                            },
                            fail(result) {
                                console.log('failed========')
                                // #ifdef MP
                                if (!slef.sysInfo.locationEnabled) {
                                    return uni.showModal({
                                        title: '温馨提示',
                                        content: '您的手机定位还未开启，开启后重新进入小程序或刷新'
                                    })
                                }
                                slef.getAuthorizeFunc(2)
                                // #endif
                                resolve(false)
                            }
                        })
                    }
                } catch (err) {
                    resolve(false)
                    console.log('失败原因：', err)
                }
            })
        },

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

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

        //         //! 调试改为广州市
        //         const obj = {
        //             name: '广州市', // 市
        //             city_id: 440100,
        //             latitude: '23.120049',
        //             longitude: '113.30765'
        //         }
        //         this.setCityInfo(obj)
        //     }
        // },
        // 获取详细地址
        getLocationAddress() {
            const slef = <any>this
            return new Promise((resolve, reject) => {
                uni.getLocation({
                    // #ifndef APP
                    type: 'gcj02',
                    // #endif
                    async success(res) {
                        const res1 = await getGeocoderCoordinate({
                            lat: res.latitude,
                            lng: res.longitude
                        })
                        resolve(res1.amapGenCoderResponse.address)
                    },
                    fail(result) {
                        console.log('failed========')

                        // #ifdef MP
                        if (!slef.sysInfo.locationEnabled) {
                            return uni.showModal({
                                title: '温馨提示',
                                content: '您的手机定位还未开启，开启后重新进入小程序或刷新'
                            })
                        }
                        slef.getAuthorizeFunc(1)
                        // #endif
                        resolve(false)
                    }
                })
            })
        },

        getLocation() {
            uni.getLocation({
                // #ifndef APP
                type: 'gcj02',
                // #endif
                success: async res => {
                    console.log('当前位置', res)
                    const userInfo = cache.get(USER_INFO)
                    await apiUpdateLocation({
                        id: userInfo.id,
                        longitude: res.longitude,
                        latitude: res.latitude
                    })
                }
            })
        },
        // 是否获取位置权限
        _checkAuthByLocation() {
            return new Promise(resolve => {
                uni.getSetting({
                    success: res => {
                        if (!res.authSetting['scope.userLocation']) {
                            return resolve(false)
                        }
                        resolve(true)
                    },
                    fail: res => {
                        console.log(res)
                    }
                })
            })
        },
        setFirstLogin(flag: boolean) {
            this.isFirstLogin = flag
        },
        // 设置定时器获取检修员，维修员位置
        async updateLocation() {
            this.closeTimer()
            const token = cache.get(TOKEN_KEY)
            if (!token) return
            const authFlag = (await this._checkAuthByLocation()) as boolean //是否授权位置
            if (!authFlag) return
            const userInfo = cache.get(USER_INFO)
            this.getLocation()
            const interval = this.config?.repairerLocation || 5
            console.log('this.config', this.config, userInfo, interval)

            this.locationTimer = setInterval(() => {
                this.getLocation()
            }, 1000 * 60 * interval)
        },
        closeTimer() {
            clearInterval(this.locationTimer)
        },
        setSelectedList(code: number) {
            if (this.selectedList.includes(code)) return
            this.selectedList.push(code)
            console.log('this.selectedList', this.selectedList)
        },
        clearSelectedList() {
            this.selectedList = []
        }
    }
})
