import React from 'react'
import { Layout, Button, Icon, Input, Menu, Dropdown, Card, Col, Row } from 'antd'
import { connect } from 'dva'
import { dateFormat } from '../../utils/baseUtils'
import Ellipsis from 'ant-design-pro/lib/Ellipsis'
import DistributeBox from './distributeBox'
import TransferBox from '../common/selectUserBox/selectUserBox';
import 'ant-design-pro/dist/ant-design-pro.css'
import Thumbnail from './thumbnail'
import './list.less'
import DeleteBox from '../common/deleteBox/deleteBox'
const { Content } = Layout
const { Search } = Input
const CardGrid = Card.Grid


class DashboardList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedRecord: null,
            visibleChooseDataSourceBox: false,
            visibleDistributeBox: false,
            visibleTransferBox: false,
            visibleGroupMenu: false, // 显示分组菜单
            visibleDeleteBox: false
        }
    }

    componentDidMount() {
        const { dispatch } = this.props;
        this.setBodyWidth();
        dispatch({ type: 'dashboard/fetchList' });
    }

    /**
     * 设置卡片容器宽度 = 每行最大卡片数量 * 卡片宽度
     */
    setBodyWidth() {
        const chartBody = document.getElementsByClassName('dashboard-body')[0]; // 卡片容器
        const parent = chartBody.parentNode; // 父级容器
        const pWidth = parent.offsetWidth; // 父级容器宽度
        const pPadding = 10 + 10; // 父级容器左右padding
        const cWidth = 512; // 每个卡片宽度
        const cMargin = 5 + 5; // 每个卡片左右margin
        const pTrueWidth = pWidth - pPadding; // 父容器实际可用宽度
        const cTrueWidth = cWidth + cMargin; // 卡片实际占用宽度
        const count = Math.floor(pTrueWidth/cTrueWidth); // 每行最大卡片数量

        chartBody.style.width = count * cTrueWidth  + 'px';
    }

    generateCard() {
        const { dashboard, dispatch } = this.props;
        const list = dashboard.list;

        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let filterLabel = dashboard.filterLabel.replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1'); // 添加转义符号

        const operationMenu = (
            <Menu className='menu-operation'>
                <Menu.Item onClick={() => {
                    this.setState({visibleDistributeBox: true})
                }}> 
                    <Icon type='share-alt'/>分发
                </Menu.Item>
                <Menu.Divider />
                <Menu.Item
                    onClick={()=>{
                        this.setState({ visibleTransferBox: true})
                    }}
                >
                    <Icon type="swap" />移交
                </Menu.Item>
                <Menu.Item
                    onClick={(e) => {
                        this.setState({ visibleDeleteBox: true})
                    }}
                >
                    <Icon type="delete" />删除
                    
                </Menu.Item>
            </Menu>
        )

        let cards = list.filter(l => {
            let reg = new RegExp('(' + filterLabel + '){1}', 'ig');
            return (l.name || '').search(reg) !== -1 || (l.description || '').search(reg) !== -1;
        }).sort((a, b) => {
            return new Date(b.createTime) - new Date(a.createTime)
        }).map( (l, i) => (
            <CardGrid className='dashboard-card' key={i} onClick={() => {
                this.setState({ selectedRecord: l })
            }}>
                <Card
                    title={
                        <Row type='flex' justify='space-between'>
                            <Col span={21} style={{ overflow: 'hidden', textOverflow: 'ellipsis' }} >
                                { filterLabel ?
                                    ((l.name || '').split(new RegExp(`(${filterLabel})`, 'i')).map((fragment, i) => {
                                        return (
                                            fragment.toLowerCase().replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') === filterLabel.toLowerCase() ?
                                            <span key={i} style={{fontWeight: 'bold', color: 'red'}} className="highlight">{fragment}</span> :
                                            fragment
                                        )
                                    }
                                    )) : l.name
                                }
                            </Col>
                            <Col style={{ textAlign: 'right' }} span={3} >
                                <Icon type='star-o'/>
                            </Col>
                        </Row>
                    }
                    cover={
                        <Col className='cover-body'>
                            <Row className='thumb' onClick={() => {
                                dispatch({ type: 'dashboardDesigner/reset' });
                                dispatch({ type: 'main/redirect', path: '/dashboard/' + l.code });
                            }}>
                                <Thumbnail type={l.type} code={l.code} option={l.chartOption} thumbnail={l.thumbnail}/>
                            </Row>
                            <Row className='desc'>
                                <Ellipsis tooltip={l.description.length > 16} lines={2}>{
                                    <span>
                                    { filterLabel ?
                                        ((l.description || '').split(new RegExp(`(${filterLabel})`, 'i')).map((fragment, i) => {
                                            return (
                                                fragment.toLowerCase().replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') === filterLabel.toLowerCase() ?
                                                <span key={i} style={{fontWeight: 'bold', color: 'red'}} className="highlight">{fragment}</span> :
                                                fragment
                                            )
                                        }
                                        )) : l.description
                                    }
                                </span>
                                }</Ellipsis>
                            </Row>
                            <Row className='footer' type='flex' justify='end' align='bottom'>
                                <Col style={{ textAlign: 'left' }} span={22}>
                                    <Row>{l.creator} {dateFormat(l.createTime, 'yyyy-MM-dd')}</Row>
                                </Col>
                                <Col span={2} style={{ textAlign: 'right' }}>
                                    <Dropdown overlay={operationMenu} trigger={['click']}>
                                        <Icon type="ellipsis" />
                                    </Dropdown>
                                </Col>
                            </Row>
                        </Col>
                    }
                >
                </Card>
            </CardGrid>
        ));
        if(cards.length === 0) {
            cards = <div style={{ padding: '7px', textAlign: 'center', fontSize: '14px', color: 'rgba(0, 0, 0, 0.45)' }}>暂无数据</div>
        }
        return cards;
    }

    handleVisibleChange = (flag) => {
        this.setState({ visibleGroupMenu: flag });
    }

    hideGroupMenu = () => {
        this.setState({
            visibleGrouMenu: false
        });
    }

    render() {
        const { dispatch, dashboard } = this.props;
        const { visibleDistributeBox, visibleTransferBox, visibleDeleteBox, selectedRecord } = this.state
        return (
            <Layout className='dashboard-list'>
                <Content>
                    <Card title={
                        <Row className='tools' type='flex' justify='space-between'>
                            <Col style={{ display: 'flex' }}>
                            </Col>
                            <Col className='search'>
                                <Col style={{ padding: '0 5px' }}>
                                    <Search
                                        placeholder="请输入关键字"
                                        value={dashboard.filterLabel}
                                        onChange={e => {
                                            dispatch({ type: 'dashboard/setFilterLabel', label: e.target.value });
                                        }}
                                    />
                                </Col>
                                <Col >
                                    <Button onClick={() => {
                                        dispatch({ type: 'dashboard/remoteQucikAdd' });
                                    }}>
                                        <Icon type="layout" />创建看板
                                    </Button>
                                </Col>
                            </Col>
                        </Row>
                    }>
                        <div className='dashboard-body'>
                            { this.generateCard() }
                        </div>
                    </Card>
                </Content>
                <DistributeBox
                    visibleDistributeBox={visibleDistributeBox}
                    selectedRecord={this.state.selectedRecord}
                    hideBox={() => {
                        this.setState({
                            visibleDistributeBox: false
                        });
                    }} />
                <TransferBox
                    visibleBox={visibleTransferBox}
                    title='选择移交对象'
                    onOk={(user) => {
                        dispatch({ type: 'dashboard/transfer', dashboardCode: this.state.selectedRecord.code, userCode: user.code });
                    }}
                    hideBox={() => {
                        this.setState({
                            visibleTransferBox: false
                        })
                    }}
                />
                <DeleteBox
                    visibleDeleteBox={visibleDeleteBox}
                    type='dashboard'
                    hideBox={() => {
                        this.setState({
                            visibleDeleteBox: false
                        })
                    }}
                    selectedRecord={selectedRecord}
                    onOk={() => {
                        dispatch({ type: 'dashboard/remoteDelete', code: this.state.selectedRecord.code })
                    }} />
            </Layout>
        )
    }
}


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

export default connect(mapStateToProps)(DashboardList)