import React from 'react';
import { Button, Input, Modal, Table } from 'antd';
import { networkUtils, config } from '@utils';
import SearchBar from '../SearchBar';

const {api} = config;
const {common} = api;
const {bidGroup} = common;

class GroupModal extends React.PureComponent {
  componentWillReceiveProps = (nextProps) => {
    if (nextProps.visible) {
      // this.fetchList({ productCode, faultModeCode, ouId });
      this.fetchList();
    }
  };

  onFilterChange = (value) => {
    const {fetchData, pagination} = this.state;
    const pager = Object.assign({}, pagination);
    pager.current = 1; // 回到第一页

    // console.log(value)
    const newFetchData = Object.assign({}, fetchData, {
      offset: 0, // 回到第一页
      limit: fetchData.limit,
      sortBy: fetchData.sortBy,
      sortDirection: fetchData.sortDirection,
      ...value,
    });

    this.setState({
      pagination: pager,
      fetchData: newFetchData,
      // selectedRows: [],
    }, () => {
      this.fetchList();
    });
  };
  handleTableChange = (pagination, filters, sorter) => {
    const pager = Object.assign({}, this.state.pagination);
    const {fetchData} = this.state;
    const {rowKey, sortBy, sortDirection} = this.props;

    pager.current = pagination.current;

    const newFetchData = Object.assign({}, fetchData, {
      limit: pagination.pageSize,
      offset: (pagination.current - 1) * pagination.pageSize,
      sortBy: sorter.field || sortBy || rowKey,
      sortDirection: sorter.order === 'descend' ? 'DESC' : (sorter.order === 'ascend' ? 'ASC' : sortDirection),
      ...filters,
    });

    this.setState({
      pagination: pager,
      fetchData: newFetchData,
      // selectedRows: [],
    }, () => {
      this.fetchList();
    });
  };
  fetchList = (params) => {
    const filter = this.props.filter;
    this.setState({fetchingTable: true});

    // 对于Cascader的数据清洗
    const newFetchData = {};
    const {fetchData}: any = this.state;
    fetchData.cccCode &&
    fetchData.cccCode.map((code, index) => {
      newFetchData['c' + (index + 1) + 'Code'] = code;
    });

    networkUtils.request({
      method: 'get',
      url: '/api/source-mgmt/bid-mgmt/bidGroup',
      // url: bidGroup[this.props.apiName],
      data: {
        ...this.state.fetchData,
        ...filter,
        ...params,
        ...newFetchData,
      },
    }).then((data) => {
      if (data.success) {
        this.setState({
          dataSource: data.data.rows,
          total: data.data.total,
          fetchingTable: false,
          // selectedRows: [],
        });
      } else {
        throw data;
        ;
      }
    });
  };
  // fetchSelected = (row) => {
  //   this.setState({
  //     selected: row,
  //   });
  // };

  constructor(props) {
    super(props);

    const {
      sortBy,
      sortDirection,
      rowKey,
    } = props;

    this.state = {
      fetchingSelected: false,
      fetchData: {
        offset: 0,
        limit: 10,
        sortBy: sortBy || rowKey,
        sortDirection: sortDirection || 'ASC',
      },
      selectedRows: [],
      pagination: {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30', '50', '100'],
        showTotal: total => `共 ${total} 条`,
        defaultPageSize: 10,
        defaultCurrent: 0,
        // current: 0,
        total: this.props.total,
      },
      dataSource: [],
      total: 0,
      fetchingTable: false,
    };
  }

  clearSelection = () => {
    // console.log('clear');
    this.setState({
      selectedRows: [],
    });
  };

  render() {
    const {dataSource, total, fetchingTable, selectedRows, pagination} = this.state;
    const {visible, onOk, onCancel, modalProps, value} = this.props;

    pagination.total = total;

    const handleOk = () => {
      // console.log(this.state.selectedRows[0]);
      // onOk(this.state.selectedRows[0].id, this.state.selectedRows[0].itemCode, this.state.selectedRows[0].itemName);
      // onOk(this.state.selectedRows[0].id, this.state.selectedRows[0].outerCode, this.state.selectedRows[0].itemName);
      onOk(this.state.selectedRows[0].id, this.state.selectedRows[0].itemC3Id, this.state.selectedRows[0].groupName);
      // onOk(dataSource.filter(l => l.cardCode === selectedRows[0])[0].id, selectedRows[0]);
    };

    const handleCancel = () => {
      onCancel();
    };

    const modalOpts = {
      ...modalProps,
      visible,
      onOk: handleOk,
      maskClosable: false,
      title: value && value.name ? `选择小组 (已选: ${value.name || ''} ${value.code || ''})` : `选择小组`,
      onCancel: handleCancel,
      footer: [
        <Button key="back" onClick={handleCancel}>取消</Button>,
        <Button
          key="submit"
          type="primary"
          loading={false}
          onClick={handleOk}
          disabled={!selectedRows.length}
        >确定</Button>,
      ],
    };

    const filter = [{
      title: '小组编号',
      dataIndex: 'id',
      tag: <Input placeholder="请输入名称/编号"/>,
      options: {
        initialValue: '',
      },
    }, {
      title: '小组名称',
      dataIndex: 'groupName',
      tag: <Input placeholder="请输入小组名称"/>,
    }];

    const rowSelection = {
      // fixed: true,
      type: 'radio',
      selectedRowKeys: selectedRows.map(r => r.id),
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
        });
      },
    };

    const tableProps = {
      rowSelection,
      rowKey: 'id',
      size: 'small',
      bordered: true,
      onRow: (record, index) => {
        return {
          onClick: (record, index) => {
            // this.fetchSelected(record);
          },
          onMouseEnter: () => {  // 鼠标移入行
          },
          onDoubleClick: () => {
            // this.props.enableDoubleClick !== false && this.handleRowDoubleClick(record, index);
          },
        };
      },
      scroll: {x: '100%', y: 300},
      dataSource,
      total,
      loading: fetchingTable,
      onChange: this.handleTableChange,
      pagination,
      columns: [{
        title: '小组编号',
        dataIndex: 'id',
        className: 'alignCenter',
        width: '30%',
      }, {
        title: '小组名称',
        dataIndex: 'groupName',
        className: 'alignCenter',
        width: '30%',
      }, {
        title: '品类名称',
        dataIndex: 'itemC3Name',
        className: 'alignCenter',
        width: '30%',
      }],
    };

    return (<Modal
        wrapClassName="vertical-center-modal"
        width="85%"
        {...modalOpts}
      >
        <SearchBar
          onFilterChange={this.onFilterChange}
          filter={filter}
        />
        <Table {...tableProps} />
      </Modal>
    );
  }
}

export default GroupModal;
