
// 引入Provider
import { Provider } from 'react-redux';
// 引入仓库
import './App.css'
import store from './store';
import Head from './layout/head/Head.tsx';
import Body from './layout/body/Body.tsx';
// import Foot from './layout/foot/Foot.tsx';
import {
    GlobalContext,
    GlobalData,
    GlobalDataAction,
    GlobalDataActionType,
    GlobalDispatchContext,
} from "./context/GlobalContext.ts";
import React, { Reducer, useReducer, useState, useEffect } from "react";
import { getCode, checkPhone,updatePhone } from './request/api.ts'
import {
    message,
    Modal,
    Form,
    Button,
    Input
} from 'antd';
import { get } from "./util/AjaxUtils.ts";
const App: React.FC = () => {
    const [isTokenFetched, setIsTokenFetched] = useState(false);
    const [isUpdateWxUsernamePhone, setIsUpdateWxUsernamePhone] = useState(false); // 绑定手机号号弹窗
    const [form] = Form.useForm<any>();
    const globalDataReducer = (state: GlobalData, action: GlobalDataAction) => {
        if (action.type == GlobalDataActionType.REFRESH_SELF) {
            if (action.user) {
                state.user.balance = action.user.balance;
                state.user.userId = action.user.userId;
                state.user.nickname = action.user.nickname;
                state.user.username = action.user.username;
                state.user.hasUserInfo = action.user.hasUserInfo;
            }
        }
        return {
            ...state
        }
    }
    const [globalData, dispatch] = useReducer<Reducer<GlobalData, GlobalDataAction>>(globalDataReducer, {
        user: {
            balance: '0',
            userId: '',
            username: '',
            nickname: '',
            hasUserInfo: false
        }
    });
    const [userId, setUserId] = useState(''); // 验证码ID
    const [messageApi, messageContext] = message.useMessage();
    const submit = async(phone:any,code:any) => {
      try{
        const formData = new URLSearchParams();
        formData.append('userId', userId);
        formData.append('phone', phone);
        formData.append('smsCode', code);

        const res = await updatePhone(formData.toString());
        console.log(res);
        
      }catch (error: any) {

        if (error.response) {
            const data = error.response.data;
            messageApi.open({
                type: 'error',
                content: data.msg ? data.msg : `${data.path}(${data.status})`,
            });
        } else {
            console.error(error)
        }
    }
    }
    const onFinish = async (values: any) => {
        // console.log('Success:', values);
        try {
            const res = await checkPhone(values.phone)
            // console.log(res);
            if(res.data == 'SUCCESS'){
                submit(values.phone,values.smsCode)
            }else{
           
                messageApi.open({
                    type: 'error',
                    content: '手机号已被绑定,请更换手机号',
                });
            }

        } catch (error: any) {

            if (error.response) {
                const data = error.response.data;
                messageApi.open({
                    type: 'error',
                    content: data.msg ? data.msg : `${data.path}(${data.status})`,
                });
            } else {
                console.error(error)
            }
        }

    };
    const [countdown, setCountdown] = useState(0); // 倒计时状态

    const sendCode = async () => {
        try {
            // 验证手机号输入项
            await form.validateFields(['phone']);

            setCountdown(120);
            console.log('发送验证码');
            const timer = setInterval(() => {
                setCountdown((prevCountdown) => {
                    if (prevCountdown > 0) {
                        return prevCountdown - 1;
                    } else {
                        clearInterval(timer);
                        return 0;
                    }
                });
            }, 1000);
            // 获取表单phone的值
            // const phone = form.getFieldValue('phone');
            await getCode(form.getFieldValue('phone'))

        } catch (error: any) {

            if (error.response) {
                const data = error.response.data;
                messageApi.open({
                    type: 'error',
                    content: data.msg ? data.msg : `${data.path}(${data.status})`,
                });
            } else {
                console.error(error)
            }
        }

    }
   
    //  const nav = useNavigate();
    useEffect(() => {

        get<any>({
            messageApi,
            url: '/api/user-info/get-user-self',
            onSuccess({ data }: any) {
                // console.log('嘻嘻嘻', data);
                // setIsUpdateWxUsernamePhone(data.isUpdateWxUsernamePhone);
                // if (data.isUpdateWxUsernamePhone == 1) {
                if (data.isUpdateWxUsernamePhone == 1) {
                    setIsUpdateWxUsernamePhone(true);
                }
                setUserId(data.userId);
                // const currentToken = sessionStorage.getItem('token');
                sessionStorage.setItem('token', data.accessToken);
                const token = sessionStorage.getItem('token');
                if (token) {
                    // 若 token 存在，设置 isTokenFetched 为 true
                    setIsTokenFetched(true);
                }
            }
        })

    }, []);
    // const token = sessionStorage.getItem('token');
    // useEffect(() => {
    //     if (token) {
    //         setIsTokenFetched(true)
    //     }


    // }, [token]);
    // 如果 token 还未获取，显示加载页面
    // if (!isTokenFetched) {
    //     return (
    //         <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
    //             <p>正在加载，请稍候...</p>
    //         </div>
    //     );
    // }
    if (isTokenFetched) {
        return (
            <div>
                {messageContext}
                <Provider store={store}>
                    <GlobalContext.Provider value={globalData}>
                        <GlobalDispatchContext.Provider value={dispatch}>
                            <Head />
                            <Body />
                            {/* <Foot/> */}
                        </GlobalDispatchContext.Provider>
                    </GlobalContext.Provider>
                </Provider>
                <Modal
                    title="绑定手机号"
                    okText="确认"
                    cancelText="取消"
                    destroyOnClose={true}
                    footer={null}
                    open={isUpdateWxUsernamePhone}
                    // onOk={() => {
                    //   setOrderDetailModal(false)
                    // }}
                    onCancel={() => {
                        setIsUpdateWxUsernamePhone(false);
                    }}
                    width={500}
                    centered

                >
                    <div className='phoneBox'>
                        <Form name="Form"
                            form={form}
                            onFinish={onFinish}
                            initialValues={{ softWare: '' }}
                        // style={{ maxWidth: 600 }}
                        >
                            <div className='phoneBoxInput'>
                                <div className='phoneBoxTitle'>手机号<span style={{ color: 'red' }}>*</span></div>
                                <Form.Item name="phone" label="" rules={[{ required: true, message: '请输入手机号' },
                                {
                                    pattern: /^1[3-9]\d{9}$/,
                                    message: '请输入有效的手机号'
                                }
                                ]}>
                                    <Input style={{
                                        width: '300px',
                                        height: '42px',
                                    }} placeholder="请输入手机号" />
                                </Form.Item>
                            </div>
                            <div className='phoneBoxInput' style={{
                                position: 'relative',
                                // backgroundColor:'pink',
                            }}>
                                <div className='phoneBoxTitle'>验证码<span style={{ color: 'red' }}>*</span></div>
                                <Form.Item name="smsCode" label="" rules={[{ required: true, message: '请输入验证码' }]}>
                                    <Input style={{
                                        width: '300px',
                                        height: '42px',
                                    }} placeholder="请输入验证码" />
                                </Form.Item>
                                {countdown === 0 ? (
                                    <div
                                        style={{
                                            position: 'absolute',
                                            right: '0',
                                            top: '0',
                                            width: '90px',
                                            height: '42px',
                                            justifyContent: 'center',
                                            alignItems: 'center',
                                            display: 'flex',
                                            cursor: 'pointer',
                                            color: '#929292',
                                            paddingRight: 10,
                                        }}
                                        onClick={sendCode}
                                    >
                                        发送验证码
                                    </div>
                                ) : (
                                    <div
                                        style={{
                                            position: 'absolute',
                                            right: '0',
                                            top: '0',
                                            width: '90px',
                                            height: '42px',
                                            justifyContent: 'center',
                                            alignItems: 'center',
                                            display: 'flex',
                                            color: '#929292',
                                            paddingRight: 10,
                                        }}
                                    >
                                        倒计时 {countdown} 秒
                                    </div>
                                )}
                            </div>
                            <div>
                                <Form.Item>
                                    <Button type="primary" htmlType="submit">
                                        提交
                                    </Button>
                                </Form.Item>
                            </div>

                        </Form>
                    </div>
                </Modal>
            </div>

        );
    }

};

export default App;