import React, { Component } from "react";
import antd, {
  Layout,
  Menu,
  Icon,
  Card,
  Input,
  Button,
  message,
  Popover,
  Row,
  Col,
  Dropdown
} from "antd";
import { connect } from "dva";
import { Link, routerRedux } from "dva/router";

import className from "classnames";

import styles from "./HomeLayout.less";
import logoImg from "@/assets/logo.png";
import MenuDatas from "./menuDatas.json";
import CustIcon from "@/components/CustIcon";
import BreadcrumbPackage from "@/components/BreadcrumbPackage/index.js";
import { getCustomer } from "@/utils/request";

const { Header, Content } = Layout;
const { SubMenu } = Menu;
const { Search } = Input;

class HomeLayout extends Component {
  constructor(props) {
    super(props);
    this.state = {
      menuDefaultSelectedKeys: "0"
    };
  }
  componentWillMount() {
    const { dispatch } = this.props;
    // 获取购物车数量
    dispatch({
      type: "cartList/getCartNumData"
    });
    // 获取门户设置信息
    dispatch({
      type: "homeLayout/getPortalConfig"
    });
  }
  componentWillReceiveProps(nextProps) {
    if (
      nextProps.location.pathname != this.props.location.pathname ||
      nextProps.location.search != this.props.location.search
    ) {
      const menuItemPath = nextProps.location.pathname;
      const searchParam = nextProps.location.search;
      const { dispatch } = this.props;
      dispatch({
        type: "global/menuItem",
        menuItem: {
          menuItemPath: menuItemPath,
          searchParam: searchParam
        }
      });
      localStorage.setItem("menuItemPath", menuItemPath);
      localStorage.setItem("searchParam", searchParam);
      dispatch({
        type: "global/additems",
        additems: []
      });
    }
    // 购物车闪烁效果
    if ("cartNum" in nextProps && nextProps.cartNum !== this.props.cartNum) {
      let count = 0;
      const self = this;
      const cartFocusSeq = setInterval(() => {
        self.setState({
          cartFocus: !(self.state.cartFocus || false)
        });
        count++;
        if (count === 4) {
          clearTimeout(cartFocusSeq);
        }
      }, 200);
    }
    if ("cartStatus" in nextProps) {
      const cartStatus = nextProps.cartStatus;
      const { dispatch } = this.props;
      if (cartStatus && cartStatus == 200) {
        message.success("购物车添加成功!");
        dispatch({
          type: "homeLayout/cartNum",
          cartStatus: null
        });
      } else if (cartStatus && cartStatus != 200) {
        message.error("购物车添加失败!");
        dispatch({
          type: "homeLayout/cartNum",
          cartStatus: null
        });
      }
    }
  }
  getMenus(datas = MenuDatas) {
    const getIcon = icon => {
      if (icon) {
        return <Icon type={icon} />;
      }
    };
    return (
      <Menu
        theme="light"
        mode="horizontal"
        // onSelect={this.onSelectHandle.bind(this)}
        defaultSelectedKeys={[this.state.menuDefaultSelectedKeys]}
        className="home-menu"
      >
        {datas.map(data => {
          if (data.children && data.children.length > 0) {
            return (
              <SubMenu
                key={data.key}
                title={
                  <span>
                    {getIcon(data.icon)}
                    {data.title}
                  </span>
                }
                className="home-submenu"
                mode="horizontal"
              >
                {data.children.map(children => {
                  return (
                    <Menu.Item
                      key={children.key}
                      mode="horizontal"
                      className="home-submenu-item"
                    >
                      <Link to={children.path}>{children.title}</Link>
                    </Menu.Item>
                  );
                })}
              </SubMenu>
            );
          } else {
            return (
              <Menu.Item key={data.key}>
                <Link to={data.path}>{data.title}</Link>
              </Menu.Item>
            );
          }
        })}
      </Menu>
    );
  }
  getMoreOptions() {
    return (
      <Menu>
        <Menu.Item onClick={this.updatePassWordHandle.bind(this)}>
          <span>修改密码</span>
        </Menu.Item>
        <Menu.Item onClick={this.removeLocalStorateInfoHandle.bind(this)}>
          <span>
            注销
          </span>
        </Menu.Item>
      </Menu>
    );
  }

  getSubMenu(datas) {
    return datas.map(data => {
      return (
        <Menu.Item
          key={data.key}
          mode="horizontal"
          className="home-submenu-item"
        >
          <Link to={data.path}>{data.title}</Link>
        </Menu.Item>
      );
    });
  }
  getHotlineContent(hotlines) {
    if (!hotlines) return null;
    return (
      <div>
        {hotlines.map(item => {
          if (item.hotline) {
            return <p key={item.id}>{item.hotline}</p>;
          } else {
            return "";
          }
        })}
      </div>
    );
  }
  getAppContent(portalInfo) {
    if (!portalInfo) return null;
    return (
      <div className={styles.appCode}>
        <Row gutter={16}>
          <Col span={12}>
            <Card>
              <div>
                <img
                  alt="Ios"
                  width="80px"
                  height="80px"
                  src={portalInfo.iosCodeUrl}
                />
              </div>
              <div className={styles.tipTitle}>
                <h3>IOS</h3>
              </div>
            </Card>
          </Col>
          <Col span={12}>
            <Card>
              <div>
                <img
                  alt="Android"
                  width="80px"
                  height="80px"
                  src={portalInfo.androidCodeUrl}
                />
              </div>
              <div className={styles.tipTitle}>
                <h3>Android</h3>
              </div>
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
  removeLocalStorateInfoHandle() {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: "/gotoLogin"
      })
    );
    localStorage.removeItem("_A_P_customer");
    localStorage.removeItem("_A_P_currency");
  }
  updatePassWordHandle() {
    const { dispatch } = this.props;
    dispatch(routerRedux.push("/buyer/updatePassword"));
  }
  clickFun() { }
  // 全局搜索框
  overallSearch(val) {
    const { dispatch, location } = this.props;
    if (location.pathname.indexOf('buyer/goodsPurchase') > -1) {
      dispatch({
        type: "goodsPurchase/getGoodsData",
        payload: {
          search_keywords: val
        }
      })
    } else {
      dispatch(
        routerRedux.push({
          pathname: "/buyer/goodsPurchase",
          query: {
            keywords: val
          }
        })
      )
    }
  }
  render() {
    const { cartNum } = this.props;
    let { portalConfig } = this.props;
    portalConfig = portalConfig || [];
    const portalInfo = portalConfig[0] || {};
    //添加逻辑，只在render数据加载后进行判断（解决刷新时瞬间展示默认logo的bug）
    const styleImage = portalConfig.length==0 ? {} : {
      backgroundImage: `url(${portalInfo.logoUrl || logoImg})`,
      backgroundRepeat: "no-repeat",
      backgroundSize: "160px 60px"
    };
    let ifShowBreadcrumb = false;
    if (
      this.props.location &&
      this.props.location.pathname &&
      this.props.location.pathname.indexOf("/buyer") >= 0
    ) {
      ifShowBreadcrumb = true;
    }
    return (
      <Layout
        className="layout"
        style={{ backgroundColor: "white", position: "relative" }}
      >
        <div className={className(styles.headerTop)}>
          <div className="header-top-content">
            <div style={{ height: "34px" }}>
              <CustIcon
                type="icon-icon-cutover"
                style={{
                  fontSize: "20px",
                  color: "#999",
                  position: "absolute",
                  top: "1px"
                }}
              />
              <span className={styles.switchCustomer}>
                &nbsp;
                <a
                  style={{ color: "#333" }}
                  target="_blank"
                  rel="noopener noreferrer"
                  href="/wbalone/index.html"
                >
                  切换商家工作台
                </a>
              </span>
            </div>
            <div style={{ display: "flex", flexDirection: "row" }}>
              <div className={styles.item}>
                <Dropdown overlay={this.getMoreOptions()}>
                  <a
                    className="ant-dropdown-link"
                    href="#"
                    style={{ color: "#666" }}
                  >
                    {getCustomer().name}
                    <Icon type="down" />
                  </a>
                </Dropdown>
              </div>
              {/* <div className={styles.item}>
                <span className={styles.infobox}>
                  消息中心
                  <i className={styles.infoNum}>9</i>
                </span>
              </div>
              <div className={styles.item}>
                <span className={styles.name}>帮助中心</span>
              </div>
              <div className={styles.item}>
                <Popover
                  placement="bottomRight"
                  title=""
                  content={this.getHotlineContent(portalInfo.hotlines)}
                  trigger="click"
                >
                  <span className={styles.name}>服务热线</span>
                  <Icon type="down" className={styles.icon} />
                </Popover>
              </div> */}
              <div className={styles.item}>
                <Popover
                  placement="bottomRight"
                  title=""
                  content={this.getAppContent(portalInfo)}
                  trigger="click"
                >
                  <span className={styles.name}>手机端</span>
                  <Icon type="down" className={styles.icon} />
                </Popover>
              </div>
            </div>
          </div>
        </div>
        <Header className={styles.header}>
          <div className="logo">
            <a className={styles.logoImg} style={styleImage} href="#/" />
          </div>
          {this.getMenus()}
          <div className={styles.searchBar}>
            <Search
              className="header-search-input"
              placeholder="商品名称/编码/型号"
              onSearch={this.overallSearch.bind(this)}
              enterButton={<CustIcon type="icon-icon-search" />}
            />
            <Link to="/buyer/cartList">
              <Button
                className={`header-btn-add-shopcart ${
                  this.state.cartFocus ? styles.cartNumHover : ""
                  }`}
              >
                <CustIcon
                  type="icon-icon-shoppingcart"
                  style={{ fontSize: "22px" }}
                />
                <span className={styles.cartBus}>
                  <em style={{ marginLeft: 10, marginRight: 5 }}>购物车</em>
                  (
                    <em
                    className={styles.cartNum}
                  >
                    {cartNum}
                  </em>
                  )
                </span>
              </Button>
            </Link>
            <Button
              className="header-btn-order"
              type="primary"
              href="#/buyer/orderEdit"
            >
              下单
            </Button>
          </div>
        </Header>
        <Content
          className={styles.contentTopBox}
          style={{ maxWidth: 1200, margin: "0 auto" }}
        >
          <div
            className={styles.breadcrumbBox}
            style={{ display: ifShowBreadcrumb ? "block" : "none" }}
          >
            <BreadcrumbPackage />
          </div>
          { this.props.children }
        </Content>
      </Layout>
    );
  }
}
export default connect(state => ({
  cartNum: state.cartList.cartNum,
  cartStatus: state.cartList.cartStatus,
  portalConfig: state.homeLayout.portalConfig
}))(HomeLayout);
