import React, { Component } from "react";
import { Layout, Menu, Icon, Carousel, Card, Badge, Tabs } from "antd";
import { connect } from "dva";
import { routerRedux, Link } from "dva/router";
import moment from "moment";
import styles from "./index.less";
import MenuComp from "@/components/GoodsLevel/index.js";
import GoodsHot from "@/components/GoodsHot/index.js";
import GoodsCommon from "@/components/GoodsCommon/index.js";
import GoodsHistory from "@/components/GoodsHistory/index.js";
import erroImg  from "@/assets/bannerError.png";

import CustIcon from "@/components/CustIcon";
import { getCustomer } from '@/utils/request';
import { amountPrecision } from '@/utils/utils';
import { toGoodsDetailHandle } from '@/utils/common';
const { Footer, Sider, Content } = Layout;
const TabPane = Tabs.TabPane;

const FundsDatas = [
  {
    title: "FundsContentCredit",
    icon: "icon-icon-cost",
    name: "信用余额"
  },
  {
    title: "FundsContentCost",
    icon: "icon-icon-credit",
    name: "费用余额"
  }
];

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ref: {}
    };
  }
  componentWillMount() {
    const { dispatch } = this.props;
    // 获取banner区展示商品
    dispatch({
      type: "home/getCarouselImgUrl"
    });
    // 获取Banner区轮播时间
    dispatch({
      type: "home/getAutoPlaySpeed"
    });
    // 获取公告
    dispatch({
      type: "home/getNoticeData"
    });
    // 获取待办事项
    dispatch({
      type: "home/getTodoDada"
    });
    // 信用余额
    dispatch({
      type: "credit/getCreditData",
      payload: {
        customerId: getCustomer().id
      }
    });
    // 费用余额
    dispatch({
      type: "public/castAmountByCustAndDate",
      payload: {
        search_customer: getCustomer().id,
        search_billDate_date: new Date().getTime()
      }
    });
  }
  getCarousel(datas) {
    if (!datas) return null;
    const { autoPlaySpeed } = this.props;
    let index = 0;
    let playSpeed = ((autoPlaySpeed || [])[0] || {}).autoPlaySpeed || "3";
    playSpeed = parseFloat(playSpeed) * 1000;
    return (
      <Carousel autoplay autoplaySpeed={playSpeed} key="carousel">
        {datas.map(data => {
          return (
            <img
              key={`img${data.productId}${++index}`}
              src={data.imgUrl ? data.imgUrl : erroImg}
              alt={data.productName}
              width={1200}
              height={460}
              style={{ width: 1200, height: 460 }}
              onClick={this.goodsDetailHandle.bind(this, data)}
              onError={this.imgErro.bind(this)}
            />
          );
        })}
      </Carousel>
    );
  }
  getTODOListData(datas = []) {
    const html = [];
    const items = {
      processCount: {
        key: "02",
        name: "待审核",
        icon: "icon-icon-review"
      },
      noSendCount: {
        key: "03",
        name: "待发货",
        icon: "icon-icon-delivery"
      },
      isSendCount: {
        key: "04",
        name: "待签收",
        icon: "icon-icon-DeliveryOrder"
      },
      noPayCount: {
        key: "06",
        name: "驳回",
        icon: "icon-icon-payment"
      }
    };
    const todos = {};
    datas.map(data => {
      return todos[data[0]] = data[1];
    });
    Object.keys(items).forEach(key => {
      const item = items[key];
      html.push(
        <div className={styles.todoListItem} key={key}>
          <Link to={`/buyer/orderList/${item.key}`} style={{ color: 'white' }}>
            <div className="todolist-icon-wrap">
              <Badge
                count={todos[item.key] || 0}
                offset={[10, 19]}
                overflowCount={99}
                className={styles.todoBadge}
              >
                <span>
                  <CustIcon type={item.icon} style={{ fontSize: 26, color: 'white'  }} />
                </span>
              </Badge>
            </div>
            <span className={styles.todolistTitle}>{item.name}</span>
          </Link>
        </div>
      );
    });
    return <div className={styles.todoList}>{html}</div>;
  }
  getAnnouncementHandle() {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: "/buyer/Announcement"
      })
    );
  }
  getNoticeDetail(item) {
    const { dispatch } = this.props;
    localStorage.setItem("id", item.noticeId);
    dispatch(
      routerRedux.push({
        pathname: "/buyer/NoticeDetail",
        noticeId: item.noticeId
      })
    );
  }
  getAnnouncementListTitleAndTime(data) {
    if (!data) return null;
    if (data.noticeInfoMap.length > 5) {
      data.noticeInfoMap = data.noticeInfoMap.slice(0, 5);
    }
    return (
      <ul>
        {data.noticeInfoMap.map(item => {
          let status = "error";
          let style = {
            color: "#E14C46"
          };
          if (item && item.isRead == "Y") {
            status = "default";
            style = {
              color: ""
            };
          }
          return (
            <li
              className={styles.noticeLi}
              key={item.noticeId}
              onClick={this.getNoticeDetail.bind(this, item)}
            >
              <span style={{ cursor: "pointer" }}><Badge status={status} /><span style={style} title={item.title}>{item.title}</span></span>
              <span
                style={{
                  float: "right",
                  color: "#999999",
                  fontSize: 12,
                  cursor: "pointer",
                  display: item.title == "暂无公告" ? 'none' : ''
                }}
              >
              </span>
            </li>
          );
        })}
      </ul>
    );
  }
  getAnnouncementList(data) {
    const datas = data && data.length > 0 ? data : [{ noticeTypeName: "全部", noticeInfoMap: [{ title: '暂无公告' }] }];
    let num = 0;
    const html = datas.map((data, index) => {
      num = index + 1;
      return (
        <TabPane tab={data.noticeTypeName} key={num}>
          {this.getAnnouncementListTitleAndTime(data)}
        </TabPane>
      );
    });

    return html;
  }
  getAnnouncement(datas) {
    const tabBarExtraContent = (
      <a
        style={{ color: "#666666" }}
        onClick={this.getAnnouncementHandle.bind(this)}
      >
        更多 <CustIcon type="icon-icon-right" style={{ fontSize: "16px" }} />
      </a>
    );
    return (
      <Card title="公告" className={styles.announcement} size="small">
        <Tabs>
          {this.getAnnouncementList(datas)}
        </Tabs>
      </Card>
    );
  }
  getTodoAndFunds(todoDada) {
    return (
      <Card>
        <Tabs size="small">
        <TabPane tab="待办任务" key={Math.random()}>
          {this.getTODOListData(todoDada)}
        </TabPane>
        <TabPane tab="资金池" key={Math.random()}>
          {this.getFunds()}
        </TabPane>
        </Tabs>
      </Card>
    );
  }
  getFunds(datas = FundsDatas) {
    const { creditData, castAmount } = this.props;
    let creditAmount = 0;
    if (creditData) {
      for (let i = 0; i < creditData.length; i++) {
        creditAmount += parseFloat(creditData[i].creditBalance);
      }
    }
    return (
      <Card className={styles.funds} key="fund_card">
        {datas.map(data => {
          return (
            <div>
              <Card.Grid key={data.title} style={{ width: "50%" }}>
                <div className="funds-icon-wrap">
                  <CustIcon type={data.icon} style={{ fontSize: 36 }} />
                </div>
                <span className="funds-text-money" style={{ display: "block" }}>
                  {data.name == "信用余额" ? amountPrecision(creditAmount) : amountPrecision(castAmount)}
                </span>
                <span className="funds-text-title">{data.name}</span>
              </Card.Grid>
            </div>
          );
        })}
      </Card>
    );
  }
  goodsDetailHandle(data, e) {
    const tempData = {
      id: data.productId,
      code: data.productCode
    };
    toGoodsDetailHandle(this.props, tempData, e);
  }
  showModal() {
    const treeListModal = this.state.ref.treeListModal;
    treeListModal.showModal();
  }
  // 图片加载失败
  imgErro(e) {
    e.target.src = erroImg;
  }
  render() {
    const { noticeData, todoDada } = this.props;
    return (
      <div>
        <div className={styles.advertising}>
          <Layout className={styles.banner}>
            <Sider className={styles.bannerSide}>
              <MenuComp />
            </Sider>
            <Content className={styles.carouselBox}>
              {this.getCarousel(this.props.imgSrcData)}
            </Content>
            {/* <Sider className={styles.bannerRightSide} width="220"> */}
              {/* <div className={styles.announcementBox}>{this.getAnnouncement(noticeData)}</div> */}
              {/* <div style={{ borderTop: "2px solid #f0f0f0" }}></div> */}
              {/* <div className={styles.todolistBox}>{this.getTodoAndFunds(todoDada)}</div> */}
            {/* </Sider> */}
          </Layout>
          <div className={styles.contentBox}>
            <div className={styles.todolistBox}>{this.getTODOListData(todoDada)}</div>
            <div className={styles.announcementBox}>{this.getAnnouncement(noticeData)}</div>
          </div>
          <GoodsHot {...this.props} />
          <GoodsCommon {...this.props} />
          <GoodsHistory />
        </div>
        <Layout style={{ height: "70px" }}>
          <Footer
            style={{
              textAlign: "center",
              position: "absolute",
              bottom: 0,
              left: 0,
              width: "100%"
            }}
          >
            Copyright <Icon type="copyright" /> 2018 用友网络科技股份有限公司
            营销云出品
          </Footer>
        </Layout>
      </div>
    );
  }
}
export default connect(state => ({
  imgSrcData: state.home.imgSrcData,
  noticeData: state.home.noticeData,
  todoDada: state.home.todoDada,
  autoPlaySpeed: state.home.autoPlaySpeed,
  creditData: state.credit.creditData,            // 信用余额
  castAmount: state.public.castAmount,            // 费用余额
}))(Home);
