import React from 'react'
import { Form, Input, Button, Select, Table, Checkbox, Divider, Icon, Popconfirm } from 'antd'
import { connect } from 'dva'
import COLUMN_TYPE from './columnType.json'
import { Resizable } from 'react-resizable';
const FormItem = Form.Item
const SelectOption = Select.Option

const ResizeableTitle = (props) => {
    const { onResize, width, ...restProps } = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable width={width} height={0} onResize={onResize}>
            <th {...restProps} />
        </Resizable>
    );
};

class DataSourceColumnConfig extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            widths: [ 80, 150, 150, 80, 80 ],
            visibleConfirm: false
        }
    }

    components = {
        header: {
            cell: ResizeableTitle,
        },
    };

    handleVisibleChange = (visible) => {
        const { columns } = this.props.dataSource.newOne;
        this.setState({ visibleConfirm: visible && (columns && columns.length > 0) });
    }

    handleResize = index => (e, { size }) => {
        this.setState(({ widths }) => {
            const nextWidths = [...widths];
            nextWidths[index] = size.width;
            return { widths: nextWidths };
        });
    };

    render() {

        const { dataSource, dispatch, loading } = this.props;
        const { widths } = this.state;

        const columns = [{
            title: <div><Checkbox
                style={{ margin: '0 8px 0 0', display: dataSource.newOne.columns ? (dataSource.newOne.columns.length > 0 ? 'inline-block' : 'none') : 'none'}}
                indeterminate={dataSource.newOne.columns ? (dataSource.newOne.columns.filter(c => c.using).length > 0 && dataSource.newOne.columns.filter(c => c.using).length < dataSource.newOne.columns.length) : false}
                checked={dataSource.newOne.columns ? (dataSource.newOne.columns.filter(c => c.using).length === dataSource.newOne.columns.length) : false}
                onChange={(e) => {
                    let target = e.target;
                    let columns = dataSource.newOne.columns ? dataSource.newOne.columns.map(c => {
                        c.using = target.checked;
                        return c;
                    }) : [];

                    dispatch({ type: 'dataSource/setNewModelField', name: 'columns', value: columns });
                }}
            />启用</div>,
            dataIndex: 'using',
            key: 'using',
            width: widths[0],
            render: (v, r) => <Checkbox
                dataKey={r.key}
                onChange={(e) => {
                    let target = e.target;
                    let key = target.dataKey;
                    let columns = dataSource.newOne.columns.map(c => {
                        if(c.key === key) {
                            c.using = target.checked;
                        }
                        return c;
                    });

                    dispatch({ type: 'dataSource/setNewModelField', name: 'columns', value: columns });
                }}
                checked={v}
            />
        }, {
            title: '列名',
            dataIndex: 'name',
            key: 'name',
            width: widths[1],
        // }, {
        //     title: '备注',
        //     dataIndex: 'description',
        //     key: 'description',
        //     width: widths[2],
        // }, {
        //     title: '数据类型',
        //     dataIndex: 'dataType',
        //     key: 'dataType',
        //     width: widths[3]
        }, {
            title: '分析类型',
            dataIndex: 'columnType',
            key: 'columnType',
            width: widths[2],
            render: (text, record) => {
                return (
                    <Select
                        style={{ width: '100%' }}
                        value={text}
                        onChange={(value) => {
                            let columns = dataSource.newOne.columns.map(c => {
                                if(c.key === record.key) {
                                    c.columnType = value;
                                    c.groupable = c.columnType === 'categorical';
                                    c.bucketizable = ['time', 'scale', 'ordinal'].indexOf(record.columnType) !== -1;
                                }
                                return c;
                            });
                            dispatch({ type: 'dataSource/setNewModelField', name: 'columns', value: columns });
                        }}
                    >
                    {
                        COLUMN_TYPE.map( c => {
                            // let dataType = record.dataType;
                            // if(c.dataType.indexOf(dataType) !== -1) {
                                return <SelectOption value={c.columnType} key={c.columnType}>{c.label}</SelectOption>
                            // }else {
                            //     return null
                            // }
                            
                        }).filter((s)=>s!==null)
                    }
                    </Select>
                )
            }
        }, {
            title: <div><Checkbox
                style={{ margin: '0 8px 0 0', display: dataSource.newOne.columns ? (dataSource.newOne.columns.length > 0 ? 'inline-block' : 'none') : 'none'}}
                indeterminate={dataSource.newOne.columns ? (dataSource.newOne.columns.filter(c => c.groupable).length > 0 && dataSource.newOne.columns.filter(c => c.groupable).length < dataSource.newOne.columns.length) : false}
                checked={dataSource.newOne.columns ? (dataSource.newOne.columns.filter(c => c.groupable).length === dataSource.newOne.columns.length) : false}
                onChange={(e) => {
                    let target = e.target;
                    let columns = dataSource.newOne.columns ? dataSource.newOne.columns.map(c => {
                        c.groupable = target.checked;
                        return c;
                    }) : [];

                    dispatch({ type: 'dataSource/setNewModelField', name: 'columns', value: columns });
                }}
            />允许分组</div>,
            dataIndex: 'groupable',
            key: 'groupable',
            width: widths[3],
            render: (v, r) => <Checkbox
                dataKey={r.key}
                onChange={(e) => {
                    let target = e.target;
                    let key = target.dataKey;
                    let columns = dataSource.newOne.columns.map(c => {
                        if(c.key === key) {
                            c.groupable = target.checked;
                        }
                        return c;
                    });

                    dispatch({ type: 'dataSource/setNewModelField', name: 'columns', value: columns });
                }}
                checked={v}
            />
        }, {
            title: <div><Checkbox
                style={{ margin: '0 8px 0 0', display: dataSource.newOne.columns ? (dataSource.newOne.columns.length > 0 ? 'inline-block' : 'none') : 'none'}}
                indeterminate={dataSource.newOne.columns ? (dataSource.newOne.columns.filter(c => c.filterable).length > 0 && dataSource.newOne.columns.filter(c => c.filterable).length < dataSource.newOne.columns.length) : false}
                checked={dataSource.newOne.columns ? (dataSource.newOne.columns.filter(c => c.filterable).length === dataSource.newOne.columns.length) : false}
                onChange={(e) => {
                    let target = e.target;
                    let columns = dataSource.newOne.columns ? dataSource.newOne.columns.map(c => {
                        c.filterable = target.checked;
                        return c;
                    }) : [];

                    dispatch({ type: 'dataSource/setNewModelField', name: 'columns', value: columns });
                }}
            />允许过滤</div>,
            dataIndex: 'filterable',
            key: 'filterable',
            width: widths[4],
            render: (v, r) => <Checkbox
                dataKey={r.key}
                onChange={(e) => {
                    let target = e.target;
                    let key = target.dataKey;
                    let columns = dataSource.newOne.columns.map(c => {
                        if(c.key === key) {
                            c.filterable = target.checked;
                        }
                        return c;
                    });

                    dispatch({ type: 'dataSource/setNewModelField', name: 'columns', value: columns });
                }}
                checked={v}
            />
        // }, {
        //     title: '允许分组',
        //     dataIndex: 'groupable',
        //     key: 'groupable',
        //     width: 50,
        //     className: 'column-groupable',
        //     render: (value, record) => <Switch disabled={record.columnType!=='categorical'} checked={value} onChange={(checked) => {
        //         let columns = dataSource.newOne.columns.map(c => {
        //             if(c.key === record.key) {
        //                 c.groupable = checked;
        //             }
        //             return c;
        //         });
        //         dispatch({ type: 'dataSource/setNewModelField', name: 'columns', value: columns });
        //     }}/>
        // }, {
        //     title: '允许分段',
        //     dataIndex: 'bucketizable',
        //     key: 'bucketizable',
        //     width: 50,
        //     className: 'column-bucketizable',
        //     render: (value, record) => <Switch
        //         disabled={['time', 'scale', 'ordinal'].indexOf(record.columnType)===-1}
        //         checked={value}
        //         defaultChecked={true}
        //         onChange={(checked) => {
        //             let columns = dataSource.newOne.columns.map(c => {
        //                 if(c.key === record.key) {
        //                     c.bucketizable = checked;
        //                 }
        //                 return c;
        //             });
        //             dispatch({ type: 'dataSource/setNewModelField', name: 'columns', value: columns });
        //         }}
        //     />
        }, {
            title: '别名',
            dataIndex: 'alias',
            key: 'alias',
            // width: widths[5],
            render: (text, record) => {
                return(
                    <Input
                        value={text}
                        placeholder={record.description ? record.description.substring(0, 10) : record.name}
                        onChange={(e) => {
                            const value = e.target.value;
                            let columns = dataSource.newOne.columns.map(c => {
                                if(c.key === record.key) {
                                    c['alias'] = value;
                                }
                                return c;
                            });
                            
                            dispatch({ type: 'dataSource/setNewModelField', name: 'columns', value: columns });
                        }}
                    >
                    </Input>
                )
            }
        // }, {
        //     title: '允许过滤',
        //     dataIndex: 'filterable',
        //     key: 'filterable',
        //     render: (value, record) => <Switch />
        }].map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));

        return (
            <div>
                {
                    dataSource.newOne.type==='database'?(
                        <div>
                            <Form size='small'>
                                <Divider orientation="left">数据对象</Divider>
                                <FormItem className='textarea-target'>
                                    <Input.TextArea
                                        disabled={!dataSource.newOne.address}
                                        placeholder={dataSource.newOne.address ? '输入表名或查询SQL，注意不能以分号结尾' : '请返回上一步选择数据库连接'}
                                        autosize={{ minRows: 3 }}
                                        value={dataSource.newOne.target}
                                        onChange={(e) => {
                                            dispatch({ type: 'dataSource/setNewModelInvalidSQL', value: false });
                                            dispatch({ type: 'dataSource/setNewModelField', name: 'target', value: e.target.value });
                                        }}
                                    />
                                </FormItem>
                                <div className='buttons'>
                                    <div className='errormessage' style={{ cursor: dataSource.newOne.invalidSQL ? 'text' : 'default', opacity: dataSource.newOne.invalidSQL ? '1' : '0' }}>未查询到列数据，请检查SQL是否正确</div>
                                    <Popconfirm
                                        title="已存在列数据，确定要覆盖吗？"
                                        visible={this.state.visibleConfirm}
                                        onVisibleChange={this.handleVisibleChange}
                                        onConfirm={() => {
                                            this.setState({
                                                visibleConfirm: false
                                            });
                                            dispatch({ type: 'dataSource/importNewModelColumns' });
                                        }}
                                        onCancel={() => {
                                            this.setState({
                                                visibleConfirm: false
                                            });
                                        }}
                                        okText="确定"
                                        cancelText="取消"
                                    >
                                        <Button disabled={!dataSource.newOne.address || loading.models.dataSource} onClick={() => {
                                            if(!dataSource.newOne.columns || dataSource.newOne.columns.length === 0) {
                                                dispatch({ type: 'dataSource/importNewModelColumns' });
                                            }
                                        }}>
                                        {
                                            loading.models.dataSource ? <Icon type="loading" /> : ''
                                        }
                                        {'获取数据列'}
                                        </Button>
                                    </Popconfirm>
                                </div>
                            </Form>
                            <Divider orientation="left">数据列</Divider>
                        </div>
                    ):null
                }
                <Table
                    className='table-columnconfig'
                    bordered
                    components={this.components}
                    dataSource={dataSource.newOne.columns}
                    columns={columns}
                    locale={{
                        emptyText: '未连接到数据对象'
                    }}
                />
            </div>
        );
    }
}

function mapStateToProps({ present: { dataSource, dataConnect, loading } }) {
    return { dataSource, dataConnect, loading }
}

export default connect(mapStateToProps)(DataSourceColumnConfig);