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

class SupplierModal 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 });
    networkUtils.request({
      method: 'get',
      url: '/api/supp/supps',
      data: {
        ...this.state.fetchData,
        ...filter,
        ...params,
      },
    }).then((data) => {
      if (data.success) {
        this.setState({
          dataSource: data.data.rows,
          total: data.data.total,
          fetchingTable: false,
          // selectedRows: this.state.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].suppCode, this.state.selectedRows[0].suppName);
      // 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: 'suppCodeName',
      tag: <Input placeholder="请输入名称/编号"/>,
    }, {
      title: '供货区域',
      dataIndex: 'region',
      tag: <SuggestSelect apiName="regions"/>,
    },
      // {
      //   title: '状态',
      //   dataIndex: 'suppStatus',
      //   tag: <UdcSelect domain="SUPP" code="SUPP_STATUS" />,
      // }
    ];

    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: 'suppCode',
        className: 'alignCenter',
        width: '15%',
      }, {
        title: '名称',
        dataIndex: 'suppName',
        className: 'alignLeft',
        width: '20%',
      }, {
        title: '状态',
        dataIndex: 'suppStatusName',
        className: 'alignCenter',
        width: '10%',
      }, {
        title: '供货区域',
        dataIndex: 'regionName',
        className: 'alignCenter',
        width: '30%',
      }, {
        title: '供应商性质',
        dataIndex: 'gysxzName',
        className: 'alignCenter',
        width: '10%',
      }, {
        title: '最新绩效',
        dataIndex: 'scoreGradeName',
        className: 'alignCenter',
        width: '10%',
      }],
    };

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

export default SupplierModal;
