import './proj-config-loginpage.css';
import {

    Col,
    // Flex,
    GetProp,
    Input,
    message,
    Modal,
    Row,
    // Space,
    Spin,
    Upload,
    UploadFile,
    UploadProps
} from "antd";
// import { useParams } from "react-router-dom";
import { useEffect, useState } from "react";
// import { DevUserId, get, downloadUrl, put, uploadImageUrl, post } from "../../../util/AjaxUtils.ts";
import { DevUserId, get, downloadUrl, put, uploadImageUrl, post } from "../../util/AjaxUtils.ts";
import { Button, Form } from 'antd';
// import CardImgSelect, { } from "../../../components/card/CardImgSelect.tsx";
import CardImgSelect, { } from "../../components/card/CardImgSelect.tsx";

type FormFieldType = {
    loginpageId: string;
    logo: string;
    bgImgs: string;
    subTitle: string;
    copyrightOwner: string;
    copyrightDate: string;
    adminUsername: string;
    adminPassword: string;
};

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

export default function ProjConfigLoginpage(props: any) {
    // const nav = useNavigate();
    // const pathParams = useParams();
    const [messageApi, contextHolder] = message.useMessage();
    const [form] = Form.useForm<FormFieldType>();
    const [loading, setLoading] = useState<boolean>(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [logoImgArray, setLogoImgArray] = useState<UploadFile[]>([]);
    const [bgImgArray, setBgImgArray] = useState<UploadFile[]>([]);
    const [iframeSrcDoc, setIframeSrcDoc] = useState();
    const height = window.innerHeight - 200;
    const [loginpageArray, setloginpageArray] = useState<any[]>([])
    const [selectedLoginpageId, setSelectedLoginpageId] = useState('');
    // 若无选择的背景 默认的第一个图片的背景
    // const [defaultId, setDefaultId] = useState('')
    const beforeUpload = (file: FileType) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传 JPG/PNG 格式文件!');
        }
        return isJpgOrPng;
    };
    const preview = () => {

        post<any>({
            messageApi,
            url: `/api/proj/preview/${props.projId}`,
            body: {
                // projId: pathParams.projId,
                loginpageId: form.getFieldValue('loginpageId'),
                logo: logoImgArray.length > 0 ? logoImgArray[0].uid : '',
                bgImgs: bgImgArray.length > 0 ? bgImgArray[0].uid : '',
                subTitle: form.getFieldValue('subTitle'),
                copyrightOwner: form.getFieldValue('copyrightOwner'),
                copyrightDate: form.getFieldValue('copyrightDate'),
            },
            onSuccess({ data }) {
                setIframeSrcDoc(data.data);
                console.log(data);

            }
        })
    }
    const getlistLoginpage = () => {
        get<any>({
            messageApi,
            url: '/api/loginpage/list',
            onSuccess({ data }) {
                console.log('登录页图片列表', data);
                setloginpageArray(data)
                // setDefaultId(data[0].loginpageId)
                // upLoginPage(data[0].loginpageId)
            }
        })
    }
    // 获取默认id
    const getDefaultID = () => {
        get<any>({
            messageApi,
            url: '/api/loginpage/list',
            onSuccess({ data }) {
                console.log('登录页图片列表', data);
                setloginpageArray(data)
                // setDefaultId(data[0].loginpageId)
                // upLoginPage(data[0].loginpageId)
                form.setFieldValue('loginpageId', data[0].loginpageId);
                setSelectedLoginpageId(data[0].loginpageId);
                preview()
            }
        })
    }
    // const upLoginPage = (id: string) => {
    //     post<any>({
    //         messageApi,
    //         url: `/api/proj/preview/${pathParams.projId}`,
    //         body: {
    //             // projId: pathParams.projId,
    //             loginpageId:form.getFieldValue('loginpageId'),
    //             logo: logoImgArray.length > 0 ? logoImgArray[0].uid : '',
    //             bgImgs: bgImgArray.length > 0 ? bgImgArray[0].uid : '',
    //             subTitle: form.getFieldValue('subTitle'),
    //             copyrightOwner: form.getFieldValue('copyrightOwner'),
    //             copyrightDate: form.getFieldValue('copyrightDate'),
    //         },
    //         onSuccess({ data }) {
    //             setIframeSrcDoc(data.data);
    //         }
    //     })
    // }
    useEffect(() => {
        getlistLoginpage()
        get<any>({
            messageApi,
            url: `/api/proj/get/config-loginpage/${props.projId}`,
            onSuccess({ data }) {
                console.log('寻找被选中id', data);
                if (data.loginpageId) {
                    form.setFieldValue('loginpageId', data.loginpageId);
                    setSelectedLoginpageId(data.loginpageId);
                    form.setFieldValue('subTitle', data.subTitle);
                    form.setFieldValue('copyrightOwner', data.copyrightOwner);
                    form.setFieldValue('copyrightDate', data.copyrightDate);
                    form.setFieldValue('adminUsername', data.adminUsername);
                    form.setFieldValue('adminPassword', data.adminPassword);
                    preview()
                } else {
                    getDefaultID()
                }

                if (data.logo) {
                    const url = downloadUrl(data.logo);
                    logoImgArray.splice(0, 1, {
                        uid: data.logo,
                        name: 'logo.png',
                        status: 'done',
                        url: url,
                        thumbUrl: url,
                    })
                    setLogoImgArray([
                        ...logoImgArray
                    ])
                }
                if (data.bgImgs) {
                    const url = downloadUrl(data.bgImgs);
                    bgImgArray.splice(0, 1, {
                        uid: data.bgImgs,
                        name: 'bg.png',
                        status: 'done',
                        url: url,
                        thumbUrl: url,
                    })
                    setBgImgArray([
                        ...bgImgArray
                    ])
                }

            }
        })

    }, [])

    return (
        <>
            {contextHolder}
            {/* <Breadcrumb
                items={[
                    {title: <Link to={'/'}>首页</Link>},
                    {title: <Link to={'/proj-create'}>创建项目</Link>},
                    {title: <a onClick={() => {nav(-1)}}>编辑项目</a>},
                    {title: '登录界面设置'},
                ]}
            /> */}
            <div className="form-container" style={{ height: `${height}px`, overflow: 'hidden', padding: '10px', background: '#EFEFEF', boxSizing: 'border-box' }}>
                <div className="loginpage-body" style={{ height: `${height}px`, overflow: 'auto' }}>
                    <Row gutter={15}>

                        <Col span={16}>
                            <div className='loginpage-bodyL' style={{ height: `${height}px`, overflow: 'auto', paddingBottom: '10px', boxSizing: 'border-box' }}>
                                <iframe srcDoc={iframeSrcDoc} style={{
                                    width: '91%',
                                    height: `613px`,
                                    border: '1px solid var(--color-border)',
                                    // background: 'pink',
                                    marginTop: '18px'
                                }} />
                                <div className='loginpage-bodyL-btn'>
                                    <Button
                                        size='large'
                                        type="default"
                                        className='seeButton' onClick={() => {
                                            props.closeModal()
                                            // window.location.reload()
                                        }}>返回</Button>
                                    <Button
                                        type="primary"
                                        size='large'
                                        className='upButton' onClick={() => {
                                            setIsEditModalOpen(true)
                                        }}>确认修改</Button>
                                </div>
                            </div>


                        </Col>

                        <Col span={8}>
                            <div style={{ height: `${height}px`, overflow: 'auto', }}>
                                <div className='setloginpage-right' >
                                    <div className='setloginpage-title'>登陆页面设置</div>
                                    <Form
                                        name="basic"
                                        form={form}
                                        layout="vertical"
                                        labelCol={{ span: 8 }}
                                        wrapperCol={{ span: 24 }}
                                        onFinish={() => {
                                            setIsEditModalOpen(true);
                                        }}
                                        autoComplete="off"
                                    // style={{ background: 'red' }}
                                    >
                                        <div className='setloginpage-formitem'>
                                            <div className='setloginpage-formitem-title'>副标题:</div>
                                            <Form.Item
                                                // label="副标题"
                                                name="subTitle"
                                                rules={[{ required: false, message: '请输入副标题' }]}
                                            >
                                                <Input placeholder="请输入副标题"
                                                    style={{
                                                        width: '375px',
                                                        height: '38px',
                                                        background: ' #F8F8F8'
                                                    }}
                                                    onChange={() => {
                                                        preview()
                                                    }} />
                                            </Form.Item>
                                        </div>
                                        <Form.Item
                                            style={{
                                                display: 'none'
                                            }}
                                            // label="副标题"
                                            name="loginpageId"
                                            rules={[{ required: false, message: 'id' }]}
                                        >
                                            <Input placeholder="loginpageid"
                                                style={{
                                                    width: '375px',
                                                    height: '38px',
                                                    background: ' #F8F8F8'
                                                }}
                                            />
                                        </Form.Item>
                                        <Form.Item>
                                            {/* <Space.Compact> */}
                                            <div style={{ display: 'flex' }}>
                                                <div className='setloginpage-formitem'>
                                                    <div className='setloginpage-formitem-title'>版权时间:</div>

                                                    <Form.Item
                                                        // label="版权时间"
                                                        name="copyrightDate"
                                                        rules={[{ required: false, message: '请输入版权时间' }]}
                                                        style={{ display: 'inline-block', marginBottom: '0' }}
                                                    >
                                                        <Input placeholder="请输入版权时间"
                                                            style={{
                                                                width: '142px',
                                                                height: '38px',
                                                                background: '#F8F8F8'
                                                            }}
                                                            onChange={() => {
                                                                preview()
                                                            }} />
                                                    </Form.Item>
                                                </div>
                                                <div className='setloginpage-formitem'>
                                                    <div className='setloginpage-formitem-title right-formitem-title'>版权人:</div>


                                                    <Form.Item
                                                        // label="版权人"
                                                        name="copyrightOwner"
                                                        rules={[{ required: false, message: '请输入版权人' }]}
                                                        style={{ display: 'inline-block', marginBottom: '0' }}>
                                                        <Input placeholder="请输入版权人"
                                                            style={{
                                                                width: '142px',
                                                                height: '38px',
                                                                background: '#F8F8F8'
                                                            }}
                                                            onChange={() => {
                                                                preview()
                                                            }} />
                                                    </Form.Item>
                                                </div>
                                            </div>
                                            {/* </Space.Compact> */}
                                        </Form.Item>
                                        <div className='setloginpage-formitem'>
                                            <div className='setloginpage-formitem-title'>Logo:</div>

                                            <Form.Item
                                            // label="LOGO"
                                            >

                                                <Upload
                                                    name="image"
                                                    listType="picture"
                                                    maxCount={1}
                                                    defaultFileList={logoImgArray}
                                                    action={uploadImageUrl()}
                                                    headers={{ 'X-USER-ID': DevUserId }}
                                                    beforeUpload={beforeUpload}
                                                    onChange={(info) => {
                                                        if (info.file.status === 'uploading') {
                                                            setLoading(true);
                                                            return;
                                                        }
                                                        if (info.file.status === 'done') {
                                                            setLoading(false);
                                                            const fileId = info.file.response.data.fileId;
                                                            const url = downloadUrl(fileId);
                                                            logoImgArray.splice(0, 1, {
                                                                uid: info.file.response.data.fileId,
                                                                name: 'logo.png',
                                                                status: 'done',
                                                                url: url,
                                                                thumbUrl: url,
                                                            })
                                                            setLogoImgArray([
                                                                ...logoImgArray
                                                            ])
                                                            preview()
                                                            return;
                                                        }
                                                    }}
                                                    onRemove={() => {
                                                        logoImgArray.splice(0)
                                                        setLogoImgArray([
                                                            ...logoImgArray
                                                        ])
                                                        preview()
                                                    }}
                                                >
                                                    <Button size="small" type="primary"
                                                        style={{
                                                            width: '81px',
                                                            height: '28px',
                                                            background: '#135BD4',
                                                            color: 'white'
                                                        }}
                                                        disabled={logoImgArray.length > 0}>上传</Button>
                                                </Upload>
                                            </Form.Item>
                                        </div>
                                        <div className='setloginpage-formitem'>
                                            <div className='setloginpage-formitem-title'>背景:</div>

                                            <Form.Item >
                                                <Upload
                                                    style={{
                                                        // background:'red'
                                                    }}
                                                    name="image"
                                                    listType="picture"
                                                    maxCount={1}
                                                    defaultFileList={bgImgArray}
                                                    action={uploadImageUrl()}
                                                    headers={{ 'X-USER-ID': DevUserId }}
                                                    beforeUpload={beforeUpload}
                                                    onChange={(info) => {
                                                        if (info.file.status === 'uploading') {
                                                            setLoading(true);
                                                            return;
                                                        }
                                                        if (info.file.status === 'done') {
                                                            setLoading(false);
                                                            const fileId = info.file.response.data.fileId;
                                                            const url = downloadUrl(fileId);
                                                            bgImgArray.splice(0, 1, {
                                                                uid: info.file.response.data.fileId,
                                                                name: 'bg.png',
                                                                status: 'done',
                                                                url: url,
                                                                thumbUrl: url,
                                                            })
                                                            setBgImgArray([
                                                                ...bgImgArray
                                                            ])
                                                            preview()
                                                            return;
                                                        }
                                                    }}
                                                    onRemove={() => {
                                                        bgImgArray.splice(0)
                                                        setBgImgArray([
                                                            ...bgImgArray
                                                        ])
                                                        preview()
                                                    }}
                                                >
                                                    <Button size="small" type="primary"
                                                        style={{
                                                            width: '81px',
                                                            height: '28px',
                                                            background: '#135BD4',
                                                            color: 'white'
                                                        }}
                                                        disabled={bgImgArray.length > 0}>上传</Button>
                                                </Upload>
                                            </Form.Item>
                                        </div>
                                        <div className='username-uerpassword'>
                                            <div className='setloginpage-formitem' >
                                                <div className='setloginpage-formitem-title'>用户名:</div>

                                                <Form.Item
                                                    // label="用户名"
                                                    name="adminUsername"
                                                    rules={[{ required: true, message: '请输入用户名' }]}

                                                >
                                                    <Input placeholder="请输入用户名"
                                                        style={{
                                                            width: '330px',
                                                            height: '34px',
                                                            background: ' #FFFFFF'
                                                        }} />
                                                </Form.Item>
                                            </div>
                                            <div className='setloginpage-formitem' style={{ marginTop: '-10px' }}>
                                                <div className='setloginpage-formitem-title'>密码:</div>

                                                <Form.Item
                                                    // label="密码"
                                                    name="adminPassword"
                                                    rules={[{ required: true, message: '请输入密码' }]}

                                                >
                                                    <Input placeholder="请输入密码"
                                                        style={{
                                                            width: '330px',
                                                            height: '34px',
                                                            background: ' #FFFFFF'
                                                        }} />
                                                </Form.Item>
                                            </div>

                                        </div>

                                        {/* <Form.Item wrapperCol={{ span: 24 }}>
                                        <div style={{ paddingTop: '15px' }}>
                                            <Flex align="center" justify="center" gap="large">
                                                <Button type="primary"
                                                    htmlType="submit"
                                                    style={{ backgroundColor: 'var(--color-primary)' }}>
                                                    保存
                                                </Button>
                                                <Button type="default" htmlType="button" onClick={() => {
                                                    nav(-1);
                                                }}>
                                                    返回
                                                </Button>
                                            </Flex>
                                        </div>
                                    </Form.Item> */}



                                    </Form>
                                    <div className='select-loginPage'>
                                        <div className='select-loginPage-title'>选择登陆页面</div>
                                        <div className='select-loginPage-imgs'>
                                            {
                                                loginpageArray.map((item) => {
                                                    return (
                                                        // <div>
                                                        //     <img src={downloadUrl(item.bgImgs)} alt="" />
                                                        // </div>
                                                        <CardImgSelect
                                                            key={item.loginpageId}
                                                            id={item.loginpageId}
                                                            title={item.mainTitle}
                                                            imgs={item.previewImgs}
                                                            selected={item.loginpageId == selectedLoginpageId}
                                                            handleClick={() => {
                                                                setSelectedLoginpageId(item.loginpageId);
                                                                // loginpageArray.forEach(loginpage => {
                                                                //     loginpage.selected = loginpage.id == item.id;
                                                                // })
                                                                // setLoginpageArray([
                                                                //     ...loginpageArray
                                                                // ])
                                                                console.log('选择的id', item.loginpageId);
                                                                form.setFieldValue('loginpageId', item.loginpageId);
                                                                preview()

                                                            }}
                                                        />
                                                    )
                                                })
                                            }
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </Col>

                    </Row>
                </div>
            </div>
            <Modal title="提示"
                okText="确定"
                cancelText="取消"
                open={isEditModalOpen}
                onOk={() => {
                    // console.log('发起球球的id',selectedLoginpageId);

                    setIsEditModalOpen(false);
                    console.log(logoImgArray)
                    put({
                        messageApi,
                        url: `/api/proj/update/config-loginpage/${props.projId}`,
                        body: {
                            logo: logoImgArray.length > 0 ? logoImgArray[0].uid : '',
                            bgImgs: bgImgArray.length > 0 ? bgImgArray[0].uid : '',
                            subTitle: form.getFieldValue('subTitle'),
                            copyrightOwner: form.getFieldValue('copyrightOwner'),
                            copyrightDate: form.getFieldValue('copyrightDate'),
                            adminUsername: form.getFieldValue('adminUsername'),
                            adminPassword: form.getFieldValue('adminPassword'),
                            loginpageId: form.getFieldValue('loginpageId')
                        },
                        onBefore() {
                            setLoading(true);
                        },
                        onSuccess() {
                            messageApi.open({
                                type: 'success',
                                content: '编辑成功'
                            })
                            // props.closeModal()
                            // props.closeModal()
                            setTimeout(() => {
                                props.closeModal()
                                // window.location.reload(); // 刷新页面
                            }, 500);

                        },
                        onFinally() {
                            setLoading(false);
                        }
                    })
                }}
                onCancel={() => {
                    setIsEditModalOpen(false);
                }}>
                <div>确定提交吗？</div>
            </Modal>
            <Spin tip="正在提交..." spinning={loading} fullscreen />
        </>
    )

}