/**
 * Created by baoyinghai on 4/20/17.
 */
import React from 'react';
import { VIEW, EDIT } from '../../constant';
import { LIST_SELECTTYPE, BUTTON_POSITION, BUTTON_RELATEDDATA, LIST_PATTERN } from '../../../../constant/dictCodes';
import { arr2obj, handleFilterItems, handleOrderItems, renderColumn } from '../../../list/util';
import { Table, Button, Row, Col, Tooltip } from '../../../../../components/mxa';
import { getParamByBindParameters } from '../../../../utils/ParamHelper';
import { showModal } from '../../../../pageContainer/ModalWrapper';

class InnerList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      dataSource: [],
      selectedRows: [],
      selectedRowKeys: [],
      rowSelection: {}
    };
    // this.mainEntityKey  主键
  }

  _onChange = () => {
    if (!this.mainEntityKey) {
      console.error('mainEntityKey can not be null');
    } else {
      const { onChange } = this.props;
      onChange && onChange(this.state.dataSource.map(r => r[this.mainEntityKey]));
    }
  };

  _onRowClick = (record, index) => {
    if (this.state.selectedType === LIST_SELECTTYPE.INLINE) return;
    console.log('onRowClick ==> ', record, index);

    const selectedIndex = this.state.selectedRowKeys.indexOf(record.key);
    if (selectedIndex > -1) {
      this.setState({
        selectedRowKeys: this.state.selectedRowKeys.filter(item => item !== record.key),
        selectedRows: this.state.selectedRows.filter(item => item.key !== record.key),
      });
    } else if (this.state.selectedType === LIST_SELECTTYPE.RADIO) {
      this.setState({
        selectedRowKeys: [record.key],
        selectedRows: [record],
      });
    } else {
      this.setState({
        selectedRowKeys: this.state.selectedRowKeys.concat(record.key),
        selectedRows: this.state.selectedRows.concat(record),
      });
    }
    // TODO: 触发onchange事件
  };

  _getParamFromQuery = bindParameters => getParamByBindParameters(this.props.query || [], bindParameters);

  _getParamFromDetail = bindParameters => getParamByBindParameters(this.props.formDataSource.detailResult || [], bindParameters);

  _createParam = bindParameters => Object.assign({}, this._getParamFromQuery(bindParameters), this._getParamFromDetail(bindParameters));


  _renderColumn = (text, fieldContent) => {
    const temp = renderColumn(text, fieldContent);
    let tdRender = (
      <span>{temp}</span>
    );
    if (typeof temp === 'string' && temp.length > 20) {
      tdRender = (
        <Tooltip title={temp} placement="top">
          <span>{temp.substring(0, 18) + '...'}</span>
        </Tooltip>
      );
    }
    return tdRender;
  };

  _processColumns = fields => {
    const columns = [];
    if (fields && fields.length > 0) {
      const fieldsObject = arr2obj(fields, 'name');
      fields.forEach((item, index) => {
        if (item.isMainEntityKey) this.mainEntityKey = item.name;
        columns.push({
          width: (item.displayColumnLength || 18) * 12,
          key: index,
          title: item.description,
          dataIndex: item.name,
          render: text => this._renderColumn(text, fieldsObject[item.name])
        });
      });
    }
    return columns;
  };

  _addKey = dataSource => dataSource && dataSource.map((item, index) => ({ ...item, key: index }));

  _processRowSelection = selectType => {
    return {
      type: LIST_SELECTTYPE.INLINE,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log('onChange ==> ', `selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        this.setState({ selectedRowKeys, selectedRows });
      },
      onSelect: (record, selected) => {
        console.log('onSelect ==> ', record, selected);
        // this.setState({ selectedRows });
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        console.log('onSelectAll ==> ', selected, selectedRows, changeRows);
        let selectedRowKeys = [];
        if (selected) {
          selectedRowKeys = selectedRows.map(row => row.key);
        }
        this.setState({ selectedRows, selectedRowKeys });
      },
      selectedRowKeys: this.state.selectedRowKeys,
    };
  };

  _appendNoPaggingParams = param => {
    return { ...param, listInstruction: LIST_PATTERN.NOPAGING };
  };

  componentDidMount() {
    const { selectedItemAction } = this.props;
    this.props.exec(() => this.props.fetch(this.props.selectedItemAction.actionLink, this._appendNoPaggingParams(this._createParam(selectedItemAction.bindParameters))).then(response => {
      const { pageResult, fields, selectType } = response;
      const dataSource = pageResult.contentList;
      const columns = this._processColumns(fields);
      this.setState({
        columns,
        dataSource: this._addKey(dataSource),
        selectType
      }, () => this._onChange());
    }));
  }

  _callback = (value, selectType) => {
    this.setState({
      dataSource: value
    }, () => this._onChange());
  };

  _initExtraData = () => {
    if (this.mainEntityKey && this.state.dataSource) {
      return this.state.dataSource.map(item => item[this.mainEntityKey]);
    }
    return null;
  };

  _showModal = () => {
    const { allItemAction } = this.props;
    const p = { requestParamsBean: { listInstruction: LIST_PATTERN.NOPAGING } };
    p.isModalInput = true;
    showModal(Object.assign({}, this._createParam(allItemAction.bindParameters), p), allItemAction.templateType, allItemAction.actionLink, this._callback, this._initExtraData());
  };

  _renderToolBar = () => {
    return (
      <div className="inner-table-tool-bar">
        <a onClick={this._showModal}>修改</a>
      </div>
    );
  };

  render() {
    const rowSelection = this._processRowSelection(this.state.selectType);
    return (
      <div>
        {this._renderToolBar()}
        <Table
          rowSelection={rowSelection}
          locale={{ emptyText: '无符合条件的相关数据' }}
          columns={this.state.columns}
          dataSource={this.state.dataSource}
          onChange={this._onChange}
          onRowClick={this._onRowClick}
          prefixCls="inner-table"
          isInner={true}
        />
      </div>
    );
  }
}

const compRender = config => {
  const { record = {}, props } = config;
  const { actions } = record.displayComponent;
  const selectedItemAction = actions.filter(i => i.type === 'SelectedItemAction')[0];
  const allItemAction = actions.filter(i => i.type === 'AllItemAction')[0];
  return (
    <InnerList
      query={props.query}
      formDataSource={props.dataSource}
      exec={props.exec}
      fetch={props.fetch}
      selectedItemAction={selectedItemAction}
      allItemAction={allItemAction}
    />
  );
};

export default {
  [VIEW]: () => {
    return (<span>未定义</span>);
  },
  [EDIT]: compRender
};
