import React from 'react'
import { Input, Icon, Button, Popconfirm, Tooltip, Modal, Form } from 'antd'
import { connect } from 'dva'
import DeleteBox from '../common/deleteBox/deleteBox'
import './header.less'
const FormItem = Form.Item

class Header extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visibleConfirm: false,
            visibleCopyBox: false,
            visibleDeleteBox: false,
            newHeaderLabel: '',
            validInfo: {
                header: { status: 'success', help: '' }
            },
        }
    }

    handleVisibleChange = (visible) => {
        this.setState({ visibleConfirm: visible });
    }

    copyHandler = () => {
        const { dispatch } = this.props;
        this.setState({
            visibleCopyBox: false
        }, () => {
            dispatch({ type: 'chartDesigner/remoteCopyAdd', newHeaderLabel: this.state.newHeaderLabel });
        });
    }

    isOwner = () => {
        const { chartDesigner, main } = this.props;
        const { creatorCode } = chartDesigner;
        const { currentUser } = main;
        return currentUser.code === creatorCode || currentUser.role === 'superAdmin';
    }

    isValid = () => {
        const { chartDesigner } = this.props;
        const { header } = chartDesigner; 

        return !!header.label && header.label.trim().length > 0 && header.label.length <= 50;
    }

    render() {
        const { chartDesigner, dispatch } = this.props;
        const { visibleCopyBox, newHeaderLabel, visibleDeleteBox, validInfo } = this.state;
        return (
            <div className='header'>
                <div className='header-item toolbar-back'>
                    {this.isOwner() && <Popconfirm
                        overlayClassName={`close-popconfirm${this.isValid() ? '' : ' confirm-disabled'}`}
                        placement="bottomLeft"
                        title="离开前保存修改吗？"
                        visible={this.state.visibleConfirm}
                        onVisibleChange={this.handleVisibleChange}
                        onConfirm={() => {
                            if(this.isValid()) {
                                dispatch({ type: 'chart/remoteModify' });
                                dispatch({ type: 'main/goBack', path: '/workshop/chart' });
                            }
                            this.setState({
                                visibleConfirm: false
                            });
                        }}
                        onCancel={() => {
                            this.setState({
                                visibleConfirm: false
                            });
                            dispatch({ type: 'main/goBack', path: '/workshop/chart' });
                        }}
                        okText="保存"
                        cancelText="不保存"
                    >
                        <Button onClick={(e) => {
                            if(!chartDesigner.dirty) {
                                dispatch({ type: 'main/goBack', path: '/workshop/chart' });
                            }
                        }}>
                            <Icon type='left' />返回
                        </Button>
                    </Popconfirm>}
                    {!this.isOwner() && <Button onClick={(e) => {
                        dispatch({ type: 'main/goBack', path: '/workshop/chart' });
                    }}>
                        <Icon type='left' />返回
                    </Button>}
                </div>
                <div className='header-item toolbar-title'>
                    <FormItem
                        validateStatus={validInfo.header.status}
                        help={validInfo.header.help}
                    >
                        <Input
                            key={chartDesigner.header.label}
                            className='input-title'
                            readOnly={!this.isOwner()}
                            defaultValue={chartDesigner.header.label}
                            addonAfter={this.isOwner() ? <Icon type="edit" 
                                onClick={(e) => {
                                    const input = e.currentTarget.parentElement.parentElement.getElementsByTagName('input')[0];
                                    input && input.focus()
                                }}
                            /> : ''}
                            onBlur={(e) => {
                                dispatch({ type: 'chartDesigner/setField', name: 'header', value: { label: e.target.value + '' } });
                            }}
                            onPressEnter={(e) => {
                                dispatch({ type: 'chartDesigner/setField', name: 'header', value: { label: e.target.value + '' } });
                            }}
                            onChange={e => {
                                let val = e.target.value + '';
                                let status, help;
                                if(val.trim().length === 0) {
                                    status = 'error';
                                    help = '数据源名称不能为空';
                                }else if(val.trim().length > 50) {
                                    status = 'error';
                                    help = '数据源名称不能超过50个字符';
                                }else {
                                    status = 'success';
                                    help = '';
                                }
                                window.clearTimeout(this.headerTimeout);
                                this.headerTimeout = window.setTimeout(() => {
                                    this.setState({
                                        validInfo: { ...validInfo, header: { status, help } }
                                    });
                                }, 100);
                            }}
                        />
                    </FormItem>
                </div>
                <div className='header-item toolbar-buttons'>
                    {this.isOwner() && <Button disabled={!this.isValid()} onClick={() => {
                        if(chartDesigner.code && chartDesigner.code !== -1) {
                            dispatch({ type: 'chart/remoteModify' });
                        }else {
                            dispatch({ type: 'chart/remoteAdd' });
                        }
                        dispatch({ type: 'chartDesigner/setDirty', dirty: false });
                    }}>保存</Button>}
                    {this.isOwner() && <Tooltip title='复制新增'>
                        <Button disabled={!this.isValid()} className='tools-btn' onClick={() => {
                            this.setState({
                                visibleCopyBox: true,
                                newHeaderLabel: chartDesigner.header.label + '_副本'
                            })
                        }}>
                        复制
                        </Button>
                    </Tooltip>}
                    {this.isOwner() && visibleCopyBox && <Modal
                        title="复制新增"
                        visible={visibleCopyBox}
                        okText='创建'
                        onOk={this.copyHandler}
                        onCancel={() => {this.setState({visibleCopyBox:false})}}
                    >
                        <p>当前的图表会被保存，您将从新的图表副本继续设计。</p>
                        副本名称:<Input value={newHeaderLabel} placeholder={chartDesigner.header.label+'_副本'} onChange={(e) => {
                            this.setState({
                                newHeaderLabel: e.target.value
                            });
                        }} />
                    </Modal>}
                    {this.isOwner() && <Button onClick={() => {
                        this.setState({
                            visibleDeleteBox: true
                        });
                    }}>删除</Button>}
                    {visibleDeleteBox && <DeleteBox
                        visibleBox={visibleDeleteBox}
                        text={<div><span>确定要删除图表【{chartDesigner.header.label}】吗？</span></div>}
                        hideBox={() => {
                            this.setState({
                                visibleDeleteBox: false
                            })
                        }}
                        okHandler={() => {
                            dispatch({ type: 'chart/remoteDelete', code: chartDesigner.code });
                            dispatch({ type: 'main/redirect', path: '/workshop/chart' });
                    }} />}
                </div>
            </div>
        );
    }
}

function mapStateToProps(state) {
    const { past, present, future } = state;
    const { main, chartDesigner } = present;
    return { main, chartDesigner, past, future }
}
export default connect(mapStateToProps)(Header);