import React, { PureComponent } from "react";
import { connect } from "dva";
import {
  Menu,
  Icon,
  Pagination,
  Table,
  Radio,
  Tabs,
  Row,
  Col,
  Card,
  Checkbox,
  message,
  Select
} 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 GoodsOptsDialog from "@/components/GoodsOptsDialog/index";
import { translateItemBomFromItem } from "@/pages/Buyer/orderEdit/orderTools";
import { goodsVersion, amountPrecision, unitPrecision } from '@/utils/common';
const RadioGroup = Radio.Group;
const TabPane = Tabs.TabPane;
const Option = Select.Option;

class OrderGoodsList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      goodsOptsParam: {
        rowData: {}
      },
      selectedGiftProms: [], // 选中的赠品行
      selectedGoodsValues: [], // 选中复选框项
      selectedPromStyle: "" // 选择促销
    };
    const { ifEditable } = this.props;
    this.columns = [
      {
        title: "商品",
        dataIndex: "goodsId",
        key: "goodsId",
        width: "280px",
        render: (text, record, index) => (
          <div className={styles.goodsNameBox}>
            <div style={{"float": 'left', "fontSize": "1.5rem", "paddingRight": "1rem"}}>
              {Number(index) + 1}
            </div>
            <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}>
                <span>编码：{record.goodsCode}</span>
                <span style={{'marginLeft':'20px'}}>规格：{record.specification}</span>
              </p>
              <p className={styles.goodsCode}>
                <span>型号：{record.model}</span>
              </p>
              <p className={record.isGift == 1 ? styles.goodsStatus : ""}>
                <span className={styles.goodsStatusTxt}>
                  {record.isGift == 1 ? "赠" : ""}
                </span>
              </p>
            </div>
          </div>
        )
      },
      {
        title: "商品选配",
        dataIndex: "baseGoodsOptValue",
        key: "baseGoodsOptValue",
        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} ${styles.textBox}`}>
              {amountPrecision(record.salePrice, "price", record.currencySign, 2)}
            </span>
            <em className={`${styles.em} ${styles.unitBox}`}>
              /{record.mainNumUnitName}
            </em>
          </span>
        )
      },
      {
        title: "成交价",
        dataIndex: "dealPrice",
        key: "dealPrice",
        className: "alignRight",
        render: (text, record, index) => (
          <span>
            <span className={`${styles.fontRed} ${styles.textBox}`}>
              {amountPrecision(record.dealPrice, "price", record.currencySign, 2)}
            </span>
            <em className={`${styles.em} ${styles.unitBox}`}>
              /{record.mainNumUnitName}
            </em>
          </span>
        )
      },
      // {
      //   title: "库存量",
      //   dataIndex: "stock",
      //   key: "stock",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span className={styles.MainNum}>
      //       <span className={styles.textBox}>{record.stock}</span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>
      //         {record.mainNumUnitName}
      //       </em>
      //     </span>
      //   )
      // },
      {
        title: "订货量",
        dataIndex: "orderNum",
        key: "orderNum",
        className: ifEditable ? "thAlignCenter" : "alignRight",
        render: (text, record, index) => {
          if (!ifEditable) {
            return (
              <span className={styles.orderNum}>
                <span className={styles.textBox}>{record.orderNum}</span>
                <em className={`${styles.em} ${styles.unitBox}`}>
                  {record.orderNumUnitName}
                </em>
              </span>
            );
          } else {
            return (
              <div className={styles.numIptBox} style={{ marginLeft: "20px" }}>
                <div style={{ width: "100px", display: "inline-block" }}>
                  <GoodsBuyIpt
                    key={record.goodsId + "-"+ index}
                    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}>
      //       <span className={styles.textBox}>{record.mainNum}</span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>
      //         {record.mainNumUnitName}
      //       </em>
      //     </span>
      //   )
      // },
      {
        title: "重量",
        dataIndex: "rowWeight",
        key: "rowWeight",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.MainNum}>
            <span className={styles.textBox}>{(text || 0).toFixed(2)}</span>
            <em className={`${styles.em} ${styles.unitBox}`}>{record.weightUnitName || ""}</em>
          </span>
        )
      },
      // {
      //   title: "体积",
      //   dataIndex: "rowVolume",
      //   key: "rowVolume",
      //   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",
        width: "100px",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.MainNum}>
            {amountPrecision(record.amount, "amount", record.currencySign, 2)}
          </span>
        )
      },
      {
        title: "成交金额",
        dataIndex: "dealAmount",
        key: "dealAmount",
        width: "100px",
        className: "alignRight",
        render: (text, record, index) => (
          <div className={styles.dealAmount}>
            <span className={styles.fontRed}>
              {amountPrecision(record.dealAmount, "amount", record.currencySign, 2)}
            </span>
          </div>
        )
      },
      // {
      //   title: "项目",
      //   dataIndex: "projectId",
      //   key: "projectId",
      //   className: "thAlignCenter",
      //   render: (text, record, index) => (
      //     <Select
      //       style={{ width: "100px", height: "30px", marginLeft: "10px" }}
      //       key={`projectId${index}${record.goodsId}`}
      //       value={text}
      //       onChange={this.recordValueChange.bind(
      //         this,
      //         index,
      //         "projectId"
      //       )}
      //     >
      //       {record.projectData.map(item => (
      //         <Option
      //           key={`projectId${index}${record.goodsId}${item.id}`}
      //           value={item.id}
      //         >
      //           {item.name}
      //         </Option>
      //       ))}
      //     </Select>
      //   )
      // },
      {
        title: "",
        dataIndex: "operation",
        key: "operation",
        width: "20px",
        render: (text, record, index) => {
          if (ifEditable) {
            return (
              <div className={styles.delBtn}>
                <Icon
                  type="close-circle"
                  className={styles.delIcon}
                  onClick={this.delHandle.bind(this, record)}
                />
              </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>
      //   )
      // }
    ];
    this.giftColumns = [
      {
        title: "商品",
        dataIndex: "goodsId",
        key: "goodsId-gift",
        width: "70%",
        className: "thAlignCenter",
        render: (text, record, index) => (
          <div>
            <div className={styles.giftsImgBox}>
              <img src={record.goodsImg} alt="" />
            </div>
            <div className={styles.giftsInfo}>
              <p className={styles.goodsTitleName}>{record.goodsDisplayName}</p>
            </div>
          </div>
        )
      },
      {
        title: "订货量",
        dataIndex: "orderNum",
        key: "orderNum-gift",
        width: "20%",
        className: "alignRight",
        render: (text, record, index) => {
          let step = 1;
          if (record.combineType == 1) {
            step = (parseFloat(record.goodCombineNum) / parseFloat(record.conversionRate || "1")).toFixed(record.orderNumUnitScale || 0);
          }
          const disabled = (step == 1 ? false : true);
          return (
            <div className={styles.numIptBox} style={{ marginLeft: "20px" }}>
              <div style={{ width: "100px", display: "inline-block" }}>
                <GoodsBuyIpt
                  key={`${record.id}${record.activityId}${index}`}
                  disabled={disabled}
                  num={record.orderNum}
                  step={step}
                  onChange={this.giftNumChange.bind(this, record)}
                />
              </div>
              <span>{record.orderNumUnitName}</span>
            </div>
          );
        }
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation-gift",
        width: "10%",
        className: "alignRight",
        render: (text, record, index) => {
          return (
            <div className={styles.giftsDelBtn} style={{ marginRight: "20px" }}>
              <a onClick={this.delGiftHandle.bind(this, record)}>删除</a>
            </div>
          );
        }
      }
    ];
  }
  componentWillReceiveProps(nextProps) {
    if ("orderCartData" in nextProps) {
      const orderCartData = nextProps.orderCartData;
      let totalDealAmount = 0; // 商品促销后总金额
      // 封装商品行金额信息
      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].orderNum).toFixed(orderCartData[i].orderNumUnitScale || 0));
        // 计算体积、重量
        orderCartData[i].rowVolume =
          parseFloat(orderCartData[i].volume || "0") *
          parseFloat(orderCartData[i].mainNum);
        orderCartData[i].rowWeight =
          parseFloat(orderCartData[i].weight || "0") *
          parseFloat(orderCartData[i].mainNum);
        // 计算商品金额：基准价 * 主数量
        orderCartData[i].amount =
          parseFloat(orderCartData[i].salePrice || "0") *
          parseFloat(orderCartData[i].mainNum || "0");
        // 计算促销后金额：促销价 * 主数量 - 均摊促销金额（整单降价均摊）
        const afterPromAmount =
          parseFloat(orderCartData[i].promPrice || "0") *
          parseFloat(orderCartData[i].mainNum || "0");
        orderCartData[i].dealAmount =
          afterPromAmount - parseFloat(orderCartData[i].promAmount || "0");
        totalDealAmount +=
          afterPromAmount - parseFloat(orderCartData[i].promAmount || "0");
      }
      // 冲抵费用均摊
      const offsetAmount = parseFloat(nextProps.offsetAmount || "0");
      if (offsetAmount > 0) {
        // 把冲抵费用均摊到商品行
        const occupyRate = offsetAmount / totalDealAmount;
        let occupyStep = offsetAmount;
        for (let j = 0; j < orderCartData.length; j++) {
          if (orderCartData[j].isGift == 1) {
            continue;
          }
          if (j == orderCartData.length - 1) {
            orderCartData[j].offsetAmount = occupyStep;
            orderCartData[j].dealAmount -= occupyStep;
            break;
          }
          const dealAmout =
            parseFloat(orderCartData[j].promPrice || "0") *
              parseFloat(orderCartData[j].mainNum || "0") -
            parseFloat(orderCartData[j].promAmount || "0");
          const offsetAmt = +(parseFloat(dealAmout * occupyRate).toFixed(
            orderCartData[j].currencyAmountScale
          ));
          occupyStep -= offsetAmt;
          orderCartData[j].offsetAmount = offsetAmt;
          orderCartData[j].dealAmount -= offsetAmt;
        }
      }
      // 计算成交价
      orderCartData.forEach(item => item.dealPrice = item.dealAmount / item.mainNum);
      this.sumFun(orderCartData);
    }
    if ("promotionInfoData" in nextProps) {
      const promotionInfoData = nextProps.promotionInfoData;
      if (promotionInfoData) {
        // 默认选择的促销维度
        const mutualRelationShip = promotionInfoData.mutualRelationShip;
        const { selectedPromStyle } = this.state;
        this.setState({
          selectedPromStyle: selectedPromStyle ? selectedPromStyle : (mutualRelationShip
            ? mutualRelationShip[0].join(",")
            : "")
        });
        // 对selectedGiftProms 进行封装，以方便后续赠品的勾选与移除
        const giftProms = promotionInfoData.giftProms;
        if (giftProms) {
          const { selectedGiftProms } = this.state;
          const newGiftProms = giftProms.map(giftProm => {
            const findGiftProm = selectedGiftProms.find(
              item =>
                `${item.activityId}${item.ruleId}` ==
                `${giftProm.activityId}${giftProm.ruleId}`
            );
            if (findGiftProm) {
              return findGiftProm;
            } else {
              const newGiftProm = Object.assign({}, giftProm, {
                giftDtos: null
              });
              return newGiftProm;
            }
          });
          this.setState({
            selectedGiftProms: newGiftProms
          });
        }
      } else {
        this.setState({
          selectedPromStyle: "",
          selectedGoodsValues: [],
          selectedGiftProms: []
        });
      }
    }
  }
  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
    //   });
    // });
    this.props.optClick && this.props.optClick(goods, index)
  }
  // 选择促销方式
  onRadioChangeHandle(e) {
    e.preventDefault();
    const { dispatch, promotionChange } = this.props;
    this.setState({
      selectedPromStyle: e.target.value
    });
    promotionChange(e.target.value);
  }
  // 勾选赠品
  onCheckBoxChange(gift, giftDtos, e) {
    let { selectedGiftProms, selectedGoodsValues } = this.state;
    // todo...
    // 判断勾选的赠品是否固定组合
    let isCombine = false;
    let combineGifts = [];
    const key = `${gift.activityId}${gift.ruleId}`;
    const goodsId = gift.goodsId;
    const conversionRate = parseFloat(gift.conversionRate || "1");
    const goodsAmout = parseFloat(gift.goodsAmout || "0");
    let orderNum = parseFloat(goodsAmout / conversionRate);
    let mainNum = goodsAmout;
    if (gift.combineType == 1) {
      const goodCombineNum = gift.goodCombineNum;
      orderNum = parseFloat(goodCombineNum / conversionRate);
      mainNum = goodCombineNum;
      isCombine = true;
      combineGifts = giftDtos.filter(item => item.giftId == gift.giftId);
    }
    gift.orderNum = +(orderNum.toFixed(gift.orderNumUnitScale || 0));
    gift.mainNum = mainNum;
    gift.rowWeight = mainNum * parseFloat(gift.weight || "0");
    gift.rowVolume = mainNum * parseFloat(gift.volume || "0");
    // 勾选赠品
    if (e.target.checked) {
      const validMsg = this.validGiftNum(
        gift,
        selectedGiftProms,
        mainNum
      );
      if (validMsg) {
        message.info(validMsg);
        this.sumFun();
        return false;
      }
      selectedGiftProms.forEach(giftProm => {
        const tempKey = `${giftProm.activityId}${giftProm.ruleId}`;
        if (tempKey == key) {
          let selectedgiftDtos = giftProm.giftDtos || [];
          if (isCombine) {
            combineGifts.forEach(item => {
              const goodCombineNum = item.goodCombineNum;
              item.orderNum = +(parseFloat(goodCombineNum / conversionRate).toFixed(item.orderNumUnitScale || 0));
              item.mainNum = goodCombineNum;
            });
            selectedgiftDtos = selectedgiftDtos.concat(combineGifts);
          } else {
            selectedgiftDtos = selectedgiftDtos.concat(gift);
          }
          giftProm.giftDtos = selectedgiftDtos;
        }
        return giftProm;
      });
      if (!selectedGoodsValues.includes(e.target.value)) {
        if (isCombine) {
          combineGifts.forEach(item => {
            const valueKey = `${item.activityId}${item.ruleId}${item.goodsId}${gift.giftId}`;
            selectedGoodsValues.push(valueKey);
          });
        } else {
          selectedGoodsValues.push(e.target.value);
        }
      }
      // 取消勾选
    } else {
      selectedGiftProms = this.removeGiftsData(selectedGiftProms, gift, isCombine);
      if (isCombine) {
        selectedGoodsValues = selectedGoodsValues.filter(
          value => !value.endsWith(gift.giftId)
        );
      } else {
        selectedGoodsValues = selectedGoodsValues.filter(
          value => value != e.target.value
        );
      }
    }
    this.setState({
      selectedGoodsValues: selectedGoodsValues,
      selectedGiftProms: selectedGiftProms.concat([])
    });
    this.props.setGiftItems(selectedGiftProms);
    this.sumFun();
  }
  // 赠品数量修改
  giftNumChange(gift, num) {
    const { selectedGiftProms } = this.state;
    const key = `${gift.activityId}${gift.ruleId}`;
    const goodsId = gift.goodsId;
    const orderNum = parseFloat(num);
    const mainNum = orderNum * (gift.conversionRate || "1");
    const validMsg = this.validGiftNum(gift, selectedGiftProms, mainNum);
    if (validMsg) {
      message.info(validMsg);
      this.setState({
        selectedGiftProms: selectedGiftProms.concat([])
      });
      this.sumFun();
      return false;
    }
    let isCombine = false;
    if (gift.combineType == 1) {
      isCombine = true;
    }
    selectedGiftProms.forEach(giftProm => {
      const tempKey = `${giftProm.activityId}${giftProm.ruleId}`;
      if (tempKey == key) {
        if (isCombine) {
          giftProm.giftDtos.forEach(giftDto => {
            if (giftDto.giftId == gift.giftId) {
              const mainNum = parseFloat(giftDto.mainNum) + parseFloat(giftDto.goodCombineNum || "0");
              const rate = parseFloat(giftDto.conversionRate || "1");
              giftDto.orderNum = +(parseFloat(mainNum / rate).toFixed(giftDto.orderNumUnitScale || 0));
              giftDto.mainNum = mainNum;
              giftDto.rowWeight = mainNum * parseFloat(giftDto.weight || "0");
              giftDto.rowVolume = mainNum * parseFloat(giftDto.volume || "0");
            }
          });
        } else {
          giftProm.giftDtos.forEach(giftDto => {
            if (giftDto.goodsId == goodsId) {
              giftDto.orderNum = num;
              giftDto.mainNum = mainNum;
              giftDto.rowWeight = mainNum * parseFloat(giftDto.weight || "0");
              giftDto.rowVolume = mainNum * parseFloat(giftDto.volume || "0");
            }
          });
        }
      }
    });
    this.setState({
      selectedGiftProms: selectedGiftProms.concat([])
    });
    this.props.setGiftItems(selectedGiftProms);
    this.sumFun();
  }
  validGiftNum(gift, selectedGiftProms, num) {
    let validMsg = "";
    const key = `${gift.activityId}${gift.ruleId}`;
    const belongGroupId = gift.belongGroupId;
    const goodsId = gift.goodsId;
    const conversionRate = parseFloat(gift.conversionRate || "1");
    const goodsAmout = gift.goodsAmout;
    let totalMainNum = num;
    const findGiftProm = selectedGiftProms.find(
      giftProm => `${giftProm.activityId}${giftProm.ruleId}` == key
    );
    if (findGiftProm && findGiftProm.giftDtos) {
      findGiftProm.giftDtos.forEach(giftDto => {
        if (
          giftDto.belongGroupId == belongGroupId &&
          giftDto.goodsId != goodsId
        ) {
          totalMainNum += parseFloat(giftDto.mainNum);
        }
      });
      if (totalMainNum > goodsAmout) {
        validMsg += `不能超出【买赠】促销【${findGiftProm.description}】下,【${
          gift.belongGroupName
        }】的可赠数量${Math.floor(goodsAmout / conversionRate)}`;
      }
    }
    return validMsg;
  }
  // 封装移除赠品数据的方法
  removeGiftsData(selectedGiftProms, gift, isCombine) {
    // todo...
    const key = `${gift.activityId}${gift.ruleId}`;
    const goodsId = gift.goodsId;
    selectedGiftProms.forEach(giftProm => {
      const tempKey = `${giftProm.activityId}${giftProm.ruleId}`;
      if (tempKey == key) {
        const giftDtos = giftProm.giftDtos;
        let newGiftItems = giftDtos.filter(item => item.goodsId != goodsId);
        if (isCombine) {
          newGiftItems = giftDtos.filter(item => item.giftId != gift.giftId);
        }
        giftProm.giftDtos = newGiftItems;
      }
      return giftProm;
    });
    return selectedGiftProms.concat([]);
  }
  // 移除赠品
  delGiftHandle(gift) {
    const { selectedGiftProms, selectedGoodsValues } = this.state;
    // 判断勾选的赠品是否固定组合
    let isCombine = false;
    if (gift.combineType == 1) {
      isCombine = true;
    }
    const newSelectedGiftActivitys = this.removeGiftsData(
      selectedGiftProms,
      gift,
      isCombine
    );
    const value = `${gift.activityId}${gift.ruleId}${gift.goodsId}${gift.giftId}`;
    let newSelectedGiftValues = selectedGoodsValues.filter(
      item => item != value
    );
    if (isCombine) {
      newSelectedGiftValues = selectedGoodsValues.filter(
        item => !item.endsWith(gift.giftId)
      );
    }
    this.setState({
      selectedGoodsValues: newSelectedGiftValues,
      selectedGiftProms: newSelectedGiftActivitys
    });
    this.props.setGiftItems(newSelectedGiftActivitys);
    this.sumFun();
  }
  recordValueChange(index, field, value) {
    const { orderCartData } = this.props;
    const newOrderCartData = orderCartData.concat([]);
    newOrderCartData[index][`${field}`] = value;
    this.props.dispatch({
      type: "orderEdit/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: "orderEdit/orderCartData",
      orderCartData: newOrderCartData
    });
  }
  // 购买数量改变
  buyNumChange(key, num) {
    const { orderCartData, dispatch } = this.props;
    const newOrderCartData = orderCartData.concat([]);
    const rowData = newOrderCartData[key];
    const rate = parseFloat(rowData.conversionRate || "1");
    newOrderCartData[key][`orderNum`] = +(num);
    newOrderCartData[key][`mainNum`] = +(num * rate);
    this.props.dispatch({
      type: "orderEdit/orderCartData",
      orderCartData: newOrderCartData
    });
    this.props.ifPromotion(true);
  }
  sumFun(data) {
    let orderCartData;
    if (data) {
      orderCartData = data;
    } else {
      orderCartData = this.props.orderCartData;
    }
    let newTotalAmount = 0; // 商品总金额
    let newTotalDealAmount = 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");
      newTotalDealAmount +=
        parseFloat(orderCartData[i].promPrice || "0") *
          parseFloat(orderCartData[i].mainNum || "0") -
        parseFloat(orderCartData[i].promAmount || "0");
      newAllWeight += parseFloat(orderCartData[i].rowWeight);
      newAllVolume += parseFloat(orderCartData[i].rowVolume);
      newTotalNum += parseFloat(orderCartData[i].orderNum);
    }
    this.fillGiftWeightAndVolume({
      newTotalAmount,
      newTotalDealAmount,
      newAllWeight,
      newAllVolume,
      newTotalNum
    });
  }
  // 如果有赠品，补充赠品体积重量
  fillGiftWeightAndVolume(value) {
    const { dispatch } = this.props;
    const { selectedGiftProms } = this.state;
    const newTotalAmount = value.newTotalAmount;
    const newTotalDealAmount = value.newTotalDealAmount;
    // 累加赠品数量、体积、重量
    let newTotalNum = value.newTotalNum;
    let newAllWeight = value.newAllWeight || 0;
    let newAllVolume = value.newAllVolume || 0;
    if (selectedGiftProms && selectedGiftProms.length > 0) {
      selectedGiftProms.forEach(giftProm => {
        const giftDtos = giftProm.giftDtos;
        if (giftDtos && giftDtos.length > 0) {
          giftDtos.forEach(gift => {
            newAllWeight += parseFloat(gift.rowWeight);
            newAllVolume += parseFloat(gift.rowVolume);
            newTotalNum += parseFloat(gift.orderNum);
          });
        }
      });
    }
    this.props.onChange({
      newTotalAmount,
      newTotalDealAmount,
      newAllWeight,
      newAllVolume,
      newTotalNum
    });
  }
  // 删除商品
  delHandle(goodsItem) {
    const { orderCartData, dispatch } = this.props;
    // todo...
    const newOrderCartData = orderCartData.filter(
      item => goodsItem.goodsId != item.goodsId || goodsItem.ext05 != item.ext05
    );
    this.props.dispatch({
      type: "orderEdit/orderCartData",
      orderCartData: newOrderCartData
    });
    // 匹配促销信息
    this.props.ifPromotion(true);
  }
  expandedRowRender(record) {
    const promotions = record.reqOrderPromRels;
    if (!promotions) return null;
    promotions.forEach(item => {
      let promWayName = "";
      switch (item.promWay) {
        case 1:
          promWayName = "买赠";
          break;
        case 2:
          promWayName = "降价";
          break;
        default:
          break;
      }
      item.promWayName = promWayName;
    });
    return promotions.map(item => {
      return (
        <p className={styles.expandedTop}>
          <span className={styles.giftTip}>{item.promWayName}</span>
          <span>{item.description}</span>
        </p>
      );
    });
  }
  render() {
    // ifEditable 订单是否可编辑， 默认可编辑：true
    const { orderCartData, ifEditable, promotionInfoData, projectData } = this.props;
    const { selectedGiftProms, selectedPromStyle } = this.state;
    if (!orderCartData || orderCartData.length < 1) return <EmptyData />;
    // 往商品行上封装项目
    orderCartData.forEach(item => {
      item.projectData = projectData || [];
    });
    const giftColumns = this.giftColumns;
    // 拼接买赠商品HTML
    const getGiftItemsHtml = giftProm => {
      const { selectedGoodsValues } = this.state;
      if (!giftProm) return null;
      const giftDtos = giftProm.giftDtos;
      if (!giftDtos) return null;
      const giftArray = [];
      for (let i = 0; i < giftDtos.length; i += 6) {
        giftArray.push(giftDtos.slice(i, i + 6));
      }
      return giftArray.map(gifts => {
        return (
          <Row gutter={16} className={styles.activityContent}>
            {gifts.map(gift => {
              return (
                <Col
                  span="4"
                  key={`${gift.activityId}${gift.ruleId}${gift.goodsId}`}
                >
                  <Card bordered={false} style={{ width: "100%" }}>
                    <div className={styles.cardImage}>
                      <Checkbox
                        checked={selectedGoodsValues.includes(
                          `${gift.activityId}${gift.ruleId}${gift.goodsId}${gift.giftId}`
                        )}
                        value={`${gift.activityId}${gift.ruleId}${
                          gift.goodsId}${gift.giftId}`}
                        className={styles.checkboxContent}
                        onChange={this.onCheckBoxChange.bind(this, gift, giftDtos)}
                      >
                        <img
                          alt=""
                          width="100%"
                          height="176px"
                          src={gift.goodsImg}
                        />
                      </Checkbox>
                    </div>
                    <div className={styles.goodsDisplayName}>
                      <p>{gift.goodsDisplayName}</p>
                    </div>
                  </Card>
                </Col>
              );
            })}
          </Row>
        );
      });
    };
    // 拼接买赠活动HTML
    const getGiftActivityHtml = () => {
      return promotionInfoData.giftProms.map(giftProm => {
        return (
          <div
            className={styles.promotionActivtyRow}
            key={`${giftProm.activityId}${giftProm.ruleId}`}
          >
            <Row className={styles.activtyTitle}>
              <Col span="24">
                <span className={styles.giftTip}>买赠</span>
                <span>{giftProm.description}</span>
              </Col>
            </Row>
            {getGiftItemsHtml(giftProm)}
          </div>
        );
      });
    };
    // 拼接已选的买赠商品HTML
    const getSelectedGiftItemsHtml = giftProm => {
      if (!giftProm) return null;
      const giftDtos = giftProm.giftDtos;
      if (!giftDtos) return null;
      return (
        <Row className={styles.activityContent}>
          {
            <Table
              className={styles.selectedGiftTable}
              showHeader={false}
              // scroll={{ y: 250 }}
              pagination={false}
              dataSource={giftDtos}
              columns={giftColumns}
            />
          }
        </Row>
      );
    };
    // 拼接已选的买赠活动HTML
    const getSelectedGiftActivityHtml = () => {
      if (!selectedGiftProms || selectedGiftProms.length < 1) {
        return null;
      }
      return selectedGiftProms.map(giftProm => {
        return (
          <div
            className={styles.promotionActivtyRow}
            key={`${giftProm.activityId}${giftProm.ruleId}`}
            style={{
              display:
                giftProm.giftDtos && giftProm.giftDtos.length > 0
                  ? "block"
                  : "none"
            }}
          >
            <Row className={styles.activtyTitle}>
              <Col span="24">
                <span className={styles.giftTip}>买赠</span>
                <span>{giftProm.description}</span>
              </Col>
            </Row>
            {getSelectedGiftItemsHtml(giftProm)}
          </div>
        );
      });
    };
    const getPromStyleRadioHtml = promStyles => {
      if (!promStyles) return null;
      const val = promStyles.join(",");
      return promStyles.map(style => {
        let styleName = "买赠-基于商品";
        if (style == 2) {
          styleName = "降价-基于商品";
        } else if (style == 3) {
          styleName = "买赠-基于订单";
        } else if (style == 4) {
          styleName = "降价-基于订单";
        }
        return (
          <Radio value={val} className={styles.radioRight40}>
            {styleName}
          </Radio>
        );
      });
    };
    const getPromoStyleHtml = () => {
      if (!selectedPromStyle || !promotionInfoData.mutualRelationShip) {
        return null;
      }
      return (
        <RadioGroup
          className={styles.radioGroup}
          onChange={this.onRadioChangeHandle.bind(this)}
          value={selectedPromStyle}
        >
          {getPromStyleRadioHtml(promotionInfoData.mutualRelationShip[0])}
          {getPromStyleRadioHtml(promotionInfoData.mutualRelationShip[1])}
        </RadioGroup>
      );
    };
    const getGiftPromsHtml = () => {
      if (
        !promotionInfoData ||
        !promotionInfoData.giftProms ||
        promotionInfoData.giftProms.length < 1
      ) {
        return null;
      }
      return (
        <Tabs defaultActiveKey="1" className={styles.promotionGiftBox}>
          <TabPane tab="可选赠品" key="1">
            {getGiftActivityHtml()}
          </TabPane>
          <TabPane tab="已选赠品" key="2">
            {getSelectedGiftActivityHtml()}
          </TabPane>
        </Tabs>
      );
    };
    // 整单降价促销
    const getOrderPriceCutHtml = () => {
      if (!promotionInfoData || !promotionInfoData.orderPriceProm) return null;
      return (
        <div className={styles.orderPriceCutTitle}>
          <span className={styles.priceTip}>降价</span>
          <span>{promotionInfoData.orderPriceProm.description}</span>
        </div>
      );
    };
    const getPromotionInfoHtml = () => {
      // 货补不展示促销信息
      if (!ifEditable) return null;
      return (
        <div style={{ width: "100%" }}>
          {/* 整单降价促销提示  start */}
          {getOrderPriceCutHtml()}
          {/* 整单降价促销提示  end */}
          {/* 订单促销维度选择  start */}
          {getPromoStyleHtml()}
          {/* 订单促销维度选择  end */}
          {/* 促销赠品选择 start */}
          {getGiftPromsHtml()}
          {/* 促销赠品选择 end */}
        </div>
      );
    };
    const columns = this.columns;
    const bomColumns = this.bomColumns;
    let orderItemBomData = [];
    if (orderCartData && orderCartData.length > 0) {
      orderItemBomData = translateItemBomFromItem(orderCartData);
    }
    // 默认展开促销活动
    const expandedTop = true;
    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}
            expandedRowRender={this.expandedRowRender.bind(this)}
            expandedOnRowsTop={expandedTop}
          />
        </TabPane>
        {/* <TabPane tab="商品BOM信息" key="product-bom-tab">
          <GridTable
            className={styles.goodsListGrid}
            dataSource={orderItemBomData}
            columns={bomColumns}
          />
        </TabPane> */}
      </Tabs>
        {/* <Table
          className={styles.goodsListGrid}
          pagination={false}
          dataSource={orderCartData}
          columns={columns}
        /> */}
        {/* 商品行信息  end */}
        {/* 促销信息  start */}
        {getPromotionInfoHtml()}
        {/* 促销信息  end */}
        <GoodsOptsDialog
          title="商品选配"
          goodsOptsParam={this.state.goodsOptsParam}
          onConfirm={this.addGoodsOptsInfo.bind(this)}
        />
      </div>
    );
  }
}
export default OrderGoodsList;
