import React, { PureComponent } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Row, Col, Select, Tabs, Table, Input, Button, message } from "antd";
import BreadcrumbPackage from "@/components/BreadcrumbPackage/index.js";
import EmptyData from "@/components/EmptyData/index";
import GoodsBuyIpt from "@/components/GoodsBuyIpt/index.js";
import styles from "./index.less";
import { getCustomer, getDefaultCurrency } from "@/utils/request.js";
const TabPane = Tabs.TabPane;
// 获取默认币种
const currency = {
  currencySign: getDefaultCurrency().currencySign || "￥",
  currencyPriceScale: getDefaultCurrency().currencyPriceScale || 2,
  currencyAmountScale: getDefaultCurrency().currencyAmountScale || 2
};

class goodsSupplyDetail extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      castTypeId: "", // 客户费用单类型主键
      financeOrgId: "", // 财务组织
      supplierId: "", // 供货方
      goodsKey: "", // 商品关键字
      cashGoods: [], // 本次兑付商品,
      selectedRowKeys: [], // 货补选择项
      totalAmount: 0 // 兑付合计金额
    };
    this.itemColumns = [
      {
        title: "商品编码",
        dataIndex: "code",
        key: "code",
        width: "20%"
      },
      {
        title: "商品名称",
        dataIndex: "displayName",
        key: "displayName",
        width: "30%"
      },
      {
        title: "库存",
        dataIndex: "stock",
        key: "stock",
        width: "20%",
        className: "alignRight",
        render: (text, record, index) => (
          <span>
            {(text / record.conversionRate).toFixed(record.assistUnitPrecision)}
            <em className={styles.em}>{record.assistUnitName}</em>
          </span>
        )
      },
      {
        title: "单价",
        dataIndex: "baseDiscountPrice",
        key: "baseDiscountPrice",
        width: "20%",
        className: "alignRight",
        render: (text, record, index) => (
          <span>
            <span className={styles.fontRed}>{currency.currencySign}{(+text).toFixed(currency.currencyPriceScale)}</span>
            <em className={styles.em}>/{record.basicUnitName}</em>
          </span>
        )
      },
      {
        title: "",
        dataIndex: "empty",
        width: "10%"
      }
    ];
    this.selectColumns = [
      {
        title: "商品编码",
        dataIndex: "code",
        key: "code",
        width: "15%"
      },
      {
        title: "商品名称",
        dataIndex: "displayName",
        key: "displayName",
        width: "20%"
      },
      {
        title: "库存",
        dataIndex: "stock",
        key: "stock",
        className: "alignRight",
        render: (text, record, index) => (
          <span>
            {(text / record.conversionRate).toFixed(record.assistUnitPrecision)}
            <em className={styles.em}>{record.assistUnitName}</em>
          </span>
        )
      },
      {
        title: "单价",
        dataIndex: "baseDiscountPrice",
        key: "baseDiscountPrice",
        className: "alignRight paddingRight-40",
        render: (text, record, index) => (
          <span>
            <span className={styles.fontRed}>{currency.currencySign}{(+text).toFixed(currency.currencyPriceScale)}</span>
            <em className={styles.em}>/{record.basicUnitName}</em>
          </span>
        )
      },
      {
        title: "兑付订货数量",
        dataIndex: "orderNum",
        key: "orderNum",
        className: "orderNum paddingRight-40",
        render: (text, record, index) => (
          <div
            className={styles.numIptBox}
            style={{ position: "relative", width: "120px" }}
          >
            <div style={{ width: "100px", float: "left" }}>
              <GoodsBuyIpt
                num={record.orderNum}
                onChange={this.buyNumChange.bind(this, index)}
              />
            </div>
            <em className={styles.em} style={{ lineHeight: "30px" }}>
              {record.assistUnitName}
            </em>
          </div>
        )
      },
      {
        title: "主数量",
        dataIndex: "mainNum",
        key: "mainNum",
        className: "alignRight",
        render: (text, record, index) => (
          <span>
            {text}
            <em className={styles.em}>{record.basicUnitName}</em>
          </span>
        )
      },
      {
        title: "兑付金额",
        dataIndex: "amount",
        key: "amount",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={`${styles.amount} ${styles.fontRed}`}>{currency.currencySign}{(+text).toFixed(currency.currencyAmountScale)}</span>
        )
      },
      {
        title: "操作",
        dataIndex: "opration",
        key: "opration",
        className: "alignCenter",
        width: "10%",
        render: (text, record, index) => (
          <span
            className={styles.delButton}
            onClick={this.delClickHandle.bind(this, record)}
          >
            删除
          </span>
        )
      }
    ];
  }
  componentWillMount() {
    const { dispatch, location } = this.props;
    // 先清空信息
    dispatch({
      type: "goodsSupplyDetail/supplyAmountAndGoodsList",
      supplyAmountAndGoodsList: []
    });
    dispatch({
      type: "goodsSupplyDetail/goodsSupplyDetailData",
      goodsSupplyDetailData: []
    });
    const castTypeId = location[`castTypeId`];
    const financeOrgId = location[`financeOrgId`];
    // 如果费用单类型主键为空，则返回列表页面
    if (!castTypeId) {
      dispatch(
        routerRedux.push({
          pathname: "/buyer/goodsSupplyList"
        })
      );
      return false;
    }
    dispatch({
      type: "goodsSupplyDetail/getGoodsSupplyDetailList",
      payload: {
        castTypeId: castTypeId
      }
    });
    this.setState({
      castTypeId: castTypeId,
      financeOrgId: financeOrgId
    });
  }
  onSelectChange(selectedRowKeys, selectedRows) {
    const { cashGoods } = this.state;
    let newCashGoods = cashGoods.concat([]);
    // 判断添加的商品是否重复 todo...
    selectedRows.forEach(addRow => {
      let repeat = false;
      const rate = parseFloat(addRow.conversionRate || "1");
      newCashGoods.forEach(item => {
        // 重复，则忽略
        if (item.id == addRow.id) {
          repeat = true;
        }
      });
      // 不重复，则转换数据，新增商品行
      const translate = {
        orderNum: 1, // 订货数量
        mainNum: rate,
        baseDiscountPrice: addRow.baseDiscountPrice,
        conversionRate: rate, // 单位换算率
        currencyPriceScale: addRow.currencyPriceScale, // 币种单价精度
        currencyAmountScale: addRow.currencyAmountScale, // 币种金额精度
        key: addRow.id
      };
      if (!repeat) {
        newCashGoods = newCashGoods.concat(
          Object.assign({}, addRow, translate)
        );
      }
    });
    const totalAmount = this.computeFun(newCashGoods);
    this.setState({
      totalAmount: totalAmount,
      cashGoods: newCashGoods,
      selectedRowKeys: selectedRowKeys
    });
  }
  onSelectHandle(record, selected, selectedRows) {
    if (!selected) {
      this.removeCashGoods([record]);
    }
  }
  onSelectAllHandle(selected, selectedRows, changeRows) {
    if (!selected) {
      this.removeCashGoods(changeRows);
    }
  }
  // todo...
  validCheckboxProps(record) {
    return {
      disabled: !record.stock || !record.baseDiscountPrice || parseFloat(record.stock || "0") <= 0
    };
  }
  removeCashGoods(rows) {
    const { cashGoods } = this.state;
    if (rows && rows.length > 0) {
      const goodsIds = [];
      rows.forEach(row => {
        goodsIds.push(row.id);
      });
      const newCashGoods = cashGoods.filter(item => {
        return !goodsIds.includes(item.id);
      });
      const totalAmount = this.computeFun(newCashGoods);
      this.setState({
        totalAmount: totalAmount,
        cashGoods: newCashGoods
      });
    }
  }
  // 确认兑付
  confrimCashHandle() {
    const { cashGoods, castTypeId, supplierId, totalAmount } = this.state;
    const { goodsSupplyDetailData, supplyAmountAndGoodsList } = this.props;
    let warnMsg = "";
    if (!supplierId) {
      warnMsg += "请选择供货方！ ";
    }
    if (!cashGoods || cashGoods.length < 1) {
      warnMsg += "请选择本次兑付商品！ ";
    }
    if (
      totalAmount > parseFloat(supplyAmountAndGoodsList.supplementAmount || "0")
    ) {
      warnMsg += "兑付超出，请重新调整！ ";
    }
    if (warnMsg) {
      message.warning(warnMsg);
      return false;
    }
    // todo...
    var cashOrderData = {
      castTypeId: castTypeId, // 客户费用单主键
      saleOrgId: supplierId, // 供货方
      reqOrderItems: cashGoods // 商品信息
    };
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: "/buyer/orderEdit",
        cashOrderData: cashOrderData
      })
    );
  }
  // 供应商改变
  supplierChange(value) {
    const { dispatch } = this.props;
    const { castTypeId, goodsKey, financeOrgId } = this.state;
    // 清空选择的兑付商品
    this.setState({
      supplierId: value,
      goodsKey: "",
      cashGoods: [],
      selectedRowKeys: []
    });
    // 重新查询货补商品todo...
    dispatch({
      type: "goodsSupplyDetail/getSupplyAmountAndGoodsList",
      payload: {
        castTypeId: castTypeId,
        financeOrgId: financeOrgId,
        supplierId: value,
        key: ""
      }
    });
  }
  // 更改兑付订货数量
  buyNumChange(key, num) {
    const { cashGoods } = this.state;
    // todo...
    const rate = parseFloat(cashGoods[key].conversionRate || "1");
    cashGoods[key][`orderNum`] = num;
    cashGoods[key][`mainNum`] = num * rate;
    const totalAmount = this.computeFun(cashGoods);
    this.setState({
      totalAmount: totalAmount,
      cashGoods: cashGoods
    });
  }
  // 删除
  delClickHandle(record) {
    const { cashGoods, selectedRowKeys } = this.state;
    const newCashGoods = cashGoods.filter(
      item => record.id != item.id
    );
    const newSelectedRowKeys = selectedRowKeys.filter(
      item => record.id != item
    );
    const totalAmount = this.computeFun(newCashGoods);
    this.setState({
      totalAmount: totalAmount,
      cashGoods: newCashGoods,
      selectedRowKeys: newSelectedRowKeys
    });
  }
  // 计算行合计、并返回兑付合计金额todo...
  computeFun(cashGoods) {
    let totalAmount = 0;
    cashGoods.forEach(item => {
      const amount =
        parseFloat(item.baseDiscountPrice || "0") * parseFloat(item.mainNum || "0");
      item.amount = amount;
      totalAmount += amount;
    });
    return totalAmount;
  }
  goodsKeyChange(e) {
    e.preventDefault();
    this.setState({
      goodsKey: e.target.value
    });
  }
  searchHandle(value) {
    const { dispatch } = this.props;
    const { castTypeId, supplierId, financeOrgId } = this.state;
    if (!supplierId) {
      message.info("请先选择供货方");
      return false;
    }
    this.setState({
      goodsKey: value,
      selectedRowKeys: []
    });
    // 重新查询货补商品todo...
    dispatch({
      type: "goodsSupplyDetail/getSupplyAmountAndGoodsList",
      payload: {
        castTypeId: castTypeId,
        supplierId: supplierId,
        financeOrgId: financeOrgId,
        key: value
      }
    });
  }
  callback(key) {
    console.log(key);
  }
  render() {
    const { goodsSupplyDetailData, supplyAmountAndGoodsList } = this.props;
    if (!goodsSupplyDetailData) return null;
    const { cashGoods, selectedRowKeys, totalAmount } = this.state;
    // 拼接下拉框选项
    const selectOptionHtml = listData => {
      if (!listData || listData.length < 1) return null;
      const optionHtmls = listData.map(item => (
        <Select.Option key={item.id} value={item.id}>
          {item.name}
        </Select.Option>
      ));
      return optionHtmls;
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange.bind(this),
      getCheckboxProps: this.validCheckboxProps.bind(this),
      onSelect: this.onSelectHandle.bind(this),
      onSelectAll: this.onSelectAllHandle.bind(this)
    };
    const itemColumns = this.itemColumns;
    const selectColumns = this.selectColumns;
    return (
      <div className={styles.goodsSupplyDetailBox}>
        {/* <BreadcrumbPackage /> */}
        <div className={styles.goodsSupplyDetailContent}>
          <div className={styles.supplierBox}>
            <span className={styles.name}>供货方：</span>
            <Select
              defaultValue={this.state.supplierId}
              className={styles.supplierSelect}
              onChange={this.supplierChange.bind(this)}
            >
              {selectOptionHtml(goodsSupplyDetailData)}
            </Select>
          </div>
          <div className={styles.searchBox}>
            <Input.Search
              placeholder="请输入商品编码/产品编码"
              enterButton="搜索"
              style={{ width: 280 }}
              value={this.state.goodsKey}
              onChange={this.goodsKeyChange.bind(this)}
              onSearch={this.searchHandle.bind(this)}
            />
          </div>
          <Tabs defaultActiveKey="1" onChange={this.callback.bind(this)}>
            <TabPane tab="货补商品" key="1">
              <Table
                rowSelection={rowSelection}
                columns={itemColumns}
                dataSource={supplyAmountAndGoodsList.goodsItems || []}
              />
            </TabPane>
            <TabPane tab="本次兑付商品" key="2">
              <Table
                pagination={false}
                columns={selectColumns}
                dataSource={cashGoods}
              />
              <div className={styles.footerInfo}>
                本供货方最高可用货补金额：
                <span className={styles.maxSuppleFee}>
                  ￥{parseFloat(supplyAmountAndGoodsList.supplementAmount || 0).toFixed(currency.currencyAmountScale)}
                </span>
                当前合计：
                <span className={styles.totalAmount}>￥{parseFloat(totalAmount || 0).toFixed(currency.currencyAmountScale)}</span>
                <Button
                  className={styles.btn}
                  type="danger"
                  onClick={this.confrimCashHandle.bind(this)}
                >
                  确认兑付
                </Button>
              </div>
            </TabPane>
          </Tabs>
        </div>
      </div>
    );
  }
}
export default connect(state => ({
  goodsSupplyDetailData: state.goodsSupplyDetail.goodsSupplyDetailData,
  supplyAmountAndGoodsList: state.goodsSupplyDetail.supplyAmountAndGoodsList
}))(goodsSupplyDetail);
