import React, { PureComponent } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Menu, Icon, Pagination, message } from "antd";
import styles from "./index.less";
// import GoodsSmallTable from "../GoodsSmallTable/index.js";
import CustIcon, { STATUS as IconStatus } from "../CustIcon";
import GoodsBuyIpt from "../GoodsBuyIpt/index.js";
import erroImg  from "@/assets/imgError.png";
import { getCustomer } from '@/utils/request';
import { amountPrecision } from '@/utils/utils';
import { goodsVersion } from '@/utils/common';

class GoodsTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      refresh: false
    };
  }
  // 购买数量改变
  buyNumChange(index, num) {
    const { goodsData, dispatch } = this.props;
    goodsData[index][`orderNum`] = num;
    dispatch({
      type: "goodsPurchase/goodsData",
      goodsData: goodsData
    });
  }
  // 增加购物车
  addCartHandle(item, index, ele) {
    ele.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;
      }
      if (item.isOptional == "1") {
        message.warning("请到商品详情页面选择商品颜色!");
        return;
      }      
    // this.iconFly(ele.target);
    const mainNum = parseFloat(item.orderNum || 1) * parseFloat(item.conversionRate || 1);
    dispatch({
      type: "cartList/addCart",
      payload: {
        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
      }
    }).finally(() => {
      const { goodsData } = this.props;
      goodsData[index].inCart = true;
      message.warning('已加入购物车');
      dispatch({
          type: "goodsPurchase/goodsData",
          goodsData: goodsData
      });
    });
  }
   // 关注商品 & 取消商品
   ifClickAlert(item, index) {
    // IconFly.destroy();
    const { goodsData, dispatch } = this.props;
    const postData = !goodsData[index].inFav ? {
      customerId: getCustomer().id,
      goodsId: item.id,
      goodsImg: item.mainPictureFileUrl,
      isPrimaryChannel: 1,
      saleOrgId: item.saleOrgId,
      supplierId: item.supplierId
    } : {
      customer: getCustomer().id,
      id: item.id
    };
    const url = goodsData[index].inFav ? "public/getDelStore" : "public/getAddStore";
    dispatch({
      type: url,
      payload: postData
    }).finally(() => {
      const { goodsData } = this.props;
      goodsData[index].inFav = !goodsData[index].inFav;
      const message = item.inFav ? "已关注" : "已取消关注";
      message.warning(message);
      dispatch({
          type: "goodsPurchase/goodsData",
          goodsData: goodsData
      });
      this.setState({ refresh: !this.state.refresh });
    });
  }
  // 跳转详情
  toDetailHandle(data, e) {
    e.preventDefault();
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        /* pathname: "/buyer/CommodityDetails", */
        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
  }
  // imgErro 图片加载失败
  imgErro(e) {
    e.target.src = erroImg;
  }
  render() {
    const { goodsData, isShow } = this.props;
    // 判断是否新品和促销
    const isNewHtml = (isNew, isPromot) => {
      let html;
      if (isNew) {
        if (isPromot) {
          html = (
            <div className={styles.goodsStatusBox}>
              <i className={styles.goodsStatusNew}>新品</i>
              <i className={styles.goodsStatusSale}>促销</i>
            </div>
          );
        } else {
          html = (
            <div className={styles.goodsStatusBox}>
              <i className={styles.goodsStatusNew}>新品</i>
            </div>
          );
        }
      } else if (isPromot) {
        html = (
          <div className={styles.goodsStatusBox}>
            <i className={styles.goodsStatusSale}>促销</i>
          </div>
        );
      }
      return html;
    };
    // 商品列表
    const goodsListHtml = () => {
      if (!goodsData) return null;
      const html = goodsData.map((item, index) => (
        <li
          className={styles.goodsHotItem}
          key={item.code}
          style={index % 5 == 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={{}} className={styles.img} onError={this.imgErro.bind(this)} />
            </div>
            {/* 商品信息 */}
            <div className={styles.goodsHotInfobox}>
              <div className={styles.goodsHotCodeBox}>
                <span className={styles.goodsHotPrice}>{item.baseDiscountPrice ? amountPrecision(item.baseDiscountPrice) : '0.00'}</span>
              </div>
              <div className={styles.goodsHotTitlebox}>
                <span className={styles.goodsTitle}>
                  {item.displayName}
                  {item.isOptional == "1" ?  <span class={styles.goodsColorMask}>调</span> : ""}
                </span>
              </div>
              <div className={styles.codeBox}>
                {/* <span className={styles.code} title={`${item.code} V${item.version}.0`}>编码: {item.code}{goodsVersion(item.version, "card")}</span> */}
                <span className={styles.code} title={`${item.code}`}>编码: {item.code}</span>
                <span className={styles.cell} title={`${item.model}`}>型号：{item.model}</span>
              </div>
              <div className={styles.codeBox}>
                {/* <span className={styles.code} title={`${item.code} V${item.version}.0`}>编码: {item.code}{goodsVersion(item.version, "card")}</span> */}
                <span className={styles.code} title={`${item.specification}`}>规格: {item.specification}</span>
              </div>
            </div>
            {/* 鼠标移入 */}
            <div className={styles.goodsHotHoverBox}>
              <div className={styles.goodsCollect} onClick={this.ifClickAlert.bind(this, item, index)}>
                <CustIcon
                  type={item.inFav ? "icon-icon-heart-i" : "icon-icon-heart"}
                  style={{ color: item.inFav ? '#E14C46' : '#333', fontSize: 20 }}
                />
              </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, index)}
              >
                  <CustIcon
                    status={(item.baseDiscountPrice && item.stock && item.baseDiscountPrice > 0 && item.stock > 0) ? item.inCart : IconStatus.DISABLE}
                    type="icon-icon-shoppingcart"
                    style={{ fontSize: 20, color: '#333' }}
                  />
              </div>
            </div>
            {/* 商品信息 --结束 */}
            {/* 促销 状态 */}
            {isNewHtml(item.isNew, item.isPromot)}
            {/* 促销 状态 --结束 */}
          </div>
        </li>
      ));
      return html;
    };
    return (
      <div
        className={styles.goodsTableBox}
        style={{ display: isShow ? "block" : "none" }}
      >
        <div className={styles.allGoodsBox}>
          <div className={styles.goodsHotBox}>
            <ul className={styles.goodsHotList}>{goodsListHtml()}</ul>
          </div>
        </div>
      </div>
    );
  }
}
export default GoodsTable;
