import React from 'react'
import '../../models/dashboardDesigner'
import { Modal, Checkbox, Row, Col, Table, Input, message } from 'antd'
import { connect } from 'dva'
import { dateFormat } from '../../utils/baseUtils'
import 'braft-editor/dist/braft.css'
import './chooseChartBox.less'
const { Search } = Input

class ChooseChartBox extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            filterLabel: '',
            selectedRecord: []
        };
    }

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

    changeSelected = (record) => {
        let arr = this.state.selectedRecord;
        let findIndex = arr.findIndex(a => a.code === record.code);
        if(findIndex !== -1) {
            arr.splice(findIndex, 1)
        }else {
            arr.push(record);
        }
        this.setState({
            selectedRecord: arr 
        });
    }

    okHandler = (model) => {
        const { selectedRecord } = this.state;
        const { dispatch, hideBox } = this.props;
        if(selectedRecord) {
            dispatch({ type: 'dashboardDesigner/addCharts', charts: selectedRecord });
            hideBox();
        }else {
            message.warning('未选中图表');
        }
    }

    handleChange = (content) => {
    }

    handleRawChange = (rawContent) => {
    }

    
    static editorProps = {
        height: 300,
        contentFormat: 'raw',
        initialContent: '<p>Hello World!</p>',
        onChange: () => {},
        onRawChange: () => {},
        image: true, // 开启图片插入功能?
    }

    render() {
        const { visibleBox, hideBox, dashboardDesigner, chart } = this.props;
        const { selectedRecord } = this.state;
        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let filterLabel = this.state.filterLabel.replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1'); // 添加转义符号
        const columns = [{
            title: '选择',
            key: 'selected',
            width: 50,
            render: (text, record) => {
                return <Checkbox checked={dashboardDesigner.items.findIndex(i => i.chartCode===record.code)!==-1 || selectedRecord.findIndex(s => s.code === record.code) !== -1 } disabled={dashboardDesigner.items.findIndex(i => i.chartCode===record.code)!==-1}/>
            }
        }, {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: 100,
            render: (text, record) => {
                return <div>
                    <div>
                        <span>
                            { filterLabel ?
                                (text.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
                                    )
                                }
                                )) : text
                            }
                        </span>
                    </div>
                </div>
            }
        }, {
            title: '创建人',
            dataIndex: 'creator',
            key: 'creator',
            width: 100
        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 120,
            render: (text) => dateFormat(new Date(text), 'yyyy-MM-dd')
        }, {
            title: '说明',
            dataIndex: 'description',
            key: 'description',
            width: 200,
            render: (text, record) => {
                return (
                    <span>
                        { filterLabel ?
                            ((text || '').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
                                )
                            }
                            )) : text
                        }
                    </span>
                )
            }
        }]
        return (
            <Modal
                className='choosechart-box'
                title={
                    <Row>
                        <Col span={14}>选择图表</Col>
                        <Col span={8}><Search 
                            placeholder="请输入关键字"
                            value={this.state.filterLabel}
                            onChange={e => {
                                this.setState({
                                    filterLabel: e.target.value
                                });
                            }}
                        /></Col>
                    </Row>
                }
                visible={visibleBox}
                onOk={() => {this.setState({ filterLabel: '', selectedRecord: [] });this.okHandler()}}
                onCancel={() => {this.setState({ filterLabel: '', selectedRecord: [] });hideBox()}}
                maskClosable={false}
                destroyOnClose={true}
            >
                <Table
                    className='choosechart-table'
                    columns={columns}
                    dataSource={chart.list.map((l, i) => ({ ...l, key: i})).filter(l => {
                        let regLabel = new RegExp('(' + filterLabel + '){1}', 'ig');
                        return (l.name || '').search(regLabel) !== -1 || (l.description || '').search(regLabel) !== -1;
                    })}
                    size='small'
                    scroll={{x: false, y: 471}}
                    pagination={false}
                    onRow={(record) => {
                        return {
                            onClick: () => {
                                if(dashboardDesigner.items.findIndex(i => i.chartCode===record.code)===-1) {
                                    this.changeSelected(record);
                                }
                            }
                        };
                    }}
                />
            </Modal>
        )
        // return (
        //     <Modal
        //         className='element-config'
        //         title={`${operation==='create'?'新增':'修改'}元素`}
        //         visible={visibleBox}
        //         onOk={() => {this.okHandler()}}
        //         onCancel={hideElementConfigBox}
        //         maskClosable={false}
        //         destroyOnClose={true}
        //     >
        //         <div>
        //             <Select defaultValue={dashboardDesigner.configBoxForm.type} style={{ width: 120 }} 
        //                 onChange={(value) => { dispatch( {type: 'dashboardDesigner/handleFieldChange', name: 'type', value: value})}}>
        //                 <Option value="chart">图表</Option>
        //                 <Option value="simple">基础元素</Option>
        //             </Select>
        //         </div>
        //         <div style={{display: `${dashboardDesigner.configBoxForm.type === "simple" ? "inline":"none"}`}}>
        //             <BraftEditor {...this.editorProps}/>
        //         </div>
        //     </Modal>
        // )
    } 
}



    




function mapStateToProps({ present: { dashboardDesigner, chart } }) {
    return { dashboardDesigner, chart };
}

export default connect(mapStateToProps)(ChooseChartBox)