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

    Col,
    // Flex,
    GetProp,
    Input,
    message,
    Modal,
    Row,
    // Space,
    Spin,
    Upload,
    UploadFile,
    UploadProps,
    Image,
    Pagination
} from "antd";
import { useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import { DevUserId, get, downloadUrl, put, uploadImageUrl, post, Axios } from "../../../util/AjaxUtils.ts";
import { Button, Form } from 'antd';
// 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 [page,setPage] = useState(1)
    const [total ,setTotal] = useState(0)
    const [selectedLoginpageId, setSelectedLoginpageId] = useState('');
    // 选择页面id和img(初始化用)
    const [modalId,setModalId] = useState('')
    const [modalImg,setModalImg] = useState('')
    const [selectImgs, setSelectImgs] = useState('')
    const [projId] = useState(pathParams.projId ? pathParams.projId : props.projId)
    // 选择登陆页面弹窗
    const [selectImgModal,setSelectImgModal] = useState(false)
    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/${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);
            }
        })
    }
    const getlistLoginpage = (page:number) => {
        get<any>({
            messageApi,
            url: '/api/loginpage/listpage',
            config: {
                params: {
                    page: page,
                    rows: 10
                }
            },
            onSuccess({ data }) {
                console.log('登录页图片列表', data);
                setloginpageArray(data.rows)
                // setDefaultId(data[0].loginpageId)
                // upLoginPage(data[0].loginpageId)
                setTotal(data.total)


                // 当有返回id时获取图片的previewImgs
                // const newData = data.rows
                // get<any>({
                //     messageApi,
                //     url: `/api/proj/get/config-loginpage/${projId}`,
                //     onSuccess({ data }) {
                //         if (data.loginpageId) {
                        
                //             const imgs = newData.filter((item: { loginpageId: any; }) => item.loginpageId === data.loginpageId)
                         
                //             setSelectImgs(imgs[0].previewImgs)
                   

                //         }

                //     }
                // })
            }
        })
    }
    // 获取默认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);
    //             setSelectImgs(data[0].previewImgs)
    //             setSelectedLoginpageId(data[0].loginpageId);
    //             setModalId(data[0].loginpageId)
    //             // 选择页面id
    //             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(page)
        get<any>({
            messageApi,
            url: `/api/proj/get/config-loginpage/${projId}`,
            onSuccess({ data }) {
                console.log('数据', data);
                // if(data.adminPassword adminUsername)
                form.setFieldValue('adminUsername', data.adminUsername?data.adminUsername:'admin');
                    form.setFieldValue('adminPassword', data.adminPassword?data.adminPassword:'admin');
                // if (data.loginpageId) {
                    form.setFieldValue('loginpageId', data.loginpageId);
                    setSelectedLoginpageId(data.loginpageId);
                    // lyp
                    // const imgs =  loginpageArray.filter(item => item.loginpageId === data.loginpageId)
                    // ?.previewImgs;
                    setSelectImgs(data.loginpagePreviewImgs)

                    setModalId(data.loginpageId)
                    form.setFieldValue('subTitle', data.subTitle);
                    form.setFieldValue('copyrightOwner', data.copyrightOwner);
                    form.setFieldValue('copyrightDate', data.copyrightDate);
                    // form.setFieldValue('adminUsername', data.adminUsername?data.adminUsername:'admin');
                    // form.setFieldValue('adminPassword', data.adminPassword?data.adminPassword:'admin');
                    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: '0', background: '#EFEFEF', boxSizing: 'border-box' }}>
                <div className="loginpage-body" style={{ height: `${height}px`, overflow: 'auto' }}>
                    <Row >

                        <Col span={16}>
                            <div className='loginpage-bodyL' style={{ height: `${height}px`, overflow: 'auto', paddingBottom: '10px', boxSizing: 'border-box' }}>
                                <iframe srcDoc={iframeSrcDoc} style={{
                                    width: 'calc(100% - 2px)',
                                    height: `90%`,
                                    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()
                                            // setTimeout(()=>{
                                            //     window.location.reload()
                                            // },500)

                                        }}>返回</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',background:'white' }}>
                                <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: '375px',
                                                            height: '38px',
                                                            background: ' #F8F8F8'

                                                        }} />
                                                </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: '375px',
                                                            height: '38px',
                                                            background: ' #F8F8F8'

                                                        }} />
                                                </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 (
                                                        <CardImgSelect
                                                            key={item.loginpageId}
                                                            id={item.loginpageId}
                                                            title={item.mainTitle}
                                                            imgs={item.previewImgs}
                                                            selected={item.loginpageId == selectedLoginpageId}
                                                            handleClick={() => {
                                                                setSelectedLoginpageId(item.loginpageId);
                                                                console.log('选择的id', item.loginpageId);
                                                                form.setFieldValue('loginpageId', item.loginpageId);
                                                                preview()

                                                            }}
                                                        />
                                                    )
                                                })
                                            }
                                        </div> */}
                                        <div style={{ fontSize: 16, width: 140,color: '#5C6065 ', }}>选择登陆页面:
                                        <div style={{fontSize:12,color:'#a8a8a8'}}>(点击图片选择背景)</div>
                                        </div>
                                        <div style={{ width: '100%', height: '100%' }} onClick={() => {
                                            // console.log(selectImgs);
                                            setSelectImgModal(true)
                                            // setPage(1)
                                            getlistLoginpage(1)
                                        }}>
                                            {/*  src={`${Axios.defaults?.baseURL}/route/file/v2/download/true/${previewImgs}`} */}

                                            <img src={downloadUrl(selectImgs)} alt="" width={'93%'} height={'97%'} />
                                        </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/${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(() => {
                                // window.location.reload()
                                props.closeModal()
                            }, 500)

                        },
                        onFinally() {
                            setLoading(false);
                        }
                    })
                }}
                onCancel={() => {
                    setIsEditModalOpen(false);
                }}>
                <div>确定提交吗？</div>
            </Modal>
            {/* 选择页面样式弹窗 */}
            <Modal title="选择登录页面"
                okText="确定"
                cancelText="取消"
                destroyOnClose={true}
                open={selectImgModal}
                width={1070}
                style={{ position: 'relative' }}
                onOk={() => {
                   
                    form.setFieldValue('loginpageId', modalId)
                    preview()
                    if(modalImg){
                        setSelectImgs(modalImg)
                        setSelectedLoginpageId(modalId);
                    }
                    setSelectImgModal(false)
                    
                }}
                onCancel={() => {
                    setModalId(selectedLoginpageId)
                    setSelectImgModal(false)

                    
                }}

            >

                <div style={{ height: `${height - 80}px`, overflow: 'auto', display: 'flex', justifyContent: 'flex-start', flexWrap: 'wrap', marginTop: 10, }}>
                    {
                        loginpageArray.map((item) => {
                            const imgSrc = `${Axios.defaults?.baseURL}/route/file/v2/download/true/${item.previewImgs}`;
                            return (
                                <div key={item.loginpageId} className={item.loginpageId == modalId ? 'page-img-select page-img-selected' : 'page-img-select'}
                                    style={{ marginRight: '10px', marginBottom: '10px' }}
                                    onClick={() => {
                                        setModalId(item.loginpageId)
                                        setModalImg(item.previewImgs)
                                    }}
                                >
                                    <div className="page-img" >
                                        <Image
                                            src={imgSrc}
                                            preview={false} width={500} height={300} />
                                    </div>
                                    <div className="page-title">
                                        <div className="checkbox"></div>
                                        {/* <div className="text">{props.title ? props.title : '标题'}</div> */}
                                    </div>
                                </div>
                            )
                        })
                    }

                </div>
                <div className='pagination'>
                    {/* defaultCurrent: 默认当前页数  total:数据总数 defaultPageSize:'页面显示几条'  */}
                    <Pagination defaultCurrent={1} total={total} defaultPageSize={10} onChange={(page) => {
                        console.log(page);
                        // setPage(page)
                        setloginpageArray([])
                        getlistLoginpage(page)
                    }} />
                </div>

            </Modal>
            <Spin tip="正在提交..." spinning={loading} fullscreen />
        </>
    )

}