import { useEffect, useState } from 'react';

import { PlanTagType } from '@/defines';
import { userConfigModel } from '@/models/userConfigModel';
import { fetchGetUserConfig, fetchPlanList, fetchPayTypeList } from '@/services/config';
import { setToken, userKey } from '@/utils/authUtils';
import { secureLocalStorage as ls } from '@/utils/localUtils';
import { getUniqueSign } from '@/utils/stringUtils';
import { currentUnixTimestamp } from '@/utils/timeUtils';

export interface Plan {
    id: string;
    title: string;
    subTitle: string;
    introduce: string;
    tag?: string;
    tagType?: PlanTagType;
    price: number;
    isDefault: boolean;
}

export interface UseServiceReturn {
    plans: Plan[];
    payMethods: API.PayTypeItem[];
}

export function useService(): UseServiceReturn {
    const { setUserConfig } = userConfigModel.useModel();

    const [plans, setPlans] = useState<Plan[]>([]);
    const [payMethods, setPayMethods] = useState<API.PayTypeItem[]>([]);

    useEffect(() => {
        const userinfo = ls.getLocal<API.UserInfo>(userKey);
        const expired = (userinfo?.accessExpires ?? 0) - currentUnixTimestamp() <= 0;
        if (expired) return; // 如果 accessToken 过期，什么都不做
        if (userinfo?.account?.username) return; // 否则，如果用户信息存在，也什么都不做
        // 请求用户信息
        fetchGetUserConfig({})
            .then((res) => {
                const data = res?.data;
                if (!data) return;
                setToken(data);
                setUserConfig(data);
            })
            .catch(() => {});
    }, [setUserConfig]);

    useEffect(() => {
        fetchPlanList({})
            .then((res) => {
                const list = res?.data?.list ?? [];
                const mapped: Plan[] = list.map((item) => ({
                    id: item.channelItemId ?? getUniqueSign(),
                    title: item.title ?? '',
                    subTitle: item.subTitle ?? '',
                    introduce: item.introduce ?? '',
                    tag: item.tag,
                    tagType: item.tagType ?? PlanTagType.NONE,
                    price: item.price ?? 0,
                    isDefault: item.isDefault ?? false,
                }));
                setPlans(mapped);
            })
            .catch(() => {});
    }, []);

    useEffect(() => {
        fetchPayTypeList({})
            .then((res) => {
                const list = res?.data?.payTypeList ?? [];
                setPayMethods(list);
            })
            .catch(() => {});
    }, []);

    return {
        plans,
        payMethods,
    };
}
