import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Row, Col, Select } from '@easyv/antd';
import message from 'components/message';
import ConfirmModal from './ConfirmModal';
import { switchUser } from 'models/user';
import { request } from 'utils/fetch';
import { api } from 'constants/config';

const Option = Select.Option;

interface IProps {
  tenantId: number;
  username: string;
  userRole: 0 | 1 | 2;
  defaultVisible?: boolean;
  switchUser: (id, callback) => void;
  children?: React.ReactNode | React.ReactNode[];
}

interface IState {
  visible: boolean;
  current: number | null;
  tenants: any;
}

class UsersModal extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    const { defaultVisible = false } = props;
    this.state = {
      visible: defaultVisible,
      current: null,
      tenants: []
    };
  }

  onHide = () => {
    this.setState({
      visible: false
    });
  };

  onShow = async () => {
    const result =
      this.props.userRole === 2
        ? await request(api.tenantList, undefined, { limit: 999, includePersonal: true })
        : await request(api.userTenants, undefined, { limit: 999 });

    this.setState({
      visible: true,
      tenants: result
    });
  };

  onComplete = () => {
    const { current } = this.state;
    if (current) {
      if (current === this.props.tenantId) {
        this.onHide();
      } else {
        this.props.switchUser(current, () => {
          window.location.reload();
        });
      }
    } else {
      message.error('请选择租户');
    }
  };

  onChange = (value) => {
    this.setState({
      current: value
    });
  };

  render() {
    const { children, tenantId, username, userRole } = this.props;
    const { visible, current, tenants } = this.state;

    let showTenants = tenants;
    if (userRole === 2 && showTenants.length > 0) {
      const currentTenant = showTenants.find((o) => o.name === `${username}的个人空间`);
      if (currentTenant) {
        showTenants = [{ ...currentTenant, name: '个人空间' }].concat(showTenants.filter((o) => o.name !== `${username}的个人空间`));
      }
    }

    return (
      <span>
        <span onClick={this.onShow} style={{ display: 'inline-block', width: '100%' }}>
          {children}
        </span>
        <ConfirmModal visible={visible} title="选择租户" footer={true} onCancel={this.onHide} onOk={this.onComplete}>
          <div style={{ padding: '30px 0' }}>
            <Row style={{ display: 'flex', alignItems: 'center' }}>
              <Col span={8} style={{ textAlign: 'right' }}>
                租户：
              </Col>
              <Col span={12}>
                <Select
                  showSearch
                  placeholder="选择租户"
                  onChange={this.onChange}
                  value={current ? `${current}` : `${tenantId}`}
                  style={{ width: '100%' }}
                  optionFilterProp="name">
                  {showTenants.map((d) => {
                    return (
                      <Option key={d.id} value={`${d.id}`} name={d.name}>
                        {d.name}
                      </Option>
                    );
                  })}
                </Select>
              </Col>
            </Row>
          </div>
        </ConfirmModal>
      </span>
    );
  }
}

function mapStateToProps(state) {
  return {
    userRole: state.user.userInfo.role,
    username: state.user.userInfo.userName,
    tenants: state.user.tenants,
    tenantId: state.user.userInfo.tenantId
  };
}

const mapDispatchToProps = {
  switchUser: switchUser
};

export default connect(mapStateToProps, mapDispatchToProps)(UsersModal);
