import * as React from 'react';
import { Form, Input, Checkbox, Button, Row, Col, Select } from 'antd';
import { UserOutlined, LockOutlined, SafetyOutlined } from '@ant-design/icons';
import Copyright from './components/Copyright';
import backgroundSrc from '@/assets/login/background.jpg';
import { useNavigate, useSearchParams, useLocation } from 'react-router-dom';

import { regex } from '@/utils';
import { useLoginStore } from './store';
import './style.less';
import logoSrc from '@/assets/public/dllogo.svg';
import LocalStorage from '@/LocalStorage';

const FormItem = Form.Item;

const Login: React.FC = () => {
    const navigate = useNavigate();
    const [searchParams, setSearchParams] = useSearchParams();
    const location = useLocation();
    
    const {
        buttonLoading,
        captchaData,
        onClickLogin,
        onCaptchaImage,
        init,
        reset
    } = useLoginStore();
    const [form] = Form.useForm();
    const [isTab, setIsTab] = React.useState(true);
    
    // Demo 模式自动登录
    React.useEffect(() => {
        const isDemo = import.meta.env.VITE_USE_MOCK === 'true';
        if (isDemo) {
            // 自动填充 Demo 账号
            form.setFieldsValue({
                username: 'demo',
                password: 'demo123'
            });
            // 自动登录
            handleDemoLogin();
        } else {
            init(form, navigate);
        }
        return () => reset();
    }, []);

    // Demo 模式登录函数
    const handleDemoLogin = async () => {
        try {
            // Demo 模式直接设置用户信息并跳转
            const isDemo = import.meta.env.VITE_USE_MOCK === 'true';
            if (isDemo) {
                // 设置 Demo 用户信息
                localStorage.setItem('token', 'mock-token-demo-12345');
                LocalStorage.setUserInfo({
                    id: '1001',
                    name: '演示用户',
                    tenantId: '100000',
                });
                LocalStorage.setPermissions(['*:*:*']);
                LocalStorage.setRoles(['admin']);
                LocalStorage.setMenuType(1);
                
                // 跳转到首页
                navigate('/appCenter');
                return;
            }
            
            // 非 Demo 模式正常登录
            const mockCaptchaData = {
                uuid: 'demo-uuid',
                img: 'demo-img'
            };
            
            const demoData = {
                username: 'demo',
                password: 'demo123',
                code: '1234',
                uuid: mockCaptchaData.uuid,
                clientId: 'e5cd7e4891bf95d1d19206ce24a7b32e',
                grantType: 'password'
            };
            
            await onClickLogin(demoData, true, navigate, null);
        } catch (error) {
            console.error('Demo 登录失败:', error);
        }
    };

    // 校验密码
    const validatorPassword = (rule: any, value: string) => {
        if (value) {
            const passwordRegex = new RegExp(regex.password);
            if (passwordRegex.test(value)) {
                return Promise.resolve();
            } else {
                return Promise.reject('密码格式不正确');
            }
        } else {
            return Promise.reject('密码不能为空');
        }
    };
    // 集团统一登录
    const group = ()=>{
        return <div id="group-login-form" className="space-y-6">
            <div className="text-center">
              <div className="w-20 h-20 bg-blue-50 rounded-full flex items-center justify-center mx-auto mb-6">
                <i className="fa fa-building text-3xl text-primary"></i>
              </div>
              <h4 className="text-xl font-medium text-neutral-700 mb-3">集团统一身份认证</h4>
              <p className="text-neutral-400 max-w-md mx-auto text-base">
                点击下方按钮，将<span className="font-bold">跳转至集团统一登录平台</span>进行身份验证
              </p>
            </div>
            
            <div className="p-5 bg-neutral-50 rounded-lg border border-neutral-200">
              <div className="flex items-start">
                <div className="flex-shrink-0 mt-0.5">
                  <i className="fa fa-info-circle text-primary text-xl"></i>
                </div>
                <div className="ml-4">
                  <p className="text-base text-neutral-500">
                    集团统一登录将使用您的集团账号密码进行验证，无需重复注册
                  </p>
                </div>
              </div>
            </div>
            <Button color="primary" size='large' className="w-full py-4 bg-white border-2 border-primary text-primary font-medium rounded-lg hover:bg-primary/5" variant="outlined">
              前往集团统一登录平台
            </Button>
          </div>
    } 
    return (
        <div className='login'>
            {/* <img src={backgroundSrc} /> */}
            <div className="w-[55%] bg-gradient-primary text-white p-1 md:p-16 flex flex-col justify-center relative overflow-hidden">
                <div className="relative z-10 max-w-xl mx-auto md:mx-0">
                    <div className="flex items-end mb-12">
                        <div className="flex items-center justify-center mr-4">
                            <img src={logoSrc} alt="Logo" className="w-50 h-50" />
                        </div>
                        {/* <h1 className="text-5xl font-bold">盈科</h1> */}
                    </div>

                    {/* <h2 className="text-[clamp(2.5rem,5vw,3.5rem)] font-bold mb-6 leading-tight">
                        安全登录，<br />高效办公
                    </h2> */}
                    {/* <p className="text-white/80 text-lg mb-10 max-w-lg">
                        提供多种安全登录方式，保障您的信息安全，提升工作效率
                    </p> */}

                    {/* <div className="grid grid-cols-2 gap-6 mt-10">
                        <div className="flex items-start">
                            <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center mr-4 flex-shrink-0">
                                <i className="fa fa-lock text-white"></i>
                            </div>
                            <div>
                                <h3 className="text-xl font-semibold mb-2">安全可靠</h3>
                                <p className="text-white/70">多重加密保障，保护您的账号安全</p>
                            </div>
                        </div>

                        <div className="flex items-start">
                            <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center mr-4 flex-shrink-0">
                                <i className="fa fa-bolt text-white"></i>
                            </div>
                            <div>
                                <h3 className="text-xl font-semibold mb-2">高效便捷</h3>
                                <p className="text-white/70">简化登录流程，提升工作效率</p>
                            </div>
                        </div>
                    </div> */}
                </div>
            </div>
            <div className='login-right'>
                <div className='login-right-content h-[700px]'>
                    <div className="mb-2">
                        <h3 className="text-[clamp(1.5rem,3vw,2.25rem)] font-bold text-neutral-700 mb-3 mt-0">账户登录</h3>
                        <p className="text-neutral-400 text-lg">请选择登录方式并完成验证</p>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-10">
                        <Button type={isTab?'primary':'default'} size='large' onClick={()=>{
                            setIsTab(true);
                        }} >
                            <i className="fa fa-user-circle text-2xl"></i>
                            <span>本地登录</span>
                        </Button>

                        <Button type={!isTab?'primary':'default'} size='large' onClick={()=>{
                            setIsTab(false);
                        }} >
                            <i className="fa fa-building text-2xl"></i>
                            <span>集团统一登录</span>
                        </Button>
                    </div>
                    {isTab&&<Form form={form}>
                        {/* {state.tenantEnabled&&<FormItem
                            name='tenantId'
                            label=''
                            labelCol={{ span: 24 }} 
                            wrapperCol={{ span: 24 }}
                        >
                            <Select
                                options={state.tenantEnabledList}
                                />
                        </FormItem>} */}
                        <FormItem
                            name='account'
                            label='账号'
                            colon={false}
                            rules={[{ required: true, message: '账号不能为空', whitespace: true }]}
                            labelCol={{ span: 24 }}  // 标签占满整行
                            wrapperCol={{ span: 24 }} // 输入框占满整行
                        >
                            <Input size='large' placeholder='请输入账号' prefix={<UserOutlined />} />
                        </FormItem>
                        <FormItem
                            name='password'
                            label='密码'
                            colon={false}
                            rules={[{ required: true, validator: validatorPassword }]}
                            labelCol={{ span: 24 }}  // 标签占满整行
                            wrapperCol={{ span: 24 }} // 输入框占满整行
                        >
                            <Input.Password size='large' placeholder='请输入密码' prefix={<LockOutlined />} />
                        </FormItem>
                        <FormItem
                            name='code'
                            label='验证码'
                            colon={false}
                            rules={[{ required: true, message: '验证码' }]}
                            labelCol={{ span: 24 }}  // 标签占满整行
                            wrapperCol={{ span: 24 }} // 输入框占满整行
                        >
                            <Row gutter={8} >
                                {/* 输入框占大部分宽度 */}
                                <Col span={17}>
                                    <Input size='large' placeholder='请输入验证码' prefix={<SafetyOutlined />} />
                                </Col>
                                {/* 验证码图片固定宽度 */}
                                <Col span={7}>
                                    <div>
                                        <img
                                            src={`data:image/png;base64,${captchaData.img}`}
                                            alt="验证码"
                                            style={{
                                                width: '100%',
                                                height: '38px',
                                                borderRadius: '2px',
                                                cursor: 'pointer'  // 提示可点击刷新
                                            }}
                                            onClick={() => { onCaptchaImage() }}
                                        />
                                    </div>
                                </Col>
                            </Row>
                        </FormItem>
                        <FormItem
                            name='remember'
                            valuePropName='checked'
                        >
                            <Checkbox>
                                记住密码 
                            </Checkbox>
                        </FormItem>
                        <FormItem>
                            <Button
                                type='primary'
                                size='large'
                                block={true}
                                loading={buttonLoading}
                                onClick={() => {
                                    form.validateFields().then(async (values) => {
                                        const data = {
                                            username: values.account,
                                            password: values.password,
                                            // tenantId: values.tenantId,
                                            code: values.code,
                                            uuid: captchaData.uuid,
                                            clientId:'e5cd7e4891bf95d1d19206ce24a7b32e',
                                            grantType:'password'
                                        }
                                        const redirectUrl = searchParams.get('redirectUrl');
                                        console.log('redirectUrl',redirectUrl)
                                        await onClickLogin(data, values.remember,navigate,redirectUrl);
                                    }).catch((error) => {
                                        console.error(error);
                                    });
                                }}
                            >
                                登录
                            </Button>
                        </FormItem>
                    </Form>}
                    {!isTab&&group()}
                </div>
                <Copyright />
            </div>
        </div>
    );
};

export default Login;