import './proj-edit-step.css';
import {
    Breadcrumb,
    Col,
    Flex,
    GetProp,
    Input,
    message,
    Modal,
    Row,
    Space,
    Spin,
    Upload,
    UploadFile,
    UploadProps
} from "antd";
import {Link, useNavigate, useParams} from "react-router-dom";
import {useEffect, useState} from "react";
import {DevUserId, get, downloadUrl, put, uploadImageUrl, post} from "../../../util/AjaxUtils.ts";
import {Button, Form} from 'antd';

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() {
    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 - 210;

    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',
            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(() => {
        get<any>({
            messageApi,
            url: `/api/proj/get/config-loginpage/${pathParams.projId}`,
            onSuccess({data}) {
                form.setFieldValue('loginpageId', 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);
                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
                    ])
                }
                preview();
            }
        })

    }, [])

    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`}}>
                <div className="loginpage-body">
                    <Row gutter={15}>
                        <Col span={6}>
                            <Form
                                name="basic"
                                form={form}
                                layout="vertical"
                                labelCol={{span: 8}}
                                wrapperCol={{span: 24}}
                                onFinish={() => {
                                    setIsEditModalOpen(true);
                                }}
                                autoComplete="off"
                            >
                                <Form.Item label="副标题"
                                           name="subTitle"
                                           rules={[{required: false, message: '请输入副标题'}]}>
                                    <Input placeholder="请输入副标题" onChange={() => {
                                        preview()
                                    }}/>
                                </Form.Item>
                                <Form.Item>
                                    <Space.Compact>
                                        <Form.Item label="版权时间"
                                                   name="copyrightDate"
                                                   rules={[{required: false, message: '请输入版权时间'}]}
                                                   style={{display: 'inline-block', marginBottom: '0'}}>
                                            <Input placeholder="请输入版权时间" onChange={() => {
                                                preview()
                                            }}/>
                                        </Form.Item>
                                        <Form.Item label="版权人"
                                                   name="copyrightOwner"
                                                   rules={[{required: false, message: '请输入版权人'}]}
                                                   style={{display: 'inline-block', marginBottom: '0'}}>
                                            <Input placeholder="请输入版权人" onChange={() => {
                                                preview()
                                            }}/>
                                        </Form.Item>
                                    </Space.Compact>
                                </Form.Item>
                                <Form.Item>
                                    <Space.Compact>
                                        <Form.Item label="用户名"
                                                   name="adminUsername"
                                                   rules={[{required: true, message: '请输入用户名'}]}
                                                   style={{display: 'inline-block', marginBottom: '0'}}>
                                            <Input placeholder="请输入用户名"/>
                                        </Form.Item>
                                        <Form.Item label="密码"
                                                   name="adminPassword"
                                                   rules={[{required: true, message: '请输入密码'}]}
                                                   style={{display: 'inline-block', marginBottom: '0'}}>
                                            <Input placeholder="请输入密码"/>
                                        </Form.Item>
                                    </Space.Compact>
                                </Form.Item>
                                <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={{backgroundColor: 'var(--color-primary)'}}
                                                disabled={logoImgArray.length > 0}>上传</Button>
                                    </Upload>
                                </Form.Item>
                                <Form.Item label="背景">
                                    <Upload
                                        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={{backgroundColor: 'var(--color-primary)'}}
                                                disabled={bgImgArray.length > 0}>上传</Button>
                                    </Upload>
                                </Form.Item>

                                <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>
                        </Col>
                        <Col span={18}>
                            <iframe srcDoc={iframeSrcDoc} style={{
                                width: '100%',
                                height: `${height - 10}px`,
                                border: '1px solid var(--color-border)'
                            }}/>
                        </Col>
                    </Row>
                </div>
            </div>
            <Modal title="提示"
                   okText="确定"
                   cancelText="取消"
                   open={isEditModalOpen}
                   onOk={() => {
                       setIsEditModalOpen(false);
                       console.log(logoImgArray)
                       put({
                           messageApi,
                           url: `/api/proj/update/config-loginpage/${pathParams.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'),
                           },
                           onBefore() {
                               setLoading(true);
                           },
                           onSuccess() {
                               messageApi.open({
                                   type: 'success',
                                   content: '编辑成功'
                               })
                           },
                           onFinally() {
                               setLoading(false);
                           }
                       })
                   }}
                   onCancel={() => {
                       setIsEditModalOpen(false);
                   }}>
                <div>确定提交吗？</div>
            </Modal>
            <Spin tip="正在提交..." spinning={loading} fullscreen/>
        </>
    )

}