import React from 'react'
import Echarts from 'echarts-for-react'
import { connect } from 'dva'
import { Table } from 'antd'
import resolveChartOption from '../chart/resolveChartOption.js'
import RichTextEditor from './richTextEditor'

const ChartView = ({ item, itemSize, chart, editMode, dispatch }) => {
    const { viewType, chartCode, content } = item;
    let children = <div className='chart-default mover'></div>;

    if(viewType === 'chart') { // 图表类型
        let targetChart = chart.list.filter(c => c.code === chartCode)[0];
        if(targetChart) {
            let option = resolveChartOption(targetChart ? targetChart.chartOption : {}, editMode);
            let type = ['bar', 'line', 'pie', 'scatter'].indexOf(targetChart.type) !== -1 ? 'echarts' :
                (['aggregateTable', 'dataView'].indexOf(targetChart.type) !== -1 ? 'table' : 'default');
            if(type === 'echarts') {
                children = <Echarts
                    key={chartCode}
                    option={option}
                    className='rc-echarts mover'
                    style={{height: '100%'}}
                />
            }else if(type === 'table') {
                const { columns, data } = option;
                const { height } = itemSize;
                children = <Table
                    className='dashboard-table'
                    size='small'
                    scroll={{
                        x: columns ? columns.length * 100 : 0,
                        y: height - 38 - 50 - 16 , // 减去工具栏高度、表格标题栏高度、分页工具高度、缩放调整按钮高度
                    }}
                    columns={columns ? columns.map(c => ({
                        ...c,
                        width: 100
                    })) : []}
                    dataSource={data}
                />
            }
        }
    }else if(viewType === 'richText') { // 富文本类型
        children = <RichTextEditor content={content} onContentChange={(content) => {
            dispatch({ type: 'dashboardDesigner/modifyItem', fields: { code: item.code, content } });
        }}/>
    }else {
        children = <div className='mover'>错误类型</div>
    }

    return (
        <div className='chartview-content' style={{ width: '100%', height: '100%' }}>
            {children}
        </div>
    );
}

export default connect(({ present: { chart } }) => ({ chart }))(ChartView);