import React, { Component } from 'react';
import { Input, Icon } from 'amos-antd';
import { Radio, Scrollbars, Collapse } from 'amos-framework';
import ImageConsts from '@gm/graphmod-assets';
import PropTypes from 'prop-types';
import { tools } from '@gm/graphmod-utils';
import { searchUser, getUserTree } from './api';
import Tip from '../tip';
import CommonModal from '../modal';
import './index.scss';

const Panel = Collapse.Panel;
const USER = 'user';
const GROUP = 'group';

/**
 * 分享人员选择
 *
 * @class UserSelector
 * @extends {Component}
 */
class UserSelector extends Component {
  static propTypes = {
    onOk: PropTypes.func
  };

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      userTree: {},
      userList: [],
      visible: false,
      searchKeyWords: '',
      currentGroups: [],
      selectedList: [],
      config: {
        getUserListUrl: '/precontrol/person/search?name={name}',
        getUserTreeUrl: '/privilege/v1/userorg/tree'
      },
      activeKey: []
    };
  }

  onOpen = (config, selectedList) => {
    this.setState({ config, visible: true, currentGroups: [], selectedList: selectedList || [] });
    getUserTree(config.getUserTreeUrl)
      .then(res => {
        tools.recursive(res).map(e => {
          if (e.type !== USER) {
            e.type = GROUP;
          }
          return e;
        });
        this.setState({ userTree: res, activeKey: res.length ? [res[0].id] : [] });
      })
      .catch(() => console.log('查询用户失败'));
  };

  onCancel = () => {
    this.setState({ visible: false, userList: [], userTree: {}, selectedList: [], searchKeyWords: '' });
  };

  onSubmit = () => {
    const { selectedList } = this.state;
    const { onOk } = this.props;
    if (this.countSelectedUser()) {
      let target = [];
      for (let i = 0; i < selectedList.length; i++) {
        let item = JSON.parse(JSON.stringify(selectedList[i]));
        target.push(item);
      }
      onOk(target);
      this.onCancel();
    } else {
      Tip.warning('请至少选择一人');
    }
  };


  // 下一级
  toChildren = group => {
    const { currentGroups } = this.state;
    currentGroups.push(group);
    this.setState({ currentGroups });
  };

  // 返回上级
  toParent = () => {
    const { currentGroups } = this.state;
    currentGroups.pop();
    this.setState({ currentGroups });
  };

  // 选中用户/分组
  addSelected = item => {
    const { selectedList } = this.state;
    if (!this.isChecked(item)) {
      selectedList.push(item);
      this.setState({ selectedList });
    }
  };

  // 移除选中的用户/分组
  removeSelected = user => {
    const { selectedList } = this.state;
    for (let i = 0; i < selectedList.length; i++) {
      if (selectedList[i].id === user.id && selectedList[i].type === user.type) {
        selectedList.splice(i, 1);
        break;
      }
    }
    this.setState({ selectedList });
  };

  // 选择/取消
  selectItem = item => {
    if (this.isChecked(item)) {
      this.removeSelected(item);
    } else {
      this.addSelected(item);
    }
  };

  // 全选/取消
  selectAll = tree => {
    if (this.isCheckedAll(tree)) {
      if (tree && tree.children && tree.children.length) {
        for (let i = 0; i < tree.children.length; i++) {
          this.removeSelected(tree.children[i]);
        }
      }
    } else {
      if (tree && tree.children && tree.children.length) {
        for (let i = 0; i < tree.children.length; i++) {
          this.addSelected(tree.children[i]);
        }
      }
    }
  };

  // 获取分组下所有用户数量
  countUserForItem = item => {
    if (item && item.type === USER) {
      return 1;
    } else if (item && item.type === GROUP) {
      let res = 0;
      let list = this.groupToList(item);
      for (let i = 0; i < list.length; i++) {
        res = res + this.countUserForItem(list[i]);
      }
      return res;
    }
    return 0;
  };

  // 树转为列表
  groupToList = group => {
    let list = [];
    if (group.children && group.children.length) {
      for (let i = 0; i < group.children.length; i++) {
        list.push(group.children[i]);
        if (group.children[i].type === GROUP) {
          list.push(group.children[i]);
          let parts = this.groupToList(group.children[i]);
          list.push(parts);
        }
      }
    }
    return list;
  };

  // 获取已选人员总数
  countSelectedUser = () => {
    let res = 0;
    const { selectedList } = this.state;
    for (let i = 0; i < selectedList.length; i++) {
      res += this.countUserForItem(selectedList[i]);
    }
    return res;
  };

  // 搜索框改变事件
  changeKeyword = keyword => {
    this.setState({ searchKeyWords: keyword });
    if (keyword && keyword.length) {
      if (this.state.config.getUserListUrl) {
        searchUser(this.state.config.getUserListUrl, keyword)
          .then(res => {
            this.setState({ userList: res });
          })
          .catch(() => console.log('查询用户出错'));
      } else {
        let userList = [];
        let userId = {};
        tools.recursive(this.state.userTree).map(e => {
          console.log(e);
          if (e.type === USER && e.name.indexOf(keyword.trim()) !== -1) {
            if (!userId[e.id]) {
              userId[e.id] = 1;
              userList.push(e);
            }
          }
          return e;
        });
        this.setState({ userList });
      }
    } else {
      this.setState({ userList: [] });
    }
  };

  // 是否选择
  isChecked = item => {
    const { selectedList } = this.state;
    for (let i = 0; i < selectedList.length; i++) {
      if (selectedList[i].id === item.id && selectedList[i].type === item.type) {
        return true;
      }
    }
    return false;
  };

  // 是否全选
  isCheckedAll = tree => {
    let res = false;
    if (tree && tree.children && tree.children.length) {
      res = true;
      for (let i = 0; i < tree.children.length; i++) {
        if (!this.isChecked(tree.children[i])) {
          res = false;
          break;
        }
      }
    }
    return res;
  };

  render() {
    const { userTree, searchKeyWords, userList, currentGroups, selectedList, visible } = this.state;

    const renderList = (data, closeable) => {
      if (data && data instanceof Array) {
        if (!data.length) {
          return null;
        }
        if (closeable) {
          return data.map((item, index) => (
            <div key={item.id} className="select-record">
              <div className="record-select-name">{item.name}</div>
              <a className="record-close" title="移除" onClick={() => this.removeSelected(item)}>
                <img src={ImageConsts.common.remove} alt="" />
              </a>
            </div>
          ));
        } else {
          return data.map((user, index) => (
            <div key={user.id} className="select-record">
              <Radio value={user.id} onClick={() => this.selectItem(user)} checked={this.isChecked(user)}>
                {user.name}
              </Radio>
            </div>
          ));
        }
      } else if (data instanceof Object) {
        if (data.id === undefined) {
          return null;
        }
        return data.children.map((item, index) => {
          if (item.type === GROUP) {
            return (
              <div key={item.id} className="select-record">
                <Radio value={item.id} onClick={() => this.selectItem(item)} checked={this.isChecked(item)}>
                  {`${item.name}（${this.countUserForItem(item)}）`}
                </Radio>
                <div className="group-icon">
                  {this.isChecked(item) ? (
                    <img src={ImageConsts.common.agency} alt="" />
                  ) : (
                    <a title="下-级" onClick={() => this.toChildren(item)}>
                      <img src={ImageConsts.common.agency} alt="" />
                    </a>
                  )}
                </div>
              </div>
            );
          } else if (item.type === USER) {
            return (
              <div key={item.id} className="select-record">
                <Radio value={item.id} onClick={() => this.selectItem(item)} checked={this.isChecked(item)}>
                  {item.name}
                </Radio>
              </div>
            );
          } else {
            return undefined;
          }
        });
      }
    };

    return (
      <CommonModal
        modalClass="cm-share-modal"
        width={537}
        visible={visible}
        onCancel={() => this.onCancel()}
        onOk={() => this.onSubmit()}
        title="人员选择"
      >
        <div className="cm-share-body">
          {currentGroups && currentGroups.length ? (
            <div className="body-left">
              <div className="group-title handle-prompt" onClick={() => this.toParent()}>
                <Icon type="left" />
                {currentGroups[currentGroups.length - 1].name}
              </div>
              <Scrollbars className="scroll-list">
                {currentGroups[currentGroups.length - 1].children && currentGroups[currentGroups.length - 1].children.length ? (
                  <div className="select-record">
                    <Radio
                      value=""
                      onClick={() => this.selectAll(currentGroups[currentGroups.length - 1])}
                      checked={this.isCheckedAll(currentGroups[currentGroups.length - 1])}
                    >
                      全选
                    </Radio>
                  </div>
                ) : null}
                {renderList(currentGroups[currentGroups.length - 1])}
              </Scrollbars>
            </div>
          ) : searchKeyWords && searchKeyWords.length ? (
            <div className="body-left">
              <div className="group-search">
                <Input prefix={<Icon type="search" />} placeholder="搜索" value={searchKeyWords} onChange={e => this.changeKeyword(e.target.value)} />
              </div>
              {userList && userList.length ? (
                <Scrollbars className="scroll-list">{renderList(userList)}</Scrollbars>
              ) : (
                <div className="search-prompt">没有匹配到任何数据</div>
              )}
            </div>
          ) : (
            <div className="body-left">
              <div className="group-search">
                <Input prefix={<Icon type="search" />} placeholder="搜索" value={searchKeyWords} onChange={e => this.changeKeyword(e.target.value)} />
              </div>
              <Scrollbars className="scroll-list">
                {userTree && userTree.length ? (
                  <Collapse activeKey={[userTree[0].id]} onChange={key => console.log(key)}>
                    {userTree.map(tree => (
                      <Panel header={tree.name} key={tree.id} expandIcon={<Icon type="caret-right" />} closeIcon={<Icon type="caret-down" />}>
                        {tree.children && tree.children.length ? (
                          <div className="select-record">
                            <Radio value="" onClick={() => this.selectAll(tree)} checked={this.isCheckedAll(tree)}>
                              全选
                            </Radio>
                          </div>
                        ) : null}
                        {renderList(tree)}
                      </Panel>
                    ))}
                  </Collapse>
                ) : null}
              </Scrollbars>
            </div>
          )}
          <div className="cm-share-hdivider" />
          <div className="body-right">
            <div className="group-title">已选（{this.countSelectedUser()}）</div>
            <Scrollbars className="scroll-list">{renderList(selectedList, true)}</Scrollbars>
          </div>
        </div>
      </CommonModal>
    );
  }
}

export default UserSelector;
