import React from 'react';
import { Loading, Dropdown, Menu, Button, Icon, Search, Dialog } from '@txdfe/at';
import { debounce } from 'debounce';
import exceed from '../../utils/api';
import MemberItem from '../mini-member-item';
import Empty from '../empty';
import { fillMembersInfo, findMemberIndex, filterMembers } from '../../utils/utils';
import './index.scss';

const { Inner } = Dialog;

class MiniPanel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: Array.isArray(props.defaultList) ? props.defaultList : [],
      currentValue: [],
      showValue: false,
      currentRole: props.customRoles.length > 0 ? props.customRoles[0] : {},
      loading: true,
    };
    this.isCustomData = Array.isArray(props.dataSource);
  }

  componentDidMount() {
    this.resetData(this.props);
    this.loadUserInfo(this.props.value.map(v => v._userId));
  }

  resetData = ({ value = [], mode, dataSource, defaultList }) => {
    const currentValue = mode === 'add' ? [] : value;
    this.setState({ currentValue });
    if (this.isCustomData) {
      this.setState({
        data: Array.isArray(defaultList) ? defaultList : dataSource,
        loading: false,
      });
    } else if (defaultList === 'recommend') {
      this.loadRecommendData();
    } else if (defaultList === 'default') {
      this.onSearch('');
    }
  }

  loadUserInfo = (userIds = []) => {
    if (!userIds.length) return;
    const { mode, value, dataSource, ready } = this.props;
    if (this.isCustomData) {
      const currentValue = fillMembersInfo(value, dataSource);
      ready(currentValue);
      this.setState({
        currentValue: mode === 'add' ? [] : currentValue,
      });
    } else {
      exceed.fetch({
        api: 'getUsersInfo',
        data: { userIds, withJoinedTeams: true },
      }).then(({ data }) => {
        const { result = [] } = data;
        const currentValue = fillMembersInfo(value, result);
        ready(currentValue);
        this.setState({
          currentValue: mode === 'add' ? [] : currentValue,
        });
      });
    }
  }

  onChange = (member, isAdd) => {
    const { multiple } = this.props;
    const { currentValue } = this.state;
    if (multiple) { // 多选
      const newValue = [...currentValue];
      if (isAdd) { // 勾选成员
        newValue.push(member);
      } else { // 反勾选
        newValue.splice(findMemberIndex(newValue, member), 1);
      }
      this.setState({
        currentValue: newValue,
      });
    } else { // 单选
      this.props.onChange([member]);
    }
  }

  fetch = (q = '') => {
    const { pageSize } = this.props;
    this.setState({ loading: true });
    exceed.fetch({
      api: 'memberSearch',
      data: {
        q,
        pageSize,
      },
    }).then(res => {
      const result = res.data.result.result || res.data.result;
      this.setState({
        data: result,
        loading: false,
      });
    });
  }

  loadRecommendData() {
    exceed.fetch({
      api: 'getRecommendUsers',
    }).then(res => {
      const result = res.data.result || [];
      this.setState({
        data: result.map(r => ({ name: r.name, _userId: r._id, memberType: 'user', userInfo: { ...r } })),
        loading: false,
      });
    });
  }

  onSearch = async (value = '') => {
    if (this.isCustomData) {
      if (this.props.onSearch) {
        this.setState({
          loading: true,
        });
        const searchData = await this.props.onSearch(value);
        this.setState({
          data: searchData,
          loading: false,
        });
        return;
      }
      this.setState({
        data: filterMembers(this.props.dataSource, value),
        loading: false,
      });
    } else {
      this.fetch(value);
    }
  }

  onSubmit = () => {
    this.props.onChange(this.state.currentValue, this.state.currentRole.value);
  }

  toggleValueList = () => {
    const { showValue } = this.state;
    this.setState({
      showValue: !showValue,
    });
  }

  onChangeRole = (index) => {
    const { customRoles } = this.props;
    this.setState({
      currentRole: customRoles[index],
    });
  }

  render() {
    const { title, multiple, customRoles, value, okText, loading: propsLoading, mode, autoFocus, debounceWait } = this.props;
    const { data, currentValue, showValue, currentRole, loading: stateLoading } = this.state;
    const listData = showValue ? currentValue : data;
    const loading = propsLoading || stateLoading;
    return (
      <Inner
        title={title}
        footer={false}
        onClose={this.props.toggleVisible}
        className="uiless-member-mini"
        autoFocus={false}
      >
        <div className="uiless-member-mini-content">
          <Search
            className="uiless-member-mini-search"
            onChange={debounce(this.onSearch, debounceWait)}
            placeholder="请输入关键字"
            addonAfter={multiple && (
              <Button
                type={showValue ? 'primary' : 'secondary'}
                size="xs"
                onClick={this.toggleValueList}
              >
                已选 {currentValue.length}
              </Button>
            )}
            autoFocus={autoFocus}
            onFocus={() => { this.setState({ showValue: false }); }}
          />
          {
            <div className="uiless-member-mini-members">
              { loading && <Loading style={{ display: 'block' }} /> }
              {
                !loading && listData.length > 0 &&
                  listData.map(item => (
                    <MemberItem
                      key={item._id}
                      member={item}
                      {...this.props}
                      onChange={this.onChange}
                      value={currentValue}
                      defaultValue={value}
                    />
                  ))
              }
              { !loading && listData.length === 0 && <Empty /> }
            </div>
          }
          {
            multiple && customRoles.length > 0 && currentValue.length > 0 &&
            <div ref={o => { this.submitPanelMini = o; }} className="uiless-member-mini-submit">
              <span>添加为</span>
              <Dropdown
                trigger={<a className="uiless-member-mini-submit-rule">{currentRole.label} <Icon type="chevron-down-s" /></a>}
                triggerType={['click']}
                container={this.submitPanelMini}
                align="tl bl"
              >
                <Menu onItemClick={this.onChangeRole}>
                  {
                    customRoles.map((item, index) => (
                      <Menu.Item key={index} className="uiless-member-mini-submit-menu">
                        {currentRole.value === item.value && <Icon size="small" type="tick" />}
                        {item.label}
                      </Menu.Item>))
                  }
                </Menu>
              </Dropdown>
            </div>
          }
          {multiple &&
            <div className="uiless-member-mini-submit-button">
              <Button
                disabled={mode === 'add' && currentValue.length === 0}
                onClick={this.onSubmit}
                type="primary"
              >
                {okText}
              </Button>
            </div>
          }
        </div>
      </Inner>
    );
  }
}

export default MiniPanel;
