import styles from '@/components/UpdateModal/index.module.scss'
import ImageUrl from '@/utils/package/imageUrl';
import { getUpdateUrl } from '@/utils/package/public';
import { Button, Flex, Modal, Progress } from 'antd';
import { forwardRef, useImperativeHandle, useState } from "react";

const UpdateModal = forwardRef((props: any, ref: any) => {
    useImperativeHandle(ref, () => ({
        changeModal: (data: any) => {
            let dataJson = JSON.parse(data)
            getContent()
            if (dataJson.type === '0') { // 打开弹窗
                setIsUpdateModal(true)
            } else if (dataJson.type === '1') { // 下载中 返回进度值
                setProgress(dataJson.value.toFixed(2))
            } else if (dataJson.type === '2') { // 下载完成
                setProgress(100)
            }
        }
    }))
    const [isUpdateModal, setIsUpdateModal] = useState(false);
    const [progress, setProgress] = useState(0); // 下载进度值
    const [updateContent, setUpdateContent] = useState('') // 版本更新内容

    function getContent() {
        fetch(`${getUpdateUrl(import.meta.env.VITE_ENV)}/update.txt?t=${+new Date()}`) // 配置服务器地址
            .then(async response => {
                if (response.status === 200) {
                    return setUpdateContent(await response.text())
                }
                throw new Error('Network response was not ok.');
            })
            .then(textContent => {
            })
            .catch(error => {
            });
    }

    function closeModal() {
        if (progress != 100) {
            window.electron.onDownload('0') // 取消下载
        }
        setIsUpdateModal(false)
    }

    return (
        <>
            <Modal
                title=""
                open={isUpdateModal}
                footer={null}
                // onCancel={() => closeModal()}
                centered
                width={'400px'}
                className='modal-padding'
                maskClosable={false}
                closeIcon={false}
            >
                <div className={styles.isUpdateModal} style={{ backgroundImage: `url(${ImageUrl.icon7})` }}>
                    <div className={styles.remarks} dangerouslySetInnerHTML={{ __html: updateContent }}>
                    </div>
                    {
                        !progress ?
                            <div className={styles.buttons}>
                                <Button type="primary"
                                    onClick={() => window.electron.onDownload('1')}
                                    style={{ width: '100%', height: '40px', marginBottom: '10px' }}
                                    className={`m-ant-btn`}
                                >立即更新</Button>
                                {import.meta.env.VITE_ENV === "development" ? <div className={styles.button2} onClick={() => setIsUpdateModal(false)}>暂不更新</div> : null}
                            </div> : progress < 100 ?
                                <div style={{ margin: '20px 0' }}>
                                    下载进度：{progress}%
                                    <Flex gap="small" vertical>
                                        <Progress percent={progress} showInfo={false} />
                                    </Flex>
                                </div> :
                                <Button type="primary"
                                    onClick={() => window.electron.onDownload('2')}
                                    style={{ width: '100%', height: '40px', margin: '20px 0' }}
                                    className={`m-ant-btn`}
                                >下载完成，点击安装</Button>
                    }
                </div>
            </Modal>
        </>
    )
})

export default UpdateModal
