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

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

class ItemModal 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/ui/suggest/items',
      url: magnifier[this.props.apiName || 'items'],
      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);
      // 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(dataSource.filter(l => l.cardCode === selectedRows[0])[0].id, selectedRows[0]);

      const { selectedRows } = this.state;
      const rows = selectedRows.length > 0 ? selectedRows.map(row => {
        return {
          id: row.id,
          code: row.outerCode,
          name: row.itemName,
        };
      }) : [];
      onOk(rows);
    };

    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: 'itemCode',
      tag: <Input placeholder="请输入名称/编号"/>,
    }, {
      title: '物料类别',
      dataIndex: 'cccCode',
      tag: <CascaderItem placeholder="选择大类/中类/小类"/>,
    }];

    const rowSelection = {
      // fixed: true,
      type: this.props.type === 'multiple' ? 'checkbox' : '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: 350 },
      dataSource,
      total,
      loading: fetchingTable,
      onChange: this.handleTableChange,
      pagination,
      columns: [{
        title: '编号',
        dataIndex: 'outerCode',
        width: '9%',
      }, {
        title: '临时编号',
        dataIndex: 'itemCode',
        width: '10%',
      }, {
        title: '名称',
        dataIndex: 'itemName',
        width: '13%',
      }, {
        title: '缩写',
        dataIndex: 'memCode',
        width: '6%',
      }, {
        title: '品牌',
        dataIndex: 'brandName',
        width: '6%',
      }, {
        title: '规格型号',
        dataIndex: 'spec',
        width: '6%',
      }, {
        title: '状态',
        dataIndex: 'itemStatusName',
        width: '6%',
      }, {
        title: '大类',
        dataIndex: 'c1Name',
        width: '6%',
      }, {
        title: '中类',
        dataIndex: 'c2Name',
        width: '6%',
      }, {
        title: '品类',
        dataIndex: 'c3Name',
        width: '6%',
      }, {
        title: '供货厂家数',
        dataIndex: 'suppNum',
        width: '7%',
      }, {
        title: '询价周期(月)',
        dataIndex: 'pricePeriod',
        width: '7%',
      }, {
        title: '主计量单位',
        dataIndex: 'uom',
        width: '6%',
      }, {
        title: '物料属性',
        dataIndex: 'itemPropName',
        width: '6%',
      }],
    };

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

export default ItemModal;
