import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Row, Col, Select } from '@easyv/antd';
import ConfirmModal from './ConfirmModal';
import { getTenants, switchUser } from 'models/user';
import debounce from 'lodash/debounce';

const Option = Select.Option;

interface IProps {
  tenants: any;
  tenantName: string;
  tenantId: number | string;
  defaultVisible?: boolean;
  switchTenant: (id) => Promise<{}>;
  getTenants: (param?) => void;
  children?: React.ReactNode | React.ReactNode[];
}

interface IState {
  visible: boolean;
  current: string | number | null;
  loading: boolean;
}

class TenantModal extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    const { defaultVisible = false, tenantId = '' } = props;
    this.state = {
      visible: defaultVisible,
      current: tenantId,
      loading: false
    };
  }

  componentDidMount() {
    this.props.getTenants();
  }

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

  onShow = () => {
    this.setState({
      visible: true
    });
  };

  onComplete = async () => {
    const { tenants, switchTenant, tenantId } = this.props;
    const { current } = this.state;
    const value = current || (tenants[0] && tenants[0].id);
    if (value && value !== tenantId) {
      this.setState({
        loading: true
      });

      const result = await switchTenant(value);

      this.setState({
        loading: false
      });

      if (result) {
        window.location.reload();
      }
    } else {
      this.onHide();
    }
  };

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

  handleSearch = (value) => {
    this.props.getTenants(value);
  };

  render() {
    // eslint-disable-next-line prefer-const
    let { tenants = [], children, tenantName, tenantId } = this.props;
    const { visible, current, loading } = this.state;
    if (tenantId) {
      const hasCurrentTenant = tenants.find((d) => d.id === tenantId);
      if (!hasCurrentTenant) {
        tenants = tenants.concat({ id: tenantId, name: tenantName });
      }
    }

    const value = current || (tenants[0] && tenants[0].id);

    return (
      <span>
        <span onClick={this.onShow} style={{ display: 'flex' }}>
          {children}
        </span>
        <ConfirmModal
          visible={visible}
          title="选择租户"
          footer={true}
          onCancel={this.onHide}
          onOk={this.onComplete}
          destroyOnClose
          confirmLoading={loading}>
          <div style={{ padding: '30px 0' }}>
            <Row style={{ display: 'flex', alignItems: 'center' }}>
              <Col span={4} style={{ textAlign: 'right' }}>
                租户：
              </Col>
              <Col span={18}>
                <Select
                  showSearch
                  onSearch={debounce(this.handleSearch, 300)}
                  filterOption={false}
                  placeholder="选择租户"
                  onChange={this.onChange}
                  value={value}
                  style={{ width: '100%' }}
                  optionFilterProp="name">
                  {tenants.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 {
    tenants: state.user.tenants,
    tenantId: state.user.userInfo.tenantId,
    tenantName: state.user.userInfo.tenantName
  };
}

const mapDispatchToProps = {
  getTenants: getTenants,
  switchTenant: switchUser
};

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