import {defineStore} from 'pinia'
import {ref} from 'vue'
import {
    appUserGetLoginUserGet,
    appAppointmentTimeQueryAppointmentTimePost,
    appMerchantCartListMerchantPost
} from '@/service'
import Config from '@/config'
import * as R from 'ramda'
import {EventEnum} from "@/constant/enums";
import {dayjs} from '@/plugin'
import {useConfigStore} from "@/store";
import {i18n} from "@/locale";

export const useUserStore = defineStore(
    'user',
    () => {

        // 登录邀请码
        const invitationCode = ref('')

        // 登录token
        const token = ref('')

        // 是否登录
        const isLogin = ref(false)

        // 用户信息
        const userInfo = ref<Partial<IUserInfo>>({})

        // 未读消息数量
        const unreadMessageCount = ref(0)

        // 地址
        const address = ref(null)

        // 预约时间
        const appointmentTime = ref<any>(null)

        // 首页展示的预约时间
        const appointmentTimeShow = computed(()=> {
            const now = dayjs()
            const tomorrow = now.add(1, 'day')
            
            // 如果预约时间不存在，显示明天的星期几
            if(!appointmentTime.value) {
                return `${tomorrow.format('dddd')}`
            }
            
            const endTime = dayjs(+appointmentTime.value.endTime)
            
            // 如果预约时间已经过去，显示明天的星期几
            if(endTime.isBefore(now)) {
                return `${tomorrow.format('dddd')}`
            }
            
            // 如果预约时间还没过去，保持原有格式
            return endTime.format('MM-DD HH:mm')
        })

        // 用户购物车信息
        const userCartAllData = ref(null)

        // 获取用户购物车信息
        const getUserCartAllData = () => {
            if(isLogin.value) {
                appMerchantCartListMerchantPost({}).then(res=> {
                    console.log('获取用户购物车', res)
                    if(res.data) {
                       userCartAllData.value = res.data|| []
                    }
                })
            }
        }

        // 查询用户的预约时间
        function getAppointmentTime() {
            if (!isLogin.value) return
            appAppointmentTimeQueryAppointmentTimePost({}).then(res => {
                appointmentTime.value = res.data || ''
            })
        }

        // 自动定位位置
        const location = ref<{
            location: string;
            formattedAddress?: string;
            longitude: string | number;
            latitude: string | number;
        }>({
            location: '',
            formattedAddress: '',
            longitude: '',
            latitude: '',
        })

        // 用户手动定位的位置
        const userSetLocation = ref({
            location: '',
            longitude: '',
            latitude: '',
        })

        // 用户位置信息
        const userLocation = computed(() => {
            if (location.value.location && !userSetLocation.value.location) {
                return location.value
            } else if(!location.value.location && userSetLocation.value.location) {
                return userSetLocation.value
            } else if(location.value.location && userSetLocation.value.location) {
                return userSetLocation.value
            } else {
                return {
                    formattedAddress: '',
                    location: '',
                    longitude: '',
                    latitude: '',
                }
            }
        })

        watch(
            token,
            (newVal) => {
                isLogin.value = !!newVal
            },
            {
                immediate: true,
            },
        )

        const configStore = useConfigStore()
        const isMember = computed(() => {
            if (!isLogin.value) {
                return false
            }
            if (!userInfo.value?.memberRechargeRecord) {
                return false
            }
            const {memberExpireTime} = userInfo.value.memberRechargeRecord || {}
            if (!memberExpireTime || !configStore.serverTime) {
                return false
            }

            return dayjs(+memberExpireTime).isAfter(dayjs(+configStore.serverTime));

        })

        const checkLogin = (): boolean => {
            console.log('isLogin.value', isLogin.value)
            if (!isLogin.value) {
                uni.navigateTo({
                    url: Config.loginPath,
                })
            }

            return isLogin.value
        }

        const clear = () => {
            userInfo.value = {}
            token.value = ''
            isLogin.value = false
            invitationCode.value = ''
            address.value = null
        }

        const getUserInfo = async () => {
            if (!isLogin.value) return
            try {
                const res = await appUserGetLoginUserGet({})
                userInfo.value = res.data || {}
            } catch (e) {
            }
        }
        function getCityName(latitude: number, longitude: number) {
            const currentLocale =
                typeof i18n.global.locale === 'string'
                    ? i18n.global.locale
                    : i18n.global.locale.value
            const language = currentLocale === 'zh-Hans' ? 'zh-CN' : currentLocale
            const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${Config.googleMapKey}&language=${language}`;

            uni.request({
                url,
                method: 'GET',
                timeout: 10000,
                success: (res: any) => {
                    const results = res.data?.results || [];
                    console.log('geocode results:', results);

                    if (!results.length) {
                        return handleFail();
                    }

                    const addr = results[0]; // 最高匹配度
                    const components = addr.address_components || [];

                    // 提取城市名的工具函数
                    const pickAddress = (types: string[]) => {
                        return components.find((item) => item.types.some((t) => types.includes(t)));
                    };

                    // 寻找城市名（多层兜底）
                    let cityObj =
                        pickAddress(["locality"]) ||
                        pickAddress(["administrative_area_level_2"]) ||
                        pickAddress(["administrative_area_level_1"]) ||
                        pickAddress(["political"]);

                    const cityName = cityObj?.long_name || null;

                    // 从 Google 获取完整地址
                    const formattedAddress = addr.formatted_address || cityName || "";

                    console.log("city:", cityObj);
                    console.log("formattedAddress:", formattedAddress);

                    if (!cityName) {
                        return handleFail();
                    }

                    // 存入 store
                    location.value = {
                        location: cityName,
                        formattedAddress,
                        longitude,
                        latitude
                    };
                },
                fail: () => handleFail()
            });

            function handleFail() {
                console.log('getLocation fail')
            }
        }


        const getLocation = () => {
            uni.getLocation({
                isHighAccuracy: true,
                type: 'wgs84',
                success: async (res) => {
                    console.log('res', res)
                    getCityName(res.latitude, res.longitude)
                },
                fail: (err) => {
                    console.log(err)
                },
            })
        }


        return {
            invitationCode,
            token,
            isLogin,
            isMember,
            userInfo,
            location,
            userSetLocation,
            userLocation,
            address,
            unreadMessageCount,
            appointmentTime,
            appointmentTimeShow,
            userCartAllData,
            getUserCartAllData,
            getUserInfo,
            checkLogin,
            clear,
            getLocation,
            getAppointmentTime,
        }
    },
    {
        persist: true,
    },
)