import React from 'react'
import { connect } from 'dva'
import ReactGridLayout from 'react-grid-layout'
import '../../models/dashboard'
import '../../../node_modules/react-grid-layout/css/styles.css'
import '../../../node_modules/react-resizable/css/styles.css'
import '../../models/dashboardDesigner'
import { Icon, Menu, Layout, Switch, Row, Col, Button, Dropdown } from 'antd'
import ElementConfig from './elementConfig'
import './layout.less'
import Element from './element'
import '../../models/dataConnect'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'


class DashboardDesigner extends React.Component {

    constructor(props) {
        super(props);
        var layout = this.loadLayout()
        this.state = {
            editMode: true,
            operation: 'create',
            visibleBox: false,
            layout: layout,
        };
    }

    saveToPNG = (element) => {
        html2canvas(element).then(function(canvas) {
                var pageData = canvas.toDataURL('image/png', 1.0);

                //方向默认竖直，尺寸ponits，格式a4[595.28,841.89]
                var pdf = new jsPDF('', 'pt', 'a4');

                //addImage后两个参数控制添加图片的尺寸，此处将页面高度按照a4纸宽高比列进行压缩
                pdf.addImage(pageData, 'PNG', 0, 0, 595.28, 592.28/canvas.width * canvas.height );

                pdf.save('stone.pdf');
        });
    }


    showElementConfigBox = (o) => {
        this.setState({
            operation: o,
            visibleBox: true
        });
    }

    hideElementConfigBox = (o) => {
        this.setState({
            visibleBox: false
        });
    }

    enableEditMode = (o) => {
        this.setState({
            editMode:true
        })
    }

    disableEditMode = (o) => {
        this.setState({
            editMode:false
        })
    }

    generateElementConfigMenu = (key) => {
        const {dashboardDesigner, dispatch} = this.props;
        return (
            <Menu>
                <Menu.Item
                    onClick={()=> {
                        let selectedElement = dashboardDesigner.elementList.find((i) => {return i.key === key});
                        dispatch({ type: 'dashboardDesigner/resetConfigBoxForm'});
                        dispatch({ type: 'dashboardDesigner/loadConfigBoxForm', element: selectedElement});
                        this.showElementConfigBox('modify')
                }}>
                    <span>属性设置</span>
                </Menu.Item>
            </Menu>
        
        
        )
    }
    generateElement() {    
        const elementList = this.props.dashboardDesigner.elementList;
        const editMode = this.state.editMode
        let IconStyle={
            display: editMode? 'inline-block':'none', 
            position: 'absolute',
            right: '3px',
            top: '3px'
        };

        
        return elementList.map ((item) => {
            if (item.type === 'chart') {
                return (
                    <div 
                        key={item.key.toString()}
                        className={`grid-item${this.state.editMode ?' grid-item-edit': ''}`} 
                    >
                        <Element type="chart" content={item.content} itemKey={item.key}/>  
                        <Dropdown overlay={this.generateElementConfigMenu(item.key)} trigger={['click']}>
                            <Icon type="setting" style={IconStyle} />
                        </Dropdown>
                    </div>
                )
            }else if (item.type === "simple") {
                return (
                    <div 
                        key={item.key.toString()}
                        className={`grid-item${this.state.editMode ?' grid-item-edit': ''}`} 
                    >
                        <Element type="simple" content={item.content} itemKey={item.key}/>
                        <Dropdown overlay={this.generateElementConfigMenu(item.key)} trigger={['click']}>
                            <Icon type="setting" style={IconStyle} />
                        </Dropdown>
                    </div>
                )
            }
            else{
                return (<div key="3" >I'm not typed!</div>)
            
            }
        })
    }

    loadLayout() {
        const layout = this.props.dashboardDesigner.layout;

        return layout.map((item) => {
            let { key, x, y, w, h, minW, maxW, minH, maxH } = item;
            return { i: key.toString(), x: x, y: y, w: w, h: h, minW: minW, maxW: maxW, minH: minH, maxH: maxH}
        })
    }

    render() {
        const { operation, visibleBox, editMode } = this.state;
        
        return (
            <Layout>
                <Row 
                    type='flex' 
                    justify ='space-between'
                    className='dashboard-header'
                >
                        <Col className='dashboard-header-title'                        >
                            <div>{this.props.dashboardDesigner.basicConfig.title}</div>
                        </Col>
                        <Col className='dashboard-toolbar'>
                            <div>
                                <Button onClick={() => {
                                    this.showElementConfigBox("create")
                                }}>
                                    添加元素
                                </Button>
                                <Button onClick={() => {
                                    this.saveToPNG(document.body)
                                }}>
                                    保存为PNG
                                </Button>
                                <span>编辑模式</span>
                                <Switch 
                                    checkedChildren="开" 
                                    unCheckedChildren="关" 
                                    checked= {editMode}
                                    
                                />
                            </div>
                        </Col>
                </Row>
                <ReactGridLayout 
                    className={`grid-layout${this.state.editMode ?' grid-layout-edit': ''}`}  
                    cols={12}
                    rowHeight={30} 
                    width={1200}  //TODO: 宽度响应式设计？
                    isDraggable={editMode}
                    isResizable={editMode}
                    compactType="horizontal"
                >
                {this.generateElement()}
                
                </ReactGridLayout>
                <ElementConfig 
                    operation={operation} 
                    visibleBox={visibleBox}
                    hideElementConfigBox={this.hideElementConfigBox} />
            </Layout>
        )
    }

}

function mapStateToProps({present: {dashboardDesigner}}) {
    return { dashboardDesigner }
}

export default connect(mapStateToProps)(DashboardDesigner)