/*
 * @Author: chenxinyu
 * @Date: 2021-03-24 21:47:52
 * @LastEditors: your name
 * @LastEditTime: 2022-01-15 22:13:58
 * @Description: 全屏对话框组件
 * @FilePath: \react-components\components\vtx-modal\index.jsx
 */
import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import useUpdateEffect from 'ahooks/es/useUpdateEffect';
import useSetState from 'ahooks/es/useSetState';
import CloseOutlined from '@ant-design/icons/CloseOutlined';
import FullscreenExitOutlined from '@ant-design/icons/FullscreenExitOutlined';
import FullscreenOutlined from '@ant-design/icons/FullscreenOutlined';
import classnames from 'classnames';
import { Modal } from 'antd';
import Title from './Title';
import { Tabs } from 'antd';
import './style';

const { TabPane } = Tabs;

// 对话框位置初始参数
const initDragArg = {
    init_x: 0,
    init_y: 0,
    x_move: 0,
    y_move: 0,
    documentMouseMove: null,
    documentMouseUp: null,
};

// 全屏参数
const initFullScreen = {
    isFull: true,
    className: 'vtx-modal-maxClass',
};

const VtxFullScreenModal = props => {
    const [fullScreen, setFullScreen] = useSetState(initFullScreen); // 是否是全屏状态
    const [dragArg, setDragArg] = useSetState(initDragArg); // 拖动配置
    const classId = useRef(new Date().getTime() + Math.random());

    let {
        wrapClassName = '',
        closable = true, // 是否显示右上角关闭按钮
        title = '', // 对话框title
        maximize = true, // 是否显示对话框全屏按钮
        onModalResize, // 对话框全屏回调
        moveable = true, // 对话框是否允许拖动
        tabs = [],
    } = props;

    // 监听对话框大小变化回调(忽略首次执行)
    useUpdateEffect(() => {
        const timer = setTimeout(() => {
            if (onModalResize && typeof onModalResize === 'function') {
                const el = document.getElementsByClassName('ant-modal-body')[0];
                const option = {
                    height: window.getComputedStyle(el).height,
                    isFull: fullScreen.isFull,
                };
                onModalResize(option);
            }
        }, 100);
        return () => clearTimeout(timer);
    }, [fullScreen.isFull]);

    // 拖拽
    useEffect(() => {
        if (props.visible && moveable) {
            const timer = setTimeout(() => {
                const modalHead = document
                    .getElementsByClassName(classId.current)?.[0]
                    ?.getElementsByClassName('ant-modal-header')?.[0];
                if (modalHead) {
                    modalHead.style.cursor = 'move';
                    modalHead.onmousedown = startDrag;
                }
            }, 200);
            return () => clearTimeout(timer);
        }
    });

    const startDrag = e => {
        e.preventDefault();
        // 全屏模式下禁止拖拽
        if (!fullScreen.isFull) {
            setDragArg({
                documentMouseUp: document.onmouseup,
                documentMouseMove: document.onmousemove,
                init_x: e.clientX - dragArg.x_move,
                init_y: e.clientY - dragArg.y_move,
            });
            document.onmousemove = e => {
                setDragArg(prev => ({
                    x_move: e.clientX - prev.init_x,
                    y_move: e.clientY - prev.init_y,
                }));
            };
            document.onmouseup = () => {
                document.onmousemove = dragArg.documentMouseMove;
                document.onmouseup = dragArg.documentMouseUp;
            };
        }
    };

    // 关闭对话框，初始化位置
    const onCancel = () => {
        if (props.onCancel && typeof props.onCancel === 'function') {
            props.onCancel();
            // TODO 关闭弹框会闪一下,待解决
            setDragArg(initDragArg);
            setFullScreen(initFullScreen);
        }
    };

    /*
     *重写title，加入对话框全屏功能
     */
    title = (function renderTitle() {
        return (
            <div className="vtx-modal-title" style={{ paddingRight: closable ? '32px' : '0px' }}>
                <div className="vtx-modal-title_name">{title}</div>
                {maximize ? (
                    <div className="vtx-modal-maximizeIcon">
                        <p
                            onClick={() => {
                                let fullScreenClass = '';
                                if (!fullScreen.isFull) {
                                    fullScreenClass = 'vtx-modal-maxClass';
                                }
                                setFullScreen({
                                    isFull: !fullScreen.isFull,
                                    className: fullScreenClass,
                                });
                            }}
                        >
                            {fullScreen.isFull ? (
                                <FullscreenExitOutlined />
                            ) : (
                                <FullscreenOutlined />
                            )}
                        </p>
                    </div>
                ) : null}
                {closable ? (
                    <div className="vtx-modal-close">
                        <p onClick={onCancel}>
                            {/* <Icon type="close" /> */}
                            <CloseOutlined />
                        </p>
                    </div>
                ) : (
                    ''
                )}
            </div>
        );
    })();

    let bodyStyle = {
        ...props.bodyStyle,
    };

    /* 限制最大高度 */
    if (!fullScreen.isFull) {
        bodyStyle = {
            maxHeight: `${window.innerHeight * 0.7}px`,
            ...bodyStyle,
        };
    }

    const transformStyle = {
        transform: `translate(${dragArg.x_move}px,${dragArg.y_move}px)`,
    };

    const newProps = {
        maskClosable: false,
        destroyOnClose: true,
        width: 700,
        ...props,
        closable: false,
        title,
        wrapClassName: classnames(
            'vtx-modal',
            wrapClassName,
            fullScreen.className,
            classId.current,
        ),
        bodyStyle,
        onCancel,
        style: {
            ...props.style,
            ...(fullScreen.isFull ? {} : transformStyle),
        },
    };

    return (
        <Modal {...newProps}>
            {tabs.length === 0 ? (
                props.children
            ) : (
                <Tabs defaultActiveKey={1}>
                    {tabs.map(tab => (
                        <TabPane tab={tab.value} key={tab.value}>
                            {tab.content}
                        </TabPane>
                    ))}
                </Tabs>
            )}
        </Modal>
    );
};

VtxFullScreenModal.info = Modal.info;
VtxFullScreenModal.success = Modal.success;
VtxFullScreenModal.error = Modal.error;
VtxFullScreenModal.warning = Modal.warning;
VtxFullScreenModal.confirm = Modal.confirm;

VtxFullScreenModal.propTypes = {
    visible: PropTypes.bool,
    wrapClassName: PropTypes.string,
    closable: PropTypes.bool,
    title: PropTypes.oneOfType([PropTypes.element, PropTypes.string]),
    maximize: PropTypes.bool,
    onModalResize: PropTypes.func,
    moveable: PropTypes.bool,
    onCancel: PropTypes.func,
    bodyStyle: PropTypes.object,
    style: PropTypes.object,
    tabs: PropTypes.array,
    children: PropTypes.node,
};

VtxFullScreenModal.Title = Title;

const size = {
    xsmall: 392,
    small: 500,
    middle: 744,
    large: 1096,
};

VtxFullScreenModal.size = size;

export default VtxFullScreenModal;
