import React, { Component } from "react";
import { Modal, Layout, Tree, List, Table, Divider, Icon, Input } from "antd";
import { connect } from "dva";

import SearchTree from "../../Tree/SearchTree/index";
import styles from "./index.less";
import { getDefaultCurrency } from "@/utils/request.js";
import { goodsVersion } from '@/utils/common';

// import { treeDatas, ListDatas } from "./mock.json";

const { Sider, Content } = Layout;
const { Search } = Input;

const stateDataKey = "treeListData";
const currencyPriceScale = getDefaultCurrency().currencyPriceScale || 2;
/**
 * 左树右表参照框
 */
class TreeListModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      selectedRows: []
    };
    this.columns = [
      {
        title: "商品编码",
        dataIndex: "code",
        key: "code",
        render: text => <a href="#">{text}</a>
      },
      {
        title: "商品名称",
        dataIndex: "displayName",
        width: "150px",
        key: "displayName",
        render: (text) => (
          <div className={styles.goodsName}>
            <span title={text}>{text}</span>
          </div>
        )
      },
      {
        title: "价格",
        dataIndex: "baseDiscountPrice",
        key: "baseDiscountPrice",
        render: (text, record, index) => (
          <span style={{ color: "#E14C46" }}>
            ￥{(record.baseDiscountPrice || 0).toFixed(currencyPriceScale)}/{record.basicUnitName}
          </span>
        )
      },
      {
        title: "版本号",
        dataIndex: "version",
        key: "version",
        render: (text, record, index) => (
          <span>
            {goodsVersion(record.version)}
          </span>
        )
      },
      {
        title: "所属产品",
        dataIndex: "productName",
        width: "120px",
        key: "productName",
        render: (text) => (
          <div className={styles.productName}>
            <span title={text}>{text}</span>
          </div>
        )
      },
      {
        title: "计量单位",
        dataIndex: "assistUnitName",
        key: "assistUnitName"
      }
    ];
  }
  // componentWillMount() {
  //   this.getListDatas();
  // }
  componentWillReceiveProps(nextProps) {
    if ("supplierId" in nextProps) {
      // 判断供应商发生变化，重新查询
      const { supplierId } = this.props;
      if (supplierId != nextProps.supplierId) {
        this.getListDatas({
          search_supplierId: nextProps.supplierId
        });
      }
    }
  }
  onChangeHandle(selectedRowKeys, selectedRows) {
    this.setState({
      selectedRowKeys: selectedRowKeys,
      selectedRows: selectedRows
    });
  }
  onPaginationChange(page, pageSize = 10) {
    this.getListDatas({
      page: page - 1,
      pageSize: pageSize || 10
    });
  }
  getListDatas(params) {
    const { dispatch, listUrl, supplierId, saleModel } = this.props;
    this.setState({
      selectedRowKeys: []
    });
    params = params || {};
    params.page = params.page ? params.page : 0;
    params.size = params.pageSize ? params.pageSize : 10;
    params["search_saleModel"] = saleModel || "";
    if (!params["search_supplierId"]) {
      params["search_supplierId"] = supplierId || "";
    }
    if (!listUrl) return;
    dispatch({
      type: "global/refListServer",
      payload: { url: listUrl, key: stateDataKey, params }
    });
  }
  handleSearch(value) {
    this.getListDatas({ search_keywords: value });
  }
  handleTreeSelect = (m, info) => {
    this.getListDatas({ search_goodsCategoryIds: m });
  };
  handleOkBtn = () => {
    const selectedRows = this.state.selectedRows;
    this.props.dispatch({
      type: "global/treeListSelectedRows",
      selectedRows
    });
    this.hideModal();
    const confirmFun = this.props.onConfirm;
    confirmFun(selectedRows);
  };

  showModal = () => {
    this.props.dispatch({
      type: "global/treeListVisible",
      payload: true
    });
  };
  hideModal = () => {
    this.props.dispatch({
      type: "global/treeListVisible",
      payload: false
    });
  };

  render() {
    const { selectedRowKeys } = this.state;
    const { listDatas } = this.props;
    // todo...
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onChangeHandle.bind(this),
      getCheckboxProps: record => ({
        disabled: !record.stock || !record.baseDiscountPrice || parseFloat(record.stock || "0") <= 0
      })
    };
    const columns = this.columns;
    let total = 0;
    let pageSize = 10;
    if (listDatas) {
      total = listDatas.totalElements || 0;
      pageSize = listDatas.size || 10;
    }
    const paginationSetting = {
        size: "small",
        pageSize: pageSize,
        total: total,
        showTotal: this.showTotalFun,
        onChange: this.onPaginationChange.bind(this)
    };
    return (
      <div>
        <Modal
          title={this.props.title || "请选择"}
          visible={this.props.visible || false}
          onOk={this.handleOkBtn.bind(this)}
          onCancel={this.hideModal}
          okText="确认"
          cancelText="取消"
          width={1080}
          className={styles.modal}
        >
          <Layout>
            <Sider className={styles.treeSider}>
              <SearchTree
                onSelect={this.handleTreeSelect.bind(this)}
                treeUrl={this.props.treeUrl}
                treeKeyword={this.props.treeKeyword}
                treeTitleword={this.props.treeTitleword}
              />
            </Sider>
            <Content style={{ backgroundColor: "white", paddingLeft: 18 }}>
              <Search
                className={styles.search}
                placeholder="输入商品编码/名称"
                enterButton="搜索"
                onSearch={this.handleSearch.bind(this)}
              />
              <Table
                columns={
                  columns || [
                    { title: "请配置表格列", dataIndex: "name", key: "0" }
                  ]
                }
                dataSource={(this.props.listDatas || {}).content}
                className={styles.table}
                pagination={paginationSetting}
                rowSelection={rowSelection}
              />
            </Content>
          </Layout>
        </Modal>
      </div>
    );
  }
}
export default connect(state => ({
  ...state,
  listDatas: state.global[stateDataKey],
  visible: state.global.treeListVisible
}))(TreeListModal);
