import React, { PureComponent } from "react";
import { connect } from "dva";
import {
  Menu,
  Icon,
  Pagination,
  Table,
  Radio,
  Tabs,
  Row,
  Col,
  Card,
  Checkbox,
  message,
  Select,
  Input,
  Button,
  Upload
} from "antd";
import styles from "./index.less";
import imgSrc from "./goods-img.png";
import GoodsBuyIpt from "../GoodsBuyIpt/index.js";
import EmptyData from "@/components/EmptyData/index";
import GridTable from "../GridTable/index";
import { goodsVersion } from '@/utils/common';
import { fillDefalutInfoForUpload, translateItemBomFromItem } from "@/pages/Buyer/orderEdit/orderTools";
import GoodsOptsDialog from "@/components/GoodsOptsDialog/index";
const RadioGroup = Radio.Group;
const TabPane = Tabs.TabPane;
const Option = Select.Option;
const getUploadTipStyle = fileList => {
  const length = fileList.length;
  return {
    bottom: length > 0 ? "-20px" : "",
    display: length >= 3 ? "none" : ""
  };
};

class OrderGoodsList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      goodsOptsParam: {
        rowData: {}
      }
    };
    const { getUploadParams } = this.props;
    this.columns = [
      {
        title: "商品",
        dataIndex: "goodsId",
        key: "goodsId",
        width: "230px",
        className: "thAlignCenter",
        render: (text, record, index) => (
          <div className={styles.goodsNameBox}>
            <div className={styles.imgBox}>
              <img src={record.goodsImg} alt="" />
            </div>
            <div className={styles.goodsInfo}>
              <p className={styles.goodsTitleName} title={record.goodsDisplayName}>
                {record.goodsDisplayName}
              </p>
              <p className={styles.goodsCode}>{record.goodsCode}{goodsVersion(record.version, "", "10%")}</p>
              <p className={record.isGift == 1 ? styles.goodsStatus : ""}>
                <span className={styles.goodsStatusTxt}>
                  {record.isGift == 1 ? "赠" : ""}
                </span>
              </p>
            </div>
          </div>
        )
      },
      {
        title: "商品选配",
        dataIndex: "salePrice",
        key: "salePrice",
        align: "right",
        render: (text, record, index) => {
          if (record.isOptional || record.baseGoodsOptValue) {
            return (
              <span className={styles.goodsOpt} onClick={this.onGoodsOptionalHandle.bind(this, record, index)}>
                {record.baseGoodsOptValue || "添加选配"}
              </span>
            );
          } else {
            return null;
          }
        }
      },
      // {
      //   title: "单价",
      //   dataIndex: "salePrice",
      //   key: "salePrice",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span>
      //       <span className={styles.fontRed}>
      //         ￥{record.salePrice.toFixed(record.currencyPriceScale)}
      //       </span>
      //       <em className={styles.em}>/{record.mainNumUnitName}</em>
      //     </span>
      //   )
      // },
      {
        title: "成交价",
        dataIndex: "dealPrice",
        key: "dealPrice",
        className: "alignRight",
        render: (text, record, index) => (
          <span>
            <span className={styles.fontRed}>
              ￥{record.dealPrice.toFixed(record.currencyPriceScale)}
            </span>
            <em className={styles.em}>/{record.mainNumUnitName}</em>
          </span>
        )
      },
      {
        title: "退货量",
        dataIndex: "orderNum",
        key: "orderNum",
        className: "alignRight thAlignCenter",
        render: (text, record, index) => {
          return (
            <div className={styles.numIptBox} style={{ marginLeft: "20px" }}>
              <div style={{ width: "100px", display: "inline-block" }}>
                <GoodsBuyIpt
                  key={record.goodsId}
                  num={record.orderNum}
                  onChange={this.buyNumChange.bind(this, index)}
                />
              </div>
              <em className={styles.em} style={{ paddingLeft: "1px" }}>
                {record.orderNumUnitName}
              </em>
            </div>
          );
        }
      },
      {
        title: "主数量",
        dataIndex: "mainNum",
        key: "mainNum",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.MainNum}>
            {record.mainNum}
            <em className={styles.em}>{record.mainNumUnitName}</em>
          </span>
        )
      },
      // {
      //   title: "金额小计",
      //   dataIndex: "amount",
      //   key: "amount",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span className={styles.MainNum}>
      //       ￥{parseFloat(record.amount).toFixed(record.currencyAmountScale)}
      //     </span>
      //   )
      // },
      {
        title: "退货金额",
        dataIndex: "dealAmount",
        key: "dealAmount",
        className: "alignRight",
        render: (text, record, index) => (
          <div className={styles.dealAmount}>
            <span className={styles.fontRed}>
              ￥{parseFloat(record.totalReturnAmount || record.dealAmount).toFixed(
                record.currencyAmountScale
              )}
            </span>
          </div>
        )
      },
      {
        title: "退货类型",
        dataIndex: "returnTypeCode",
        key: "returnTypeCode",
        className: "alignRight",
        render: (text, record, index) => (
          <Select
            style={{ width: "80px", height: "30px" }}
            key={`returnTypeId${index}${record.goodsId}`}
            value={text}
            onChange={this.recordValueChange.bind(this, index, "returnTypeCode")}
          >
            {record.returnTypeData.map(item => (
              <Option
                key={`returnTypeId${index}${record.goodsId}${item.id}`}
                value={item.code}
              >
                {item.name}
              </Option>
            ))}
          </Select>
        )
      },
      {
        title: "退货原因",
        dataIndex: "returnReasonId",
        key: "returnReasonId",
        className: "alignRight thAlignCenter",
        render: (text, record, index) => (
          <Select
            style={{ width: "100px", height: "30px" }}
            key={`returnReasonId${index}${record.goodsId}`}
            value={text}
            onChange={this.recordValueChange.bind(
              this,
              index,
              "returnReasonId"
            )}
          >
            {record.returnCauseData.map(item => (
              <Option
                key={`returnReasonId${index}${record.goodsId}${item.id}`}
                value={item.id}
              >
                {item.name}
              </Option>
            ))}
          </Select>
        )
      },
      {
        title: "备注",
        dataIndex: "remark",
        key: "remark",
        className: "alignRight thAlignCenter",
        render: (text, record, index) => (
          <Input
            style={{ width: "120px", height: "30px" }}
            value={text}
            onChange={this.recordInputChage.bind(this, index, "remark")}
          />
        )
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        width: "160px",
        className: "thAlignCenter positionRelative",
        render: (text, record, index) => {
          return (
            <div className={styles.bodyUploadBox}>
              <Upload
                key={`body-${record.goodsId}-id-${index}`}
                className={styles.bodyUploadContent}
                action="/iuap-saas-filesystem-service/file/upload"
                data={getUploadParams(`body-${record.goodsId}-id-${index}`)}
                fileList={record.reqOrderAttachments}
                onChange={this.bodyFilehandleChange.bind(this, index)}
              >
                <span
                  className={styles.uploadTip}
                  style={getUploadTipStyle(record.reqOrderAttachments || [])}
                >
                  <Icon type="upload" className={styles.uploadIcon} />
                  (最多上传三张)
                </span>
              </Upload>
              <div className={styles.delBtn}>
                <Icon
                  type="close-circle"
                  className={styles.delIcon}
                  onClick={this.delHandle.bind(this, record)}
                />
              </div>
            </div>
          );
        }
      }
    ];
    this.bomColumns = [
      {
        title: "商品",
        dataIndex: "goodsId",
        key: "goodsId-bom",
        width: "25%",
        render: (text, record, index) => (
          <div className={styles.goodsNameBox}>
            <div className={styles.imgBox}>
              <img src={record.goodsImg} alt="" />
            </div>
            <div className={styles.goodsInfo}>
              <p className={styles.goodsTitleName} title={record.goodsDisplayName || record.goodsName}>
                {record.goodsDisplayName}
              </p>
              <p className={styles.goodsCode}>{record.goodsCode}{goodsVersion(record.version)}</p>
              <p className={record.isGift == 1 ? styles.goodsStatus : ""}>
                <span className={styles.goodsStatusTxt}>
                  {record.isGift == 1 ? "赠" : ""}
                </span>
              </p>
            </div>
          </div>
        )
      },
      {
        title: "选配",
        dataIndex: "baseGoodsOptValue",
        key: "baseGoodsOptValue-bom",
        width: "15%",
        render: (text, record, index) => (
          <span className={styles.valBox} title={record.baseGoodsOptValue}>
            {record.baseGoodsOptValue}
          </span>
        )
      },
      {
        title: "母件行号",
        dataIndex: "parentRowNum",
        key: "parentRowNum",
        width: "10%",
        className: "alignRight",
        render: (text, record, index) => (
          <span>
            <span>{text}</span>
          </span>
        )
      },
      {
        title: "母件商品名称",
        dataIndex: "parentGoodsName",
        key: "parentGoodsName",
        width: "12%",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.valBox} title={text}>
            {text}
          </span>
        )
      },
      {
        title: "母件商品编码",
        dataIndex: "parentGoodsCode",
        key: "parentGoodsCode",
        width: "12%",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.valBox} title={text}>
            {text}
          </span>
        )
      },
      // {
      //   title: "重量",
      //   dataIndex: "rowWeight",
      //   key: "rowWeight-bom",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span className={styles.MainNum}>
      //       <span className={styles.textBox}>{(text || 0).toFixed(record.weightUnitPrecision || 2)}</span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>{record.weightUnitName || ""}</em>
      //     </span>
      //   )
      // },
      // {
      //   title: "单价",
      //   dataIndex: "salePrice",
      //   key: "salePrice-bom",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span>
      //       <span className={`${styles.fontRed} ${styles.textBox}`}>
      //       {amountPrecision(record.salePrice, "price", record.currencySign, record.currencyPriceScale)}
      //       </span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>
      //         /{record.mainNumUnitName}
      //       </em>
      //     </span>
      //   )
      // },
      // {
      //   title: "成交价",
      //   dataIndex: "dealPrice",
      //   key: "dealPrice-bom",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span>
      //       <span className={`${styles.fontRed} ${styles.textBox}`}>
      //       {amountPrecision(record.dealPrice, "price", record.currencySign, record.currencyPriceScale)}
      //       </span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>
      //         /{record.mainNumUnitName}
      //       </em>
      //     </span>
      //   )
      // },
      {
        title: "订货量",
        dataIndex: "orderNum",
        key: "orderNum-bom",
        width: "12%",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.orderNum}>
            <span className={styles.textBox}>{record.orderNum}</span>
            <em className={`${styles.em} ${styles.unitBox}`}>
              {record.orderNumUnitName}
            </em>
          </span>
        )
      },
      {
        title: "主数量",
        dataIndex: "mainNum",
        key: "mainNum-bom",
        width: "12%",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.MainNum}>
            <span className={styles.textBox}>{record.mainNum}</span>
            <em className={`${styles.em} ${styles.unitBox}`}>
              {record.mainNumUnitName}
            </em>
          </span>
        )
      },
      // {
      //   title: "重量",
      //   dataIndex: "rowWeight",
      //   key: "rowWeight-bom",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span className={styles.MainNum}>
      //       <span className={styles.textBox}>{(text || 0).toFixed(record.weightUnitPrecision || 2)}</span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>{record.weightUnitName || ""}</em>
      //     </span>
      //   )
      // },
      // {
      //   title: "体积",
      //   dataIndex: "rowVolume",
      //   key: "rowVolume-bom",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span className={styles.MainNum}>
      //       <span className={styles.textBox}>{(text || 0).toFixed(record.volumeUnitPrecision || 2)}</span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>{record.volumeUnitName || ""}</em>
      //     </span>
      //   )
      // },
      // {
      //   title: "金额",
      //   dataIndex: "amount",
      //   key: "amount-bom",
      //   width: "100px",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span className={styles.MainNum}>
      //       {amountPrecision(record.amount, "amount", record.currencySign, record.currencyAmountScale)}
      //     </span>
      //   )
      // },
      // {
      //   title: "成交金额",
      //   dataIndex: "dealAmount",
      //   key: "dealAmount-bom",
      //   width: "100px",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <div className={styles.dealAmount}>
      //       <span className={styles.fontRed}>
      //         {amountPrecision(record.dealAmount, "amount", record.currencySign, record.currencyAmountScale)}
      //       </span>
      //     </div>
      //   )
      // }
    ];
  }
  componentWillReceiveProps(nextProps) {
    if ("orderCartData" in nextProps) {
      const orderCartData = nextProps.orderCartData;
      // 封装商品行金额信息
      for (let i = 0; i < orderCartData.length; i++) {
        if (orderCartData[i].isGift == 1) {
          continue;
        }
        orderCartData[i].mainNum = +(parseFloat(orderCartData[i].mainNum).toFixed(orderCartData[i].mainNumUnitScale || 0));
        orderCartData[i].orderNum = +(parseFloat(orderCartData[i].mainNum).toFixed(orderCartData[i].orderNumUnitScale || 0));
        // 计算体积、重量
        orderCartData[i].rowVolume =
          parseFloat(orderCartData[i].volume) *
          parseFloat(orderCartData[i].mainNum);
        orderCartData[i].rowWeight =
          parseFloat(orderCartData[i].weight) *
          parseFloat(orderCartData[i].mainNum);
        // 计算商品金额：基准价 * 主数量
        orderCartData[i].amount =
          parseFloat(orderCartData[i].salePrice || "0") *
          parseFloat(orderCartData[i].mainNum || "0");
        // 计算成交金额：成交价 * 主数量
        const dealAmount =
          parseFloat(orderCartData[i].dealPrice || "0") *
          parseFloat(orderCartData[i].mainNum || "0");
        orderCartData[i].dealAmount = dealAmount;
        // 实际退货金额, 门户新增退货单时，实际退货金额默认为 成交金额
        orderCartData[i].totalReturnAmount = dealAmount;
      }
      this.sumFun(orderCartData);
    }
  }
  // 选配
  onGoodsOptionalHandle(goods, index) {
    const goodsOptsParam =  {
      rowData: goods,
      goodsId: goods.goodsId,
      baseGoodsOptId: goods.baseGoodsOptId,
      rowIndex: index
    };
    this.setState({
      goodsOptsParam: goodsOptsParam
    }, () => {
      this.props.dispatch({
        type: "global/goodsOptsVisible",
        payload: true
      });
    });
  }
  recordValueChange(index, field, value) {
    const { orderCartData, ifBaseReturnOrder, dispatch } = this.props;
    const newOrderCartData = orderCartData.concat([]);
    newOrderCartData[index][`${field}`] = value;
    this.props.dispatch({
      type: "returnOrderEdit/orderCartData",
      orderCartData: newOrderCartData
    });
  }
  recordInputChage(index, field, e) {
    e.preventDefault();
    this.recordValueChange(index, field, e.target.value);
  }
  bodyFilehandleChange(index, info) {
    const { orderCartData } = this.props;
    const newOrderCartData = orderCartData.concat([]);
    let fileList = info.fileList;
    fileList = fileList.slice(-3);
    fileList = fileList.map(file => {
      if (file.response && file.response.data) {
        file.attachmentUrl = file.response.data[0].url;
        file.attachmentName = file.response.data[0].filename;
      }
      return file;
    });
    fileList = fileList.filter(file => {
      if (file.response) {
        return !!file.attachmentUrl;
      }
      return true;
    });
    newOrderCartData[index][`reqOrderAttachments`] = fileList;
    this.props.dispatch({
      type: "returnOrderEdit/orderCartData",
      orderCartData: newOrderCartData
    });
    // 移除附件
    // if (file.status == "removed") {
    //   fileList = fileList.filter(item => item.uid != file.uid);
    //   newOrderCartData[index][`fileList`] = fileList;
    //   this.props.dispatch({
    //     type: "returnOrderEdit/orderCartData",
    //     orderCartData: newOrderCartData
    //   });
    // } else if (file.status == "done") {
    //   if (file.response.status === 'success') {
    //     file.url = file.response.url;
    //     fileList.push(file);
    //     newOrderCartData[index][`fileList`] = fileList;
    //     this.props.dispatch({
    //       type: "returnOrderEdit/orderCartData",
    //       orderCartData: newOrderCartData
    //     });
    //   }
    // }
  }
  // 选配信息
  addGoodsOptsInfo(goodsOpts, rowIndex) {
    const { orderCartData, dispatch } = this.props;
    const optResult = [];
    const id = [];
    const newOrderCartData = orderCartData.concat([]);
    // BOM选配赋值todo...
    goodsOpts.forEach(goodsOpt => {
      if (newOrderCartData[rowIndex][`reqOrderItemBoms`]) {
        newOrderCartData[rowIndex][`reqOrderItemBoms`].forEach(reqOrderItemBom => {
          if (reqOrderItemBom.childGoodsId == goodsOpt.goodsId) {
            reqOrderItemBom.baseGoodsOptId = goodsOpt.id;
            reqOrderItemBom.baseGoodsOptValue = goodsOpt.optResult;
          }
        });
      }
      optResult.push(goodsOpt.optResult);
      id.push(goodsOpt.id);
    });
    newOrderCartData[rowIndex][`baseGoodsOptId`] = id.join(",");
    newOrderCartData[rowIndex][`baseGoodsOptValue`] = optResult.join(",");
    dispatch({
      type: "returnOrderEdit/orderCartData",
      orderCartData: newOrderCartData
    });
  }
  // 退货数量改变
  buyNumChange(key, num) {
    const { orderCartData, ifBaseReturnOrder, dispatch } = this.props;
    const newOrderCartData = orderCartData.concat([]);
    const rowData = newOrderCartData[key];
    const rate = parseFloat(rowData.conversionRate || "1");
    num = parseFloat(num || "0");
    // 如果是基于原单退货，则需校验输入的退货量
    if (ifBaseReturnOrder) {
      // 最大可退货数量 = 累计出库量 - 累计退货量
      const returnMaxOrderNum = parseFloat(rowData.returnMaxOrderNum || "0");
      if (num > returnMaxOrderNum) {
        message.info(
          `商品行【${
            rowData.goodsDisplayName
          }】输入的退货数量不能高于商品最大可退货量【${returnMaxOrderNum}】，请重新输入`
        );
      } else {
        newOrderCartData[key][`orderNum`] = num;
        newOrderCartData[key][`mainNum`] = num * rate;
      }
    } else {
      newOrderCartData[key][`orderNum`] = num;
      newOrderCartData[key][`mainNum`] = num * rate;
    }
    this.props.dispatch({
      type: "returnOrderEdit/orderCartData",
      orderCartData: newOrderCartData
    });
  }
  sumFun(data) {
    let orderCartData;
    if (data) {
      orderCartData = data;
    } else {
      orderCartData = this.props.orderCartData;
    }
    let newTotalAmount = 0; // 商品总金额（退货单金额）
    let newTotalDealAmount = 0; // 商品成交总金额（退货单成交金额）
    let newTotaltotalReturnAmount = 0; // 实际退货总金额
    let newAllWeight = 0; // 总重量
    let newAllVolume = 0; // 总体积
    let newTotalNum = 0; // 总数量
    for (let i = 0; i < orderCartData.length; i++) {
      newTotalAmount +=
        parseFloat(orderCartData[i].salePrice || "0") *
        parseFloat(orderCartData[i].mainNum || "0");
      const dealAmount =
        parseFloat(orderCartData[i].dealPrice || "0") *
        parseFloat(orderCartData[i].mainNum || "0");
      newTotalDealAmount += dealAmount;
      newTotaltotalReturnAmount += dealAmount;
      newAllWeight += orderCartData[i].rowWeight;
      newAllVolume += orderCartData[i].rowVolume;
      newTotalNum += orderCartData[i].orderNum;
    }
    this.props.onChange({
      newTotalAmount,
      newTotalDealAmount,
      newTotaltotalReturnAmount,
      newAllWeight,
      newAllVolume,
      newTotalNum
    });
  }
  // 删除商品
  delHandle(goodsItem) {
    const { orderCartData, dispatch } = this.props;
    // todo...
    const newOrderCartData = orderCartData.filter(
      item => goodsItem.goodsId != item.goodsId
    );
    this.props.dispatch({
      type: "returnOrderEdit/orderCartData",
      orderCartData: newOrderCartData
    });
  }
  render() {
    const { orderCartData, returnCauseData, returnTypeData } = this.props;
    if (!orderCartData || orderCartData.length < 1) return <EmptyData />;
    // 往商品行上封装退货原因/退货类型
    orderCartData.forEach(item => {
      item.returnCauseData = returnCauseData || [];
      item.returnTypeData = returnTypeData || [];
    });
    const columns = this.columns;
    const bomColumns = this.bomColumns;
    const orderItemBomData = translateItemBomFromItem(orderCartData);
    return (
      <div className={styles.goodsListBox}>
        {/* 商品行信息  start */}
        <Tabs defaultActiveKey="product-tab" type="card">
          <TabPane tab="商品信息" key="product-tab">
            <GridTable
              className={styles.goodsListGrid}
              dataSource={orderCartData}
              columns={columns}
            />
          </TabPane>
          {/* <TabPane tab="商品BOM信息" key="product-bom-tab">
            <GridTable
              className={styles.goodsListGrid}
              dataSource={orderItemBomData}
              columns={bomColumns}
            />
          </TabPane> */}
        </Tabs>
        <GoodsOptsDialog
          title="商品选配"
          goodsOptsParam={this.state.goodsOptsParam}
          onConfirm={this.addGoodsOptsInfo.bind(this)}
        />
      </div>
    );
  }
}
export default OrderGoodsList;
