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 GoodsBig from "../GoodsBig/index.js";
import GoodsBuyIpt from "../GoodsBuyIpt/index.js";

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

class GoodsHot extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      refresh: false
    };
  }
  componentWillMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "goodsHot/getGoodsHotData"
    });
    dispatch({
      type: "cartList/getCartListData"
    });
  }
  // 购买数量改变
  buyNumChange(key, num) {
    const { goodsHotData } = this.props;
    goodsHotData[key][`orderNum`] = num;
    this.props.dispatch({
      type: "goodsHot/goodsHotData",
      goodsHotData: goodsHotData
    });
  }
  // 增加购物车
  addCartHandle(item) {
    const { goodsHotData, 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 { goodsHotData, 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 { goodsHotData } = this.props;
      goodsHotData[index].inFav = !goodsHotData[index].inFav;
      const message = item.inFav ? "已关注" : "已取消关注";
      message.warning(message);
      dispatch({
        type: "goodsHot/goodsHotData",
        goodsHotData: goodsHotData
      });
      this.setState({ refresh: !this.state.refresh });
    });
  }
  // 跳转详情
  toDetailHandle(data) {
    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/replenishment/4"
      })
    );
  }
  // 图片加载失败
  imgErro(e) {
    e.target.src = erroImg;
  }
  render() {
    const { goodsHotData, cartListData } = this.props;
    if (cartListData && goodsHotData) {
      for (const cartGroup of cartListData) {
          if (cartGroup && cartGroup.cartlist) {
              const cartList = cartGroup.cartlist;
              for (const cart of cartList) {
                  for (const goods of goodsHotData) {
                      if (cart.goodsId === goods.id) {
                          goods.inCart = true;
                      }
                  }
              }
          }
      }
    }
    const goodsHotListHtml = () => {
      const goodsHotListData = goodsHotData && !goodsHotData.status ? goodsHotData : [];
      if (goodsHotListData.length == 0) return (<div className={styles.noGoodsHot}>暂无热销产品</div>);
      const html = goodsHotListData.map((item, index) => (
        <li className={styles.goodsHotItem} key={item.id} style={index == 0 ? { marginLeft: 0 } : { marginLeft: 13 }}>
          <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.length > 19 ? `${item.displayName.substr(0, 18)}...` : item.displayName}</span>
                <span className={styles.goodsColorMask}></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}>
                <div className={styles.goodsHotCode}>
                <span className={styles.goodsHotPrice}>{item.baseDiscountPrice ? amountPrecision(item.baseDiscountPrice) : '0.00'}</span>
                </div>
                <span className={styles.oldPrice}>{item.basePrice ? amountPrecision(item.basePrice) : '0.00'}</span>
              </div>
            </div>
            {/* 商品信息 --结束 */}
            {/* 鼠标移入 */}
            <div className={styles.goodsHotHoverBox}>
              <div className={styles.goodsCollect} onClick={this.addAndDelStore.bind(this, item)}>
                <CustIcon
                  type={item.inFav ? "icon-icon-heart-i" : "icon-icon-heart"}
                  style={{ fontSize: 26, 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: 26, color: '#333' }}
                />
              </div>
            </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)}
            style={goodsHotData && goodsHotData.length > 4 ? {} : { display: 'none' }}
          >
            更多 <CustIcon type="icon-icon-right" style={{ fontSize: 16 }} />
          </span>
        </div>
        <div className={styles.goodsHotBox}>
          <ul className={styles.goodsHotList}>{goodsHotListHtml()}</ul>
        </div>
      </div>
    );
  }
}
export default connect(state => ({
  goodsHotData: state.goodsHot.goodsHotData,
  cartListData: state.cartList.cartListData,
}))(GoodsHot);
