// entrypoints/popup/pages/Login.tsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Input, Message, Form, Grid } from '@alifd/next';
const { Row, Col } = Grid


export default function Login({ setIsLoggedIn }: { setIsLoggedIn: (loggedIn: boolean) => void }) {
    const formRef = useRef<any>(null); // 创建 ref 引用
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [errors, setErrors] = useState<{ username?: string, password?: string }>({});
    const [keys, setKeys] = useState('');
    const [validImg, setValidImg] = useState('');
    const navigate = useNavigate();

    useEffect(() => {
        evVerify()
    }, [])

    const validateForm = () => {
        const newErrors: { username?: string, password?: string } = {};

        if (!username.trim()) {
            newErrors.username = '请输入用户名';
        }

        if (!password) {
            newErrors.password = '请输入密码';
        } else if (password.length < 6) {
            newErrors.password = '密码长度至少为6位';
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    const evVerify = () => {
        console.log('username')
        fetch('https://user.landwu.com/api/user/verify', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        }).then(resjson => {
            return resjson.json(); // 正确解析 Response 为 JSON 数据
        }).then(res => {
            const { data = {} } = res;
            const { data: info = {} } = data;
            const { key = "", img = "" } = info;
            setKeys(key)
            setValidImg(img)
        })
    }

    const handleLogin = (value: any, e: any) => {
        console.log(e,"rrrrrrr", value)
        return
        e.preventDefault();

        if (!validateForm()) {
            return;
        }

        setLoading(true);

        try {
            const params = {

            }
            // 发送登录请求
            fetch('https://user.landwu.com/api/user/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username,
                    password,
                    code
                }),
            }).then(response => response.json()).then(res => {
                const { key = "" } = this.state;
                values["key"] = key;
                login
                    .login(values)
                    .then((res) => {
                        // this.props.isLogin && this.props.isLogin( {access_token:'access_token--11'});
                        const { msg = "", token = "", code } = res;
                        if (!code) {
                            this.setState(() => {
                                return {
                                    loading: false,
                                };
                            });
                            return false;
                        }
                        console.log(res, "--res", code);

                        if (code == -1) {
                            console.log("code", code)
                            this.verify();
                            message.error(msg);
                            this.setState(() => {
                                return {
                                    loading: false,
                                };
                            });
                            return false;
                        }
                        message.success(msg);
                        // console.log(res, "res",token);

                        // localStorage.setItem("access_token", toCode(token));
                        localStorage.setItem("access_token", token);
                        // Cookies.set("access_token", toCode(token));
                        this.setState(
                            () => {
                                return {
                                    loading: true,
                                };
                            },
                            () => {
                                // this.props.isLogin && this.props.isLogin({ admin: "data.admin" });
                                // this.props.isLogin && this.props.isLogin({ access_token: token });
                                console.log(this.props.history.location.pathname, 'historytoCode', toCode(1), fromCode('<(('))
                                localStorage.removeItem('lw_config_page')
                                localStorage.removeItem('lw_config_limit')
                                localStorage.removeItem('lw_menu_config')

                                localStorage.setItem('nav_index_1', 0)
                                localStorage.removeItem('nav_index_2')
                                localStorage.removeItem('nav_index_3')
                                localStorage.removeItem('is_offline');//是否门店
                                Loading.init()
                                setTimeout(() => {
                                    let parms = {}
                                    if (getIsoffline() == 1) {
                                        parms['is_shipping'] = getIsoffline()
                                    }
                                    user
                                        .user_getProfile(parms)
                                        .then((res) => {
                                            Loading.remove()
                                            console.log(res, '获取用户信息')

                                            const { data = {} } = res;
                                            const { userinfo = {} } = data;
                                            this.getUserInfoLog(userinfo, token)
                                            if (userinfo.is_offline) {
                                                localStorage.setItem('is_offline', toCode(userinfo.is_offline))
                                            }
                                            localStorage.setItem("user_info", JSON.stringify(userinfo));
                                            if (!getQuery('is_link') && getQuery('code')) {
                                                this.pdd_pddServiceAuth(() => {
                                                    location.reload(true);
                                                })

                                            } else {
                                                Loading.init()
                                                rule.rule_getRuleAuth().then(res => {
                                                    Loading.remove()
                                                    const { data } = res
                                                    let data_menu = data;
                                                    console.log(data_menu, '-data_menudata_menudata_menu')
                                                    if (data_menu.length && !getQuery('is_link')) {
                                                        const _indexUrl = data_menu[0]
                                                        const { push } = this.props.history
                                                        console.log(_indexUrl, '_indexUrl')
                                                        // push('')
                                                        push(_indexUrl.url)
                                                        // console.log(_indexUrl,'_indexUrl_indexUrl',this.props.history)
                                                    }
                                                    localStorage.setItem('lw_menu_config', JSON.stringify(data_menu))
                                                    window.location.reload(true);
                                                    this.props.isLogin &&
                                                        this.props.isLogin({
                                                            admin: userinfo.username,
                                                            access_token: token,
                                                        });
                                                }).catch(() => {
                                                    Loading.remove()
                                                })
                                                // this.props.history.push('/index')

                                                // console.log(res,'res')
                                                // location.reload(true);
                                            }
                                            return false;

                                        })
                                        .catch((e) => {
                                            Loading.remove()
                                            // location.reload(true);
                                            this.setState(() => {
                                                return {
                                                    loading: false,
                                                };
                                            });
                                        });
                                }, 200);
                            }
                        );
                    })
                    .catch((e) => {
                        console.log("catch")
                        this.setState(() => {
                            return {
                                loading: false,
                            };
                        });
                    });
            })


        } catch (error) {
            console.error('登录请求失败:', error);
            Message.error('网络错误，请稍后重试');
        }

        // 模拟登录请求
        // setTimeout(() => {
        //     // 这里添加实际的登录逻辑
        //     if (username && password) {
        //         // 模拟登录成功
        //         localStorage.setItem('isLoggedIn', 'true');
        //         setIsLoggedIn(true);
        //         // 跳转到首页
        //         navigate('/');
        //         Message.success('登录成功');
        //     } else {
        //         Message.error('登录失败，请检查用户名和密码');
        //     }
        //     setLoading(false);
        // }, 1000);
    };

    return (
        <div className="bg-gray-50 p-4">
            <div className="text-center mb-6">
                <h1 className="text-2xl font-bold text-gray-800">登录</h1>
            </div>

            <Form onSubmit={handleLogin} ref={formRef}>
                <Form.Item
                    label="用户名"
                    required
                    help={errors.username}
                    validateState={errors.username ? 'error' : undefined}
                >
                    <Input
                        placeholder="请输入用户名"
                        value={username}
                        onChange={(value) => {
                            setUsername(value);
                            if (errors.username) {
                                setErrors({ ...errors, username: undefined });
                            }
                        }}
                        disabled={loading}
                    />
                </Form.Item>

                <Form.Item
                    label="密码"
                    required
                    help={errors.password}
                    validateState={errors.password ? 'error' : undefined}
                >
                    <Input
                        htmlType="password"
                        placeholder="请输入密码"
                        value={password}
                        onChange={(value) => {
                            setPassword(value);
                            if (errors.password) {
                                setErrors({ ...errors, password: undefined });
                            }
                        }}
                        disabled={loading}
                    />
                </Form.Item>
                <Row>
                    <Col span={16}>
                        <Form.Item
                            label="验证码"
                            name="code"
                            required
                        >
                            <Input
                                size="large"
                            />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <img
                            src={validImg}
                            style={{
                                width: 82,
                                height: 30,
                                marginTop: 28
                            }}
                            onClick={evVerify}
                        />
                    </Col>
                </Row>

                <Form.Item>
                    <Button
                        type="primary"
                        htmlType="submit"
                        loading={loading}
                        className="w-full"
                    >
                        {loading ? '登录中...' : '登录'}
                    </Button>
                </Form.Item>
            </Form>

            <div className="mt-4 text-center text-sm text-gray-500">
                <p>忘记密码？请联系管理员</p>
            </div>
        </div>
    );
}