import React, { Component } from "react";
import _ from "lodash";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import {
  Menu,
  Icon,
  Pagination,
  Checkbox,
  Button,
  message,
  Popconfirm
} from "antd";
import LazyLoad from "react-lazy-load";
import styles from "./index.less";
import FooterToolbar from "../FooterToolbar";
import GoodsBuyIpt from "../GoodsBuyIpt/index.js";
import CustIcon, { STATUS as IconStatus } from "../CustIcon";
import { amountPrecision } from '@/utils/utils';
import erroImg  from "@/assets/imgError.png";
import { goodsVersion } from '@/utils/common';

/**
 * 购物车-商品显示-列表显示
 * @param cartCheckStatus: {saleOrgId+goodsId: Boolean};用来标示购物车商品的选中状态
 */
class CartListComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      allPrice: 0, // 总价
      selectNum: 0 // 已选个数
    };
    this.state.checkAllStatus = this.props.checkAllStatus;
  }
  componentWillMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "cartList/getCartListData"
    });
  }
  // 获取已经选择的数据
  getCheckedData(cartCheckStatus) {
    const { cartListData = {}, dispatch } = this.props;
    const ids = [];
    let checkData;
    const childDatas = [];
    for (let i = 0; i < cartListData.length; i++) {
      const data = cartListData[i];
      for (const j in cartCheckStatus) {
        if (cartCheckStatus[j] !== true) continue;
        if (j == data.saleOrgId) {
          checkData = _.cloneDeep(data);
          break;
        } else if (j.startsWith(data.saleOrgId)) {
          for (let m = 0; m < cartListData[i].cartlist.length; m++) {
            const childData = cartListData[i].cartlist[m];
            if (j == `${data.saleOrgId}${childData.id}`) {
              childDatas.push(childData);
            }
          }
          checkData = _.cloneDeep(data);
        }
      }
    }
    if (childDatas && childDatas.length > 0) {
      checkData.cartlist = childDatas;
    }
    console.log(checkData)
    return checkData;
  }
  // 总价
  allPrice(cartCheckStatus) {
    const checkData = this.getCheckedData(
      cartCheckStatus || this.state.cartCheckStatus
    );
    let selectNum = 0;
    let allPrice = 0;
    if (checkData) {
      for (const cart of checkData.cartlist) {
        allPrice += parseFloat(cart.salePrice) * parseFloat(cart.orderNum) * parseFloat(cart.conversionRate);
        selectNum += parseFloat(cart.orderNum);
      }
    }
    this.setState({
      allPrice,
      selectNum,
      cartCheckStatus
    });
  }
  // 去下单
  goBuyBtn() {
    const { dispatch } = this.props;
    const { cartCheckStatus } = this.state;
    const checkData = this.getCheckedData(cartCheckStatus);
    if (!checkData) {
      message.warning("请选择商品!");
      return;
    }
    dispatch(
      routerRedux.push({
        pathname: "/buyer/orderEdit",
        cartData: checkData
      })
    );
  }
  // 购买数量改变
  orderNumChange(index, cartGroupItem, num) {
    const { dispatch } = this.props;
    let { cartListData } = this.props;
    cartListData = cartListData.concat([]);
    let newCartlistData = '';
    for (let i = 0; i < cartListData.length; i++) {
        if (cartListData[i].saleOrgCode == cartGroupItem.saleOrgCode) {
            newCartlistData = cartListData[i].cartlist;
            const conversionRate = parseFloat(newCartlistData[index][`conversionRate`] || "1");
            newCartlistData[index][`orderNum`] = num;
            newCartlistData[index][`mainNum`] = num * conversionRate;
            cartListData[i].cartlist[index][`orderNum`] = num;
            cartListData[i].cartlist[index][`mainNum`] = num * conversionRate;
        }
    }
    dispatch({
      type: "cartList/updateCart",
      payload: newCartlistData[index]
    }).finally(() => {
      dispatch({
        type: "cartList/cartListData",
        cartListData: cartListData
      });
    });
  }
  // checkAll全选
  checkAllClick(cartGroupItem) {
    const cartCheckStatus =
      this.state.cartCheckStatus || this.props.cartCheckStatus;

    if (!cartCheckStatus[cartGroupItem.saleOrgId]) {
      // 勾选供货方则自动选择所有子元素
      cartCheckStatus[`checkedSize${cartGroupItem.saleOrgId}`] =
        cartCheckStatus[`childSize${cartGroupItem.saleOrgId}`];
      for (const i in cartCheckStatus) {
        if (i.startsWith(cartGroupItem.saleOrgId)) {
          cartCheckStatus[i] = true;
        } else if (
          i.startsWith("checkedSize") &&
          !i.startsWith(`checkedSize${cartGroupItem.saleOrgId}`)
        ) {
          cartCheckStatus[i] = 0;
        } else if (!i.startsWith("childSize")) {
          cartCheckStatus[i] = false;
        }
      }
    } else {
      // 反选供货方则反选其所有子元素
      cartCheckStatus[`checkedSize${cartGroupItem.saleOrgId}`] = 0;
      for (const i in cartCheckStatus) {
        if (i.startsWith(cartGroupItem.saleOrgId)) {
          cartCheckStatus[i] = false;
        }
      }
    }
    this.allPrice(cartCheckStatus);
  }
  // 选中商品,改变状态
  goodsCheckChange(groupId, cartId) {
    const { dispatch } = this.props;
    const cartCheckStatus =
      this.state.cartCheckStatus || this.props.cartCheckStatus;
    const key = `${groupId}${cartId}`;
    cartCheckStatus[key] = !cartCheckStatus[key];
    // 供货方分组计数
    if (cartCheckStatus[key]) {
      cartCheckStatus[`checkedSize${groupId}`] += 1;
    } else {
      cartCheckStatus[`checkedSize${groupId}`] -= 1;
    }
    // 所有子元素被选择则自动勾选供货方分组
    if (
      cartCheckStatus[`checkedSize${groupId}`] ===
      cartCheckStatus[`childSize${groupId}`]
    ) {
      cartCheckStatus[groupId] = true;
    } else {
      cartCheckStatus[groupId] = false;
    }
    // 反选其他供货方分组数据
    for (const i in cartCheckStatus) {
      if (
        !i.startsWith(groupId) &&
        !i.startsWith("childSize") &&
        !i.startsWith(`checkedSize${groupId}`)
      ) {
        cartCheckStatus[i] = false;
        if (i.startsWith("checkedSize")) {
          cartCheckStatus[i] = 0;
        }
      }
    }
    this.allPrice(cartCheckStatus);
  }
  // 商品单项删除
  deleteGoods(cartItem) {
    const { dispatch } = this.props;
    // 删除后台
    dispatch({
      type: "cartList/deleteCartListData",
      payload: { id: cartItem.id }
    });
  }
  // 删除选中商品
  selectDelete() {
    const { cartCheckStatus } = this.state;
    const { cartListData, dispatch } = this.props;

    const checkData = this.getCheckedData(cartCheckStatus);
    if (!checkData || checkData.lenght == 0) {
      message.warning("请选择商品!");
    }
    const ids = [];
    for (const data of checkData.cartlist) {
      ids.push(data.id);
    }
    // 删除后台
    dispatch({
      type: "cartList/deleteCartListData",
      payload: { id: ids.join(",") }
    });
  }

  // 删除选中商品
  deleteAll() {
    // const { cartCheckStatus } = this.state;
    // const { cartListData, dispatch } = this.props;

    // const checkData = this.getCheckedData(cartCheckStatus);
    // if (!checkData || checkData.lenght == 0) {
    //   message.warning("请选择商品!");
    // }
    // const ids = [];
    // for (const data of checkData.cartlist) {
    //   ids.push(data.id);
    // }
    // 删除后台
    const { dispatch } = this.props;
    dispatch({
      type: "cartList/deleteAllCartListData"
    });
  }
   // 图片加载失败
   imgErro(e) {
    e.target.src = erroImg;
  }
  // 跳转详情
  toDetailHandle(data, e) {
    e.preventDefault();
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: "/buyer/goods/GoodsDetail",
        query: {
          code: data.code,
          id: data.goodsId,
          saleOrgId: data.saleOrgId ? data.saleOrgId : data.supplier,
          productId: data.productId
        }
      })
    );
    localStorage.setItem("goodsSku", data.code);
    localStorage.setItem("goodsDetailsId", data.goodsId);  // 商品Id
    localStorage.setItem("goodsDetailSsaleOrgId", data.saleOrgId ? data.saleOrgId : data.supplier);  // 供应商
    localStorage.setItem("goodsDetailProductId", data.productId);  // 产品id
  }
  render() {
    const { cartListData } = this.props;
    const { allPrice, selectNum, cartCheckStatus } = this.state;
    // 返回是否全选状态
    const checkAllStatus = cartGroupItem => {
      if (!cartCheckStatus) return false;
      return cartCheckStatus[cartGroupItem.saleOrgId];
    };
    // 商品列表-子表
    const goodsListChildHtml = cartGroupItem => {
      if (!cartGroupItem.cartlist) return null;
      const html = cartGroupItem.cartlist.map((item, index) => (
        <div
          className={styles.goodsChildList}
          key={`${cartGroupItem.saleOrgId}${item.goodsId}-${index}`}
        >
          <div className={styles.goodsNameBox}>
            <div className={styles.goodsCheck}>
              <Checkbox
                onChange={this.goodsCheckChange.bind(
                  this,
                  cartGroupItem.saleOrgId,
                  item.id
                )}
                checked={
                  cartCheckStatus
                    ? cartCheckStatus[`${cartGroupItem.saleOrgId}${item.id}`]
                    : false
                }
              />
            </div>
            <div className={styles.imgBox}>
              <LazyLoad height={60} offsetVertical={60}>
                <img src={item.goodsImg ? item.goodsImg : erroImg} alt="" onError={this.imgErro.bind(this)}  style={{ width: '60px', height: '60px', border: '1px solid #eee', cursor: 'pointer' }} onClick={this.toDetailHandle.bind(this, item)} />
              </LazyLoad>
            </div>
            <div className={styles.goodsInfo}>
              <p className={styles.goodsTitleName}>{item.goodsDisplayName.length > 20 ? `${item.goodsDisplayName.substr(0, 20)}...` : item.goodsDisplayName}</p>
              <p style={{ color: '#999','fontSize': '12px', margin: '0px'}}>
                <span>编码：{item.goodsCode}</span>
                <span style={{'marginLeft': '20px'}}>型号：{item.model}</span>
              </p>
              <p style={{ color: '#999','fontSize': '12px', margin: '0px'}}>
                <span>规格：{item.specification}{item.specification.indexOf("/") >= 0 ? "" : item.mainNumUnitName}</span>
              </p>
            </div>
          </div>
          <div className={styles.goodsColorBox}>
            <span className={styles.color}>
              {item.baseGoodsOptValue}
            </span>
              <em className={styles.cell}></em>
          </div>
          <div className={styles.goodsPriceBox}>
            <span className={styles.price}>
              {amountPrecision(item.salePrice)}{" "}
            </span>
            <em className={styles.cell}>/{item.mainNumUnitName}</em>
          </div>
          <div className={styles.goodsNumBox}>
            <div className={styles.numIptBox}>
              <GoodsBuyIpt
                num={item.orderNum}
                onChange={this.orderNumChange.bind(this, index, item)}
              />
            </div>
            <span className={styles.cell}>{item.orderNumUnitName}</span>
          </div>
          <div className={styles.goodsCartBox}>
            {amountPrecision(parseFloat(item.salePrice) * parseFloat(item.orderNum) * parseFloat(item.conversionRate), 'amount')}
          </div>
          <div className={styles.goodsFocusBox}>
            <CustIcon
              type="icon-icon-heart"
              style={{ fontSize: 26 }}
            />
            <Popconfirm
              title="确定要删除此行？"
              onConfirm={this.deleteGoods.bind(this, item)}
            >
              <CustIcon
                type="icon-icon-delete"
                style={{ fontSize: 26, marginLeft: 15 }}
              />
            </Popconfirm>
          </div>
        </div>
      ));
      return html;
    };
    // 商品；列表
    const goodsListHtml = () => {
      const html = [];
      if (!cartListData || cartListData.length == 0) {
        return (
          <div className={styles.noData}>暂无数据</div>
        );
      }
      for (let i = 0; i < cartListData.length; i++) {
        const item = cartListData[i];
        html.push(
          <div className={styles.goodsItem} key={item.saleOrgId}>
            {/* 商品经销商 */}
            <div className={styles.goodsHead}>
              <Checkbox
                checked={checkAllStatus(item)}
                onChange={this.checkAllClick.bind(this, item)}
              />
              <span className={styles.name}>{item.saleOrgName || item.supplierName}</span>
              <span className={styles.sortItem}>
                编码排序<Icon type="arrow-up" className={styles.icon} />
              </span>
              <span className={styles.sortItem}>
                时间排序<Icon type="arrow-up" className={styles.icon} />
              </span>
            </div>
            {/* 商品经销商--end */}
            {goodsListChildHtml(item, i)}
          </div>
        );
      }
      return html;
    };
    return (
      <div className={styles.cartListBox}>
        <div className={styles.goodsListHead}>
          <div className={styles.goodsDisplayName}>商品</div>
          <div className={styles.goodsColor}>颜色</div>
          <div className={styles.goodsPrice}>单价</div>
          <div className={styles.goodsNum}>订货量</div>
          {/* <div className={styles.goodsMainNum}>主数量</div>
          <div className={styles.goodsInventory}>库存</div> */}
          <div className={styles.goodsCart}>金额小计</div>
          <div className={styles.goodsFocus}>操作</div>
        </div>
        <div className={styles.goodsList}>{goodsListHtml()}</div>
        <div className={styles.settleBox}>
            <Popconfirm
              title="确定要删除已选行？"
              onConfirm={this.selectDelete.bind(this)}
            >
              <span className={styles.deleteBtn}>删除选中商品</span>
            </Popconfirm>
            <Popconfirm
              title="确定要删除清除购物车？"
              onConfirm={this.deleteAll.bind(this)}
            >
              <span className={styles.deleteBtn}>一键清除</span>
            </Popconfirm>
            {/* <span className={styles.focusBtn}>移入关注</span> */}
            <Button
              className={styles.goBuyBtn}
              onClick={this.goBuyBtn.bind(this)}
            >
              去下单
            </Button>
            <span className={styles.allPrice} style={{ paddingRight: 20 }}>
              <em className={styles.price}>{amountPrecision(allPrice, 'amount')}</em>
            </span>
            <span className={styles.allPrice} style={{ marginTop: 5 }}>总价:</span>
            <span className={styles.selectNum}>
              已选择<em className={styles.num}> {selectNum} </em>件商品
            </span>
        </div>
      </div>
    );
  }
}

export default connect(state => ({
  cartListData: state.cartList.cartListData,
  cartCheckStatus: state.cartList.cartCheckStatus
}))(CartListComp);
