import React from 'react';
import { Button, Card, Col, Icon, Input, Modal, Row, Table, Tree } from 'antd';
import { config, networkUtils } from '@utils';

const { api } = config;
const { common } = api;
const { mdata } = api;
const { tree } = common;
const { emps, orgs } = tree;

const TreeNode = Tree.TreeNode;

class TreeTableView extends React.PureComponent {

  constructor(props) {
    super(props);

    const {
      limit,
      offset,
    } = props;

    this.myInput = React.createRef();

    this.state = {
      fetching: false,
      tableFetching: false,
      modalVisible: false,
      selected: {},
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      dataTree: [],
      tableData: [],
      orgId: null,
      filter: {},

      pagination: {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30', '50', '100'],
        showTotal: total => `共 ${total} 条`,
        defaultPageSize: 20,
        defaultCurrent: 1,
        pageSize: parseInt(limit, 20) || 20,
        current: (parseInt(offset, 20) / limit) + 1 || 1,
        total: 0,
      },
    };
  }

  componentWillReceiveProps = (nextProps) => {
    // 外部企业组件onChange后，选择了不同企业时
    if (nextProps.ouId != this.state.selected.ouId) {
      this.emitEmpty();
    }
    // 点击修改、查看，非新增时
    nextProps.empId && !this.state.selected.id && this.fetchEmployee(nextProps.empId);
  };

  fetchData = (nextProps) => {
    nextProps.ouId && this.fetchTree(nextProps.ouId);
  };

  fetchTable = () => {
    this.setState({ tableFetching: true }, () => {
      const { current, pageSize } = this.state.pagination;
      networkUtils.request({
        method: 'get',
        url: emps,
        data: {
          offset: (current - 1) * pageSize,
          limit: pageSize,
          ouId: this.props.ouId,
          orgId: this.state.orgId,
          ...this.state.filter,
        }
      }).then((data) => {
        if (data.success) {
          this.setState({
            tableData: data.data.rows,
            tableFetching: false,
            pagination: {
              ...this.state.pagination,
              total: data.data.total,
            }
          });
        } else {
          throw data;
        }
      });

    });

  };

  fetchTree = (ouId) => {
    this.setState({ fetching: true });
    networkUtils.request({
      method: 'get',
      url: orgs.replace('{id}', ouId),
    }).then((data) => {
      if (data.success) {
        this.setState({
          dataTree: data.data || [],
          fetching: false,
        });
      } else {
        throw data;
      }
    });
  };

  onSelectTree = (selectedKeys, info) => {
    this.myInput.current.input.value = null;
    // console.log(this.myInput.current);
    selectedKeys.length && this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1,
      },
      orgId: selectedKeys[0],
      filter: {}
    }, () => {
      this.fetchTable();
    });
  };

  onSelectRow = (row) => {
    this.setState({
      selected: row,
      modalVisible: false,
    });
  };

  openModal = () => {
    this.setState({
      modalVisible: true,
    });
    this.fetchData(this.props);
  };

  handleCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };

  handleOk = () => {
    this.props.onChange(this.state.selected.id);
    this.setState({});
  };

  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  emitEmpty = () => {
    this.setState({
      fetching: false,
      tableFetching: false,
      modalVisible: false,
      selected: {},
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      dataTree: [],
      tableData: [],
      orgId: null,
      filter: {},
    });
  };

  fetchEmployee = (id) => {
    networkUtils.request({ method: 'get', url: `${mdata.emp}/${id}` }).then((data) => {
      if (data.success) {
        this.setState({
          selected: data.data
        });
      } else {
        throw data;
      }
    });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const pager = Object.assign({}, this.state.pagination);
    const { current, pageSize } = pagination;
    pager.current = pagination.current;
    pager.pageSize = pagination.pageSize;

    this.setState({
      pagination: pager,
    }, () => {
      this.fetchTable({
        offset: (current - 1) * pageSize,
        limit: pageSize,
      });
    });
  };

  render() {
    const { dataTree, modalVisible, selected, searchValue, expandedKeys, autoExpandParent, fetching, tableData, tableFetching } = this.state;

    const { title, value, disabled, orgId } = this.props;

    const suffix = selected.empName && !disabled ? <Icon type="close-circle" onClick={this.emitEmpty}/> : null;

    const loop = data => data.map((item) => {
      const index = item.orgName.indexOf(searchValue);
      const beforeStr = item.orgName.substr(0, index);
      const afterStr = item.orgName.substr(index + searchValue.length);
      const orgName = index > -1 ? (
        <span>
          {beforeStr}
          <span style={{ color: '#f50' }}>{searchValue}</span>
          {afterStr}
        </span>
      ) : <span>{item.orgName}</span>;
      if (item.children) {
        return (
          <TreeNode key={item.id} title={orgName}>
            {loop(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={orgName}
                       icon={selected.orgId == item.id ? <Icon type="check"/> : null}
      />;
    });

    const tableProps = {
      rowKey: 'id',
      scroll: { x: '100%', y: 410 },
      size: 'small',
      bordered: true,
      columns: [{
        title: '选择',
        dataIndex: 'choose',
        width: '5%',
        render: (value, row, index) => {
          return <Button
            disabled={row.userId !== null}
            icon="check"
            shape="circle"
            size="small"
            onClick={() => this.onSelectRow(row)}
          />;
        },
      }, {
        title: '员工编号',
        dataIndex: 'empCode',
        width: '10%',
      }, {
        title: '姓名',
        dataIndex: 'empName',
        width: '10%',
      }, {
        title: '员工类型',
        dataIndex: 'empTypeName',
        width: '10%',
      }, {
        title: '状态',
        dataIndex: 'empStatusName',
        width: '5%',
      }],
      filter: null,
      dataSource: tableData,
      loading: tableFetching,
      onChange: this.handleTableChange,
      pagination: this.state.pagination,
    };


    return (
      <Col>
        <Input
          addonAfter={<Icon type="search" onClick={!disabled ? this.openModal : void 0}/>}
          disabled={disabled}
          suffix={suffix}
          data-id={selected && selected.id ? selected.id : value}
          value={(selected && selected.empName) || null}
          style={{ width: '100%' }}
          readOnly={true}
        />
        <Modal
          wrapClassName="vertical-center-modal"
          width="80%"
          maskClosable={false}
          visible={modalVisible}
          title={title || '树形选择'}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          afterClose={this.handleOk}
          footer={null}
        >
          {/*<Row style={{ marginBottom: 10 }}>*/}

          {/*</Row>*/}
          <Row gutter={12}>
            <Col span={6}>
              <Card
                title={false}
                loading={fetching}
                bodyStyle={{ padding: 10 }}
                style={{ maxHeight: 500, height: 500, overflowY: 'scroll' }}
              >
                <Tree
                  showIcon
                  onSelect={this.onSelectTree}
                  onExpand={this.onExpand}
                  expandedKeys={expandedKeys}
                  autoExpandParent={autoExpandParent}
                >
                  {dataTree && loop(dataTree)}
                </Tree>
              </Card>

            </Col>
            <Col span={18}>
              <Input style={{ width: '50%' }} ref={this.myInput} placeholder={'员工编号/名称'} onPressEnter={(e) => {
                e.persist();
                this.setState({
                  filter: {
                    empCodeName: e.target.value,
                  },
                  pagination: {
                    ...this.state.pagination,
                    current: 1,
                  }
                }, () => {
                  this.fetchTable();
                });
              }}/>
              <Table {...tableProps} />
            </Col>
          </Row>
        </Modal>
      </Col>
    );
  }
}

export default TreeTableView;
