import React, { Component } from 'react'
import { Layout } from 'antd'
import Swiper, { Mousewheel, Scrollbar } from 'swiper'
import 'swiper/swiper-bundle.css'
import Menu from './menu'
import store from 'store'

Swiper.use([Mousewheel, Scrollbar])

const { getState, subscribe } = store

let timer, swiper

const siderSwiperOptions = {
    direction: 'vertical',
    slidesPerView: 'auto',
    freeMode: true,
    scrollbar: {
        el: '#layout--swiper-scrollbar',
    },
    mousewheel: true,
}

const UpdateSwiper = () => {
    clearTimeout(timer)
    timer = setTimeout(() => {
        // 需要更新两次
        swiper.update()
        swiper.update()
    }, 300)
}

export default class index extends Component {
    state = {
        ...getState('layout'),
    }

    constructor(props) {
        super(props)

        this.unsubscribe = subscribe('layout', state => {
            this.setState(state)
        })
    }

    componentDidMount() {
        swiper = new Swiper('#layout--swiper-container', siderSwiperOptions)

        window.addEventListener('resize', () => {
            UpdateSwiper()
        })
    }

    componentWillUnmount() {
        this.unsubscribe()
    }

    updateSwiper() {
        UpdateSwiper()
    }

    static getDerivedStateFromProps(props, state) {
        UpdateSwiper()
        return null
    }

    render() {
        return (
            <Layout.Sider
                className="yo-layout-sider"
                width="200"
                collapsed={this.state.siderCollapsed || false}
            >
                <div className="yo-sider-nav">
                    <div className="swiper-container" id="layout--swiper-container">
                        <div className="swiper-wrapper">
                            <div className="swiper-slide">
                                <Menu
                                    parent={this}
                                    menuStyle={{ height: '100%', borderRight: 0 }}
                                />
                            </div>
                        </div>
                        <div className="swiper-scrollbar" id="layout--swiper-scrollbar"></div>
                    </div>
                </div>
            </Layout.Sider>
        )
    }
}
