import React from 'react';
import { Input, Icon, Button, Popconfirm, Switch, Form } from 'antd';
import { connect } from 'dva';
import './header.less';
import Loadable from 'utils/loadable';

const DeleteBox = Loadable(() => import('components/common/deleteBox/deleteBox'), true);

const FormItem = Form.Item;

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

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

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

    isValid = () => {
        const { dashboardDesigner } = this.props;
        const { name } = dashboardDesigner; 

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

    render() {
        const { dashboardDesigner, dispatch } = this.props;
        const { visibleDeleteBox, validInfo } = this.state;
        const { editMode } = dashboardDesigner;

        return (
            <div className='dashboarddesigner-header-content'>
                <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={async () => {
                            if(this.isValid()) {
                                dispatch({ type: 'dashboard/remoteModify' });
                                dispatch({ type: 'main/goBack', path: '/workshop/dashboard' });
                            }
                            this.setState({
                                visibleConfirm: false
                            });
                        }}
                        onCancel={() => {
                            this.setState({
                                visibleConfirm: false
                            });
                            dispatch({ type: 'main/redirect', path: '/workshop/dashboard' });
                        }}
                        okText="保存"
                        cancelText="不保存"
                    >
                        <Button onClick={() => {
                            if(!dashboardDesigner.dirty) {
                                dispatch({ type: 'main/goBack', path: '/workshop/dashboard' });
                                dispatch({ type: 'dashboardDesigner/reset' });
                            }
                        }}>
                            <Icon type='left' />返回
                        </Button>
                    </Popconfirm>}
                    {!this.isOwner() && <Button onClick={(e) => {
                        dispatch({ type: 'main/goBack', path: '/workshop/chart' });
                        dispatch({ type: 'dashboardDesigner/reset' });
                    }}>
                        <Icon type='left' />返回
                    </Button>}
                </div>
                <div className='header-item toolbar-title'>
                    <FormItem
                        validateStatus={validInfo.name.status}
                        help={validInfo.name.help}
                    >
                        <Input
                            key={dashboardDesigner.name}
                            className='input-title'
                            defaultValue={dashboardDesigner.name}
                            readOnly={!this.isOwner()}
                            addonAfter={this.isOwner() ? <Icon type="edit" 
                                onClick={(e) => {
                                    const input = e.currentTarget.parentElement.parentElement.getElementsByTagName('input')[0];
                                    input && input.focus()
                                }}
                            /> : null}
                            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, name: { status, help } }
                                    });
                                }, 100);
                            }}
                            onBlur={(e) => {
                                dispatch({ type: 'dashboardDesigner/setField', name: 'name', value: e.target.value });
                            }}
                            onPressEnter={(e) => {
                                dispatch({ type: 'dashboardDesigner/setField', name: 'name', value: e.target.value });
                            }}
                        />
                    </FormItem>
                </div>
                <div className='header-item toolbar-viewswitch'>
                    {this.isOwner() && <Switch
                        className={`mode-switch ${editMode ? 'edit-mode-switch' : 'view-mode-switch'}`}
                        checked={editMode}
                        checkedChildren="编辑"
                        unCheckedChildren="浏览"
                        onChange={(checked) => {
                            dispatch({ type: 'dashboardDesigner/setEditMode', checked });
                            // 主动触发一次window的resize事件
                            window.setTimeout(() => {
                                var e = document.createEvent("Event");
                                e.initEvent("resize", true, true);
                                window.dispatchEvent(e);
                            }, 500);
                        }}
                    />}
                    {this.isOwner() && <Button disabled={!this.isValid()} style={{ marginLeft: '8px' }} onClick={() => {
                        if(dashboardDesigner.code && dashboardDesigner.code !== -1) {
                            dispatch({ type: 'dashboard/remoteModify' });
                        }else {
                            dispatch({ type: 'dashboard/remoteAdd' });
                        }
                    }}>保存</Button>}
                    {this.isOwner() && <Button style={{ marginLeft: '8px' }} onClick={() => {
                        this.setState({
                            visibleDeleteBox: true
                        });
                    }}>删除</Button>}
                    {visibleDeleteBox && <DeleteBox
                        visibleBox={visibleDeleteBox}
                        text={<div><span>确定要删除报表【{dashboardDesigner.name}】吗？</span></div>}
                        hideBox={() => {
                            this.setState({
                                visibleDeleteBox: false
                            })
                        }}
                        okHandler={() => {
                            dispatch({ type: 'dashboard/remoteDelete', code: dashboardDesigner.code })
                            dispatch({ type: 'main/redirect', path: '/workshop/dashboard' });
                    }} />}
                </div>
            </div>
        );
    }
}

export default connect(({ main, dashboardDesigner }) => ({ main, dashboardDesigner }))(Header);