/**
 * 图表列表
 */
import React from 'react'
import { Layout, Button, Icon, Menu, Card, Col, Row, Breadcrumb, Tag, Checkbox } from 'antd'
import { connect } from 'dva'
import ChooseDataSourceBox from './chooseDataSourceBox'
import GroupManagementBox from '../common/groupManageMentBox/box'
import EmptyContent from '../common/emptyContent/index'
import 'ant-design-pro/dist/ant-design-pro.css'
import GroupSelector from '../common/groupSelector/popover'
import ChartCard from './chartCard'
import DistributeBox from './distributeBox'
import TransferBox from '../common/selectUserBox/selectUserBox'
import DeleteBox from '../common/deleteBox/deleteBox'
import { arrayToTree } from '../../utils/baseUtils'
import ListFilter from '../common/listFilter/index'
import Loading from '../common/loading/index'
import CusIcon from '../common/cusIcon/index'
import './list.less'
const { Content } = Layout
const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符

class ChartList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedRecord: null,

            visibleChooseDataSourceBox: false,
            visibleDistributeBox: false,
            visibleTransferBox: false,
            visibleGroupMenu: false, // 显示分组菜单
            visibleDeleteBox: false,
            visibleGroupManageMentBox: false, // 显示分组管理组件
            visibleDataPreviewBox: false,
        }
        this.bodyRef = React.createRef();
    }

    componentDidMount() {
        const { dispatch, chart } = this.props;
        this.setBodyWidth();
        dispatch({ type: 'chart/fetchList' })
        dispatch({ type: 'chart/remoteGroupList' });
        let parent = this.bodyRef.current.parentNode;
        parent.scrollTo && parent.scrollTo(0, chart.listScrollTop);
        window.addEventListener('resize', this.setBodyWidth);
    }

    componentWillUnmount() {
        const { dispatch } = this.props;
        window.removeEventListener('resize', this.setBodyWidth);
        dispatch({ type: 'chart/setFields', fields: [
            { name: 'listScrollTop', value: this.bodyRef.current.parentNode.scrollTop },
        ] });
    }

    /**
     * 设置卡片容器宽度 = 每行最大卡片数量 * 卡片宽度
     */
    setBodyWidth = () => {
        const cardBody = this.bodyRef.current; // 卡片容器
        const parent = cardBody.parentNode; // 父级容器
        const pWidth = parent.offsetWidth; // 父级容器宽度
        const pPadding = 10 + 10; // 父级容器左右padding
        const cWidth = 207; // 每个卡片宽度
        const cMargin = 8 + 8; // 每个卡片左右margin
        const pTrueWidth = pWidth - pPadding; // 父容器实际可用宽度
        const cTrueWidth = cWidth + cMargin; // 卡片实际占用宽度
        const count = Math.ceil(pTrueWidth/cTrueWidth) - 1; // 每行最大卡片数量，考虑到滚动条，减少一个
        const cardBodyWidth = count * cTrueWidth; // 考虑到滚动条，减少一个

        cardBodyWidth > 0 ? cardBody.style.width = cardBodyWidth + 'px' : void(0);
    }

    onFilterAndGroup = cardList => {
        const { chart } = this.props;
        const { filterItem, currentGroup, noGroup } = chart;
        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let filterLabel = chart.filterLabel ? (chart.filterLabel + '').replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') : ''; // 添加转义符号
        let filterReg = new RegExp('(' + filterLabel + '){1}', 'ig');

        let list = cardList.map(l => {
            let visible = false;
            if(filterItem.type === 'date') {
                if(filterLabel===""){
                    if(noGroup) {
                        visible = l.groupCode === '-1';
                    }else {
                        visible = !!currentGroup ? l.groupCode === currentGroup.code : true;
                    }
                }else if(filterLabel.indexOf('#')>-1){
                    let start = filterLabel.split('#')[0]
                    let end = filterLabel.split('#')[1]
                    let nowTime = new Date(l[filterItem.name]).getTime();
                    if(nowTime>=start && nowTime<=end){
                        if(noGroup) {
                            visible = l.groupCode === '-1'
                        }else {
                            visible = !!currentGroup ? l.groupCode === currentGroup.code : true;
                        }
                    }else {
                        visible = false;
                    }
                }else{
                    visible = false;
                }
            }else {
                if((l[filterItem.name] + '').search(filterReg) > -1) {
                    if(noGroup) {
                        visible = l.groupCode === '-1'
                    }else {
                        visible = !!currentGroup ? l.groupCode === currentGroup.code : true;
                    }
                }else {
                    visible = false;
                }
            }
            return { ...l, visible, animated: true }
        })

        return list;
    }

    onSort = (list) => {
        return list.sort((a, b) => {
            return new Date(b.createTime) - new Date(a.createTime)
        })
    }

    onFilter = () => {
        const { list } = this.props.chart;
        return this.onFilterAndGroup(list);
    }

    getParens = (group) => {
        const groupData = this.props.chart.groupList;
        let pgroups = [group];
        let fgroup = groupData.find(g => g.code === group.pcode);
        if(fgroup) {
            pgroups = this.getParens(fgroup).concat(pgroups);
        }
        return pgroups;
    }

    generateGroupTags = () => {
        const { chart, dispatch } = this.props;
        const { currentGroup, noGroup } = chart;
        const pGroups = currentGroup ? [{ code: '-1', label: '全部分组' }].concat(this.getParens(currentGroup)) : [{ code: '-1', label: '全部分组' }];
        return <Breadcrumb className={`group${noGroup ? ' nogroup' : ''}`} separator=">">
            { pGroups.map(g => (
                <Breadcrumb.Item key={g.code}>
                    <Tag color={'blue'} >
                        {g.code === '-1' && <Icon title="分组维护" type="bars" onClick={() => {
                            this.setState({
                                visibleGroupManageMentBox: true
                            });
                        }}/>}
                        <span onClick={() => {
                            let group = chart.groupList.find(group => group.code === g.code);
                            dispatch({ type: 'chart/setCurrentGroup', group: group });
                            this.bodyRef.current.parentNode.scrollTo && this.bodyRef.current.parentNode.scrollTo(0, 0)
                        }}>{g.label}</span>
                        <GroupSelector
                            visible={this.state['visibleGroupSelector' + g.code]}
                            handleVisibleChange={(visible) => {
                                let obj = {};
                                obj['visibleGroupSelector' + g.code] = visible
                                this.setState(obj);
                            }}
                            pGroup={g}
                            groupList={chart.groupList}
                            selectGroup={(group) => {
                                let obj = {};
                                obj['visibleGroupSelector' + g.code] = false;
                                this.setState(obj);
                                dispatch({ type: 'chart/setCurrentGroup', group });
                                this.bodyRef.current.parentNode.scrollTo && this.bodyRef.current.parentNode.scrollTo(0, 0)
                            }}
                        >
                            { arrayToTree(chart.groupList, g.code, 'code', 'pcode', 'children').length > 0 && <Icon style={{ marginLeft: '4px', fontSize: '12px' }} type="caret-down" />}
                        </GroupSelector>
                    </Tag>
                </Breadcrumb.Item>
            )) }
        </Breadcrumb>
    }

    generateOperationMenu = () => {
        const { main, chart, dispatch } = this.props;
        const { currentUser } = main;
        const { selectedRecord } = this.state;
        const treeData = arrayToTree(chart.groupList, '-1', 'code', 'pcode', 'children');
        
        return (
            <Menu className='menu-operation'>
                <Menu.Item disabled>
                    <Icon type="link" />分享
                </Menu.Item>
                {/* {selectedRecord && (currentUser.code === selectedRecord.creatorCode || currentUser.role === 'superAdmin') && <Menu.Item onClick={() => {
                    const { selectedRecord } = this.state;
                    // const selectedChartDataSourceCode = selectedRecord ? selectedRecord.code : '';
                    const selectedChartCode = selectedRecord ? selectedRecord.code : '';
                    dispatch({ type: 'chartPolicy/fetchList', chartCode: selectedChartCode });
                    dispatch({ type: 'chartPolicy/remoteColumnData', chartCode: selectedChartCode });
                    // dispatch({ type: 'chartDesigner/remoteDataColumn', code:  });
                    this.setState({visibleDistributeBox: true})
                }}> 
                    <Icon type='share-alt'/>分发
                </Menu.Item>} */}
                { selectedRecord && (currentUser.code === selectedRecord.creatorCode || currentUser.role === 'superAdmin') && <Menu.SubMenu className='setgroupmenu' title={<div><Icon style={{ marginRight: '6px' }} type='profile' />移动到</div>}>
                    {[<Menu.Item key='-1' className={selectedRecord.groupCode === '-1' ? 'current' : ''} onClick={() => {
                        dispatch({ type: 'chart/remoteSetGroup', chart: selectedRecord, group: { code: '-1'} });
                    }}>
                        未分组
                    </Menu.Item>].concat(this.createGroupMenu(treeData))}
                </Menu.SubMenu>}
                <Menu.Divider />
                { selectedRecord && (currentUser.code === selectedRecord.creatorCode || currentUser.role === 'superAdmin') && <Menu.Item
                    onClick={()=>{
                        this.setState({ visibleTransferBox: true})
                    }}
                >
                    <Icon type="swap" />移交
                </Menu.Item>}
                { selectedRecord && (currentUser.code === selectedRecord.creatorCode || currentUser.role === 'superAdmin') && <Menu.Item
                    onClick={(e) => {
                        this.setState({ visibleDeleteBox: true})
                    }}
                >
                    <Icon type="delete" />删除
                    
                </Menu.Item>}
            </Menu>
        )
    }

    generateCard(list) {
        const { chart } = this.props;
        let { filterItem } = chart;

        let filterLabel = chart.filterLabel ? (chart.filterLabel + '').replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') : ''; // 添加转义符号
        
        let cards = list.map( (l, i) => (
            <ChartCard
                key={l.code}
                chart={l}
                filterItem={filterItem}
                filterLabel={filterLabel}
                onCardClick={this.onCardClick}
                generateOperationMenu={this.generateOperationMenu}
            />
        ));
        if(cards.length === 0) {
            return <EmptyContent />
        }
        return cards;
    }

    onCardClick = (chart) => {
        this.setState({ selectedRecord: chart })
    }

    createGroupMenu = (treeData) => {
        const { dispatch } = this.props;
        const { selectedRecord } = this.state;
        return treeData.map(t => {
            if(t.children && t.children.length > 0) {
                return <Menu.SubMenu
                    key={t.code}
                    className={selectedRecord.groupCode === t.code ? 'current' : ''}
                    title={t.label}
                    onTitleClick={() => {
                        dispatch({ type: 'chart/remoteSetGroup', chart: selectedRecord, group: t });
                    }}
                >
                    {this.createGroupMenu(t.children)}
                </Menu.SubMenu>
            }else {
                return <Menu.Item className={selectedRecord.groupCode === t.code ? 'current' : ''} key={t.code} onClick={() => {
                    dispatch({ type: 'chart/remoteSetGroup', chart: selectedRecord, group: t });
                }}>{t.label}</Menu.Item>
            }
        })
    }

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

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

    onDrop = (info) => {
        const { dispatch } = this.props;

        const dropCode = info.node.props.eventKey;
        const dragCode = info.dragNode.props.eventKey;
        const dropPos = info.node.props.pos.split('-');
        const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]); // -1/0/1 -> 兄/子/弟
        dispatch({ type: 'chart/remoteMoveGroup', dragCode, dropCode, dropPosition });
    }

    render() {
        const { dispatch, chart } = this.props;
        const { listLoading, noGroup } = chart;
        const { visibleChooseDataSourceBox, visibleDistributeBox, visibleGroupManageMentBox, visibleTransferBox, visibleDeleteBox, selectedRecord } = this.state;
        let viewList =  this.onFilter();
        return (
            <Layout className='layout-chart'>
                <Loading visible={listLoading} />
                <Content>
                    <Card bordered={false} title={
                        <Row className='tools' type='flex' justify='space-between'>
                            <Col className="groups" style={{ display: 'flex', width: 'calc(100% - 324px)', overflow: 'hidden' }}>
                                <Checkbox style={{ marginTop: '4px' }} checked={noGroup} onChange={(e) => {
                                    dispatch({ type: 'chart/setField', name: 'noGroup', value: e.target.checked });
                                    this.bodyRef.current.parentNode.scrollTo && this.bodyRef.current.parentNode.scrollTo(0, 0)
                                }}><span className="nogroup">未分组</span></Checkbox>
                                { this.generateGroupTags() }
                            </Col>
                            <Col className='search'>
                                <Col>
                                    <Button className='btn-refresh' onClick={() => {
                                        dispatch({ type: 'chart/setFilterLabel', label: '' });
                                        dispatch({ type: 'chart/fetchList', mandatory: true });
                                    }}>
                                        {/* <CusIcon type='bi-refresh'/> */}
                                        <Icon type='sync'/>
                                    </Button>
                                </Col>
                                <Col>
                                    <ListFilter modelName='chart' model={chart}/>
                                </Col>
                                <Col >
                                    <Button className='tool-link' onClick={() => {
                                        dispatch({ type: 'dataSource/fetchList' });
                                        this.setState({
                                            visibleChooseDataSourceBox: true
                                        });
                                    }}>
                                        <CusIcon type="bi-nav-chart" />创建图表
                                    </Button>
                                    {visibleChooseDataSourceBox && <ChooseDataSourceBox visibleChooseDataSourceBox={visibleChooseDataSourceBox} hideBox={() => {
                                        this.setState({
                                            visibleChooseDataSourceBox: false
                                        });
                                    }}/>}
                                </Col>
                            </Col>
                        </Row>
                    }>
                        <div ref={this.bodyRef} className='chart-body'>
                            { this.generateCard(viewList) }
                        </div>
                    </Card>
                </Content>
                {visibleGroupManageMentBox && <GroupManagementBox
                    typeText='图表'
                    visibleBox={visibleGroupManageMentBox}
                    groupData={chart.groupList}
                    hideBox={() => {
                        this.setState({
                            visibleGroupManageMentBox: false
                        })
                    }}
                    okHandler={(aGroups, mGroups, dGroups) => {
                        return dispatch({ type: 'chart/remoteSetGroups', aGroups, mGroups, dGroups }).then(() => {
                            dispatch({ type: 'chart/fetchList', mandatory: true });
                            dispatch({ type: 'chart/setCurrentGroup', group: null });
                        });
                    }}
                />}
                {visibleDistributeBox && <DistributeBox visibleDistributeBox={visibleDistributeBox} selectedRecord={this.state.selectedRecord} hideBox={() => {
                    this.setState({
                        visibleDistributeBox: false
                    });
                }} />}
                {visibleTransferBox && <TransferBox
                    visibleBox={visibleTransferBox}
                    title='选择移交对象'
                    okHandler={(user) => {
                        dispatch({ type: 'chart/transfer', chartCode: this.state.selectedRecord.code, userCode: user.code });
                    }}
                    hideBox={() => {
                        this.setState({
                            visibleTransferBox: false
                        })
                    }}
                />}
                {visibleDeleteBox && <DeleteBox
                    visibleBox={visibleDeleteBox}
                    text={<div><span>确定要删除图表【{selectedRecord.name}】吗？</span></div>}
                    hideBox={() => {
                        this.setState({
                            visibleDeleteBox: false
                        })
                    }}
                    okHandler={() => {
                        dispatch({ type: 'chart/remoteDelete', code: this.state.selectedRecord.code }).then(() => {
                            dispatch({ type: 'chart/fetchList', mandatory: true });
                        })
                }} />}
            </Layout>
        )
    }
}

export default connect(({ main, chart }) => ({ main, chart }))(ChartList)