import React, { PureComponent } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Menu, Icon, message } from "antd";
import iconfontStyles from "../../iconfont/iconfont.css";
import styles from "./index.less";
// import GoodsSmall from "../GoodsSmall/index.js";
import imgsrc from "./goodsHot.png";
import GoodsBuyIpt from "../GoodsBuyIpt/index.js";

import CustIcon, { STATUS as IconStatus } from "../CustIcon";
import erroImg  from "@/assets/imgError.png";
import { amountPrecision } from '@/utils/utils';
import { getCustomer } from '@/utils/request';

class GoodsCommon extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
        refresh: false
    };
  }
  componentWillMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "goodsCommon/getGoodsCommon",
      payload: null
    });
    dispatch({
      type: "cartList/getCartListData"
  });
  }
  // 购买数量改变
  buyNumChange(key, num) {
    const { goodsAllData } = this.props;
    goodsAllData[key][`orderNum`] = num;
    this.props.dispatch({
      type: "goodsCommon/goodsAllData",
      goodsAllData: goodsAllData
    });
  }
  // 增加购物车
  addCartHandle(item, e) {
    e.preventDefault();
    const { dispatch } = this.props;
    if (!item.baseDiscountPrice || !item.stock || item.baseDiscountPrice <= 0 || item.stock <= 0) {
      return false;
    }
    if (item.orderNum < 1) {
      message.warning("添加数量不能为0!");
      return;
    }
    const mainNum = parseFloat(item.orderNum || 1) * parseFloat(item.conversionRate || 1);
    const postData = {
      orderNum: item.orderNum || 1,
        mainNum: mainNum,
        goodsId: item.id,
        goodsDisplayName: item.displayName,
        goodsName: item.name,
        goodsCode: item.code,
        goodsImg: item.mainPictureFileUrl,
        orderNumUnitId: item.assistUnitId,
        orderNumUnitCode: item.assistUnitCode,
        orderNumUnitName: item.assistUnitName,
        orderNumUnitScale: item.orderNumUnitScale || 0,
        mainNumUnitId: item.basicUnitId,
        mainNumUnitCode: item.basicUnitCode,
        mainNumUnitName: item.basicUnitName,
        mainNumUnitScale: item.basicUnitPrecision || 0,
        weight: item.grossWeight, // 默认取毛重
        ...item
    };
    dispatch({
      type: "cartList/addCart",
      payload: postData
    }).finally(() => {
      message.warning('已加入购物车');
    });
  }
  // 关注商品 & 取消商品
  addAndDelStore(item, index) {
    const { dispatch } = this.props;
    const postData = !item.inFav ? {
        customerId: getCustomer().id,
        goodsId: item.id,
        goodsImg: item.mainPictureFileUrl,
        isPrimaryChannel: 1,
        saleOrgId: item.saleOrgId,
        supplierId: null
    } : {
        customer: getCustomer().id,
        id: item.id
    };
    const url = item.inFav ? "public/getDelStore" : "public/getAddStore";
    dispatch({
      type: url,
      payload: postData
    }).finally(() => {
        const { goodsAllData } = this.props;
        goodsAllData[index].inFav = !goodsAllData[index].inFav;
        const message = item.inFav ? "已关注" : "已取消关注";
        message.warning(message);
        dispatch({
            type: "goodsCommon/goodsAllData",
            goodsAllData: goodsAllData
        });
        this.setState({ refresh: !this.state.refresh });
    });
  }
  // 跳转详情
  toDetailHandle(data, e) {
    e.preventDefault();
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: "/buyer/goods/GoodsDetail",
        query: {
          code: data.code,
          id: data.id,
          saleOrgId: data.saleOrgId ? data.saleOrgId : data.supplier,
          productId: data.productId
        }
      })
    );
    localStorage.setItem("goodsSku", data.code);
    localStorage.setItem("goodsDetailsId", data.id);  // 商品Id
    localStorage.setItem("goodsDetailSsaleOrgId", data.saleOrgId ? data.saleOrgId : data.supplier);  // 供应商
    localStorage.setItem("goodsDetailProductId", data.productId);  // 产品id
  }
  // 跳转商品列表页
  toGoodsPurchase() {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: "/buyer/goodsPurchase"
      })
    );
  }
  // 图片加载失败
  imgErro(e) {
    e.target.src = erroImg;
  }
  render() {
    const { goodsAllData, cartListData } = this.props;
    if (!goodsAllData || goodsAllData.length === 0) {
      return null;
    }
    if (cartListData && goodsAllData) {
      for (const cartGroup of cartListData) {
          if (cartGroup && cartGroup.cartlist) {
              const cartList = cartGroup.cartlist;
              for (const cart of cartList) {
                  for (const goods of goodsAllData) {
                      if (cart.goodsId === goods.id) {
                          goods.inCart = true;
                      }
                  }
              }
          }
      }
  }
    const goodsHotListHtml = () => {
      const html = goodsAllData.map((item, index) => (
        <li className={styles.goodsHotItem} key={item.id} style={index % 4 == 0 && index != 0 ? { marginRight: 0 } : { marginRight: 10 }}>
          <div className={styles.goodsHot}>
            <div
              className={styles.imgBox}
              onClick={this.toDetailHandle.bind(this, item)}
            >
              <img src={item.mainPictureFileUrl ? item.mainPictureFileUrl : erroImg} alt="" onError={this.imgErro.bind(this)} className={styles.img} />
            </div>
            {/* 商品信息 */}
            <div className={styles.goodsHotInfobox}>
              <div className={styles.goodsHotTitlebox}>
                <span className={styles.goodsTitle}>{item.displayName}</span>
              </div>
              <div className={styles.codeBox}>
                <div>
                  <span>编码: {item.code}</span>
                  <span className={styles.cell} title={`${item.model}`}>型号：{item.model}</span>
                </div>
                <div>
                  <span>规格: {item.specification}</span>
                </div>
              </div>
              <div className={styles.goodsHotCodeBox}>
                <span className={styles.goodsHotPrice}>{item.baseDiscountPrice ? amountPrecision(item.baseDiscountPrice) : '0.00'}</span>
              </div>
            </div>
            {/* 商品信息 --结束 */}
            {/* 鼠标移入 */}
            <div className={styles.goodsHotHoverBox}>
              <div className={styles.goodsCollect} onClick={this.addAndDelStore.bind(this, item, index)}>
                <CustIcon
                  type={item.inFav ? "icon-icon-heart-i" : "icon-icon-heart"}
                  style={{ fontSize: 20, color: item.inFav ? '#E14C46' : '#333' }}
                />
              </div>
              <div className={styles.iptBox}>
                <GoodsBuyIpt
                  onChange={this.buyNumChange.bind(this, index)}
                  num={1}
                />
              </div>
              <div
                className={styles.addCart}
                onClick={this.addCartHandle.bind(this, item)}
              >
                  <CustIcon
                    type="icon-icon-shoppingcart"
                    status={(item.baseDiscountPrice && item.stock && item.baseDiscountPrice > 0 && item.stock > 0) ? item.inCart : IconStatus.DISABLE}
                    style={{ fontSize: 20, color: '#333' }}
                  />
              </div>
            </div>
            {/* 鼠标移入--结束 */}
            {/* 促销 状态 *
            <div className={styles.goodsStatusBox}>
              <i className={styles.goodsStatusNew}>新品</i>
              <i className={styles.goodsStatusSale}>促销</i>
            </div>
            {/* 促销 状态 --结束 */}
          </div>
        </li>
      ));
      return html;
    };
    return (
      <div className={styles.allGoodsBox}>
        <div className={styles.heardbox}>
          <span className={styles.title}>全部商品</span>
          <span
            className={styles.more}
            onClick={this.toGoodsPurchase.bind(this)}
          >
            更多 <CustIcon type="icon-icon-right" style={{ fontSize: 16 }} />
          </span>
        </div>
        <div className={styles.goodsHotBox}>
          <ul className={styles.goodsHotList} key="goods_ul">
            {goodsHotListHtml()}
          </ul>
        </div>
      </div>
    );
  }
}
export default connect(state => ({
  goodsAllData: state.goodsCommon.goodsAllData,
  cartListData: state.cartList.cartListData,
}))(GoodsCommon);
