import React, { PureComponent } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Menu, Icon, Pagination, Spin, message } from "antd";
import LazyLoad from "react-lazy-load";
import classnames from "classnames";
import iconfontStyles from "../../iconfont/iconfont.css";

import styles from "./index.less";
import imgSrc from "./goods-img.png";
import GoodsBuyIpt from "../GoodsBuyIpt/index.js";
import CustIcon, { STATUS as IconStatus } from "../CustIcon";

import Fly from "@/utils/fly";
import erroImg  from "@/assets/imgError.png";
import { amountPrecision } from '@/utils/utils';
import { getCustomer } from '@/utils/request';
import { goodsVersion, toGoodsDetailHandle } from '@/utils/common';

/**
 * 商品中心-商品显示-列表方式
 */
class GoodsList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      refresh: false
    };
  }
  // 购买数量改变
  orderNumChange(index, num) {
    const { goodsData, dispatch } = this.props;
    goodsData[index][`orderNum`] = num;
    dispatch({
      type: "goodsPurchase/goodsData",
      goodsData: goodsData
    });
    this.setState({ refresh: !this.state.refresh });
  }
  // 跳转详情
  toDetailHandle(data, e) {
    toGoodsDetailHandle(this.props, data, e);
  }
  // 购物车飞入动画
  iconFly(element) {
    // 动画起始定位
    const sourcePostion = {
      left: element.offsetLeft, // 开始位置（必填）#fly元素会被设置成position: fixed
      top: element.offsetTop - window.scrollY - 30 // 开始位置（必填）
    };
    // 动画目标定位
    const targetPostion = {
      left: document.querySelector(".header-btn-add-shopcart").offsetLeft, // 结束位置（必填）
      top:
        document.querySelector(".header-btn-add-shopcart").offsetTop -
        window.scrollY // 结束位置（必填）
    };
    // fly options
    const options = {
      start: {
        width: element.offsetWidth, // 开始时高度
        height: element.offsetHeight, // 开始时高度
        ...sourcePostion
      },
      end: {
        width: element.offsetWidth, // 结束时高度
        height: element.offsetHeight, // 结束时高度
        ...targetPostion
      },
      autoPlay: false, // 是否直接运动,默认true
      speed: 2.0, // 越大越快，默认1.2
      vertex_Rtop: 100 // 运动轨迹最高点top值，默认20
      // onEnd: () => {} // 结束回调
    };
    const IconFly = new Fly(element, options);
    IconFly.play();
  }
  // 加入购物车
  addCart(item, ele) {
    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
      }
    });
  }
  // 关注商品 & 取消商品
  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.storeId
    };
    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 });
    });
  }
  // 图片加载失败
  imgErro(e) {
    e.target.src = erroImg;
  }
  tabLoading(data) {
    if (data == 0) {
        return (
            <div style={{ textAlign: 'center', height: '80px', lineHeight: '80px', marginTop: 10 }}>
                <Spin size="large" />
            </div>
        );
    } else if (data == 1) {
        return (
            <div className="ant-table-placeholder">暂无数据</div>
        );
    }
  }
  render() {
    const { goodsData, isShow, tabLoading } = this.props;
    // 商品列表
    const goodsListHtml = data => {
      if (tabLoading) return (this.tabLoading(0));
      if (!data || data.length == 0) return (this.tabLoading(1));
      const html = data.map((item, index) => (
        <div className={styles.goodsItem} key={item.code}>
          <div className={styles.goodsNameBox}>
            <div
              className={styles.imgBox}
              onClick={this.toDetailHandle.bind(this, item)}
            >
              <LazyLoad height={60} offsetVertical={60}>
                <img src={item.mainPictureFileUrl ? item.mainPictureFileUrl : erroImg} alt="" onError={this.imgErro.bind(this)} />
              </LazyLoad>
            </div>
            <div className={styles.goodsInfo}>
              <p className={styles.goodsTitleName}>
                <span className={styles.goodsStatus} style={{ display: item.isNew ? "inline-block" : "none" }} >
                  <span className={styles.goodsStatusTxt}>新</span>
                </span>
                {item.displayName}
                {item.isOptional == "1" ? <span class={styles.goodsColorMask}>调</span> : ""}
              </p>
              {/* <p className={styles.goodsCode}>{item.code}{goodsVersion(item.version)}</p> */}
              <p className={styles.goodsCode}>
                <span>编码：{item.code}</span>
                <span className={styles.model}>型号：{item.model}</span>
              </p>
              <p className={styles.goodsCode}>规格：{item.specification}</p>
            </div>
          </div>
          {/* <div className={styles.supplierBox}>
            <span title={item.saleOrgName || item.supplierName}>
              {item.saleOrgName || item.supplierName}
            </span>
          </div> */}
          <div className={styles.goodsPriceBox}>
            <span className={styles.price}>
              {item.baseDiscountPrice ? amountPrecision(item.baseDiscountPrice) : '0.00'}{" "}
              <em className={styles.cell}>/{item.basicUnitName}</em>
            </span>
          </div>
          {/* <div className={styles.goodsInventoryBox}>
            <span className={styles.InventoryNum}>
              {item.stock}{" "}
              <em className={styles.cell}>{item.basicUnitName}</em>
            </span>
          </div> */}
          <div className={styles.goodsNumBox}>
            <div className={styles.numIptBox}>
              <GoodsBuyIpt
                num={item.orderNum}
                onChange={this.orderNumChange.bind(this, index)}
              />
            </div>
            <span className={styles.cell}>{item.assistUnitName}</span>
          </div>
          {/* <div className={styles.goodsMainNumBox}>
            <span className={styles.MainNum}>
              {item.orderNum * item.conversionRate}{" "}
              <em className={styles.cell}>{item.basicUnitName}</em>
            </span>
          </div> */}
          <div className={styles.goodsCartBox}>
            <CustIcon
              type="icon-icon-shoppingcart"
              status={(item.baseDiscountPrice && item.stock && item.baseDiscountPrice > 0 && item.stock > 0) ? item.inCart : IconStatus.DISABLE}
              onClick={this.addCart.bind(this, item)}
            />
            <CustIcon
             // status={item.inFav}
              type={item.inFav ? "icon-icon-heart-i" : "icon-icon-heart"}
              style={{ color: item.inFav ? '#E14C46' : '#333', marginLeft: '30px' }}
              onClick={this.ifClickAlert.bind(this, item, index)}
            />
          </div>
        </div>
      ));
      return html;
    };
    return (
      <div
        className={styles.goodsListBox}
        style={{ display: isShow ? "block" : "none" }}
      >
        <div className={styles.goodsListHead}>
          <div className={styles.goodsDisplayName}>商品</div>
          {/* <div className={styles.supplierName}>供货方</div> */}
          <div className={styles.goodsPrice}>价格</div>
          {/* <div className={styles.goodsInventory}>库存</div> */}
          <div className={styles.goodsNum}>订货量</div>
          {/* <div className={styles.goodsMainNum}>主数量</div> */}
          <div className={styles.goodsCart}>操作</div>
        </div>
        <div className={styles.goodsList}>{goodsListHtml(goodsData)}</div>
      </div>
    );
  }
}
export default GoodsList;
