import React, { PureComponent } from "react";
import moment from "moment";
import { connect } from "dva";
import { Link, routerRedux } from "dva/router";
import {
  Icon,
  Checkbox,
  Select,
  Input,
  DatePicker,
  Popover,
  Button,
  Modal,
  Popconfirm
} from "antd";
import styles from "./index.less";
import OrderListComp from "@/components/OrderListComp/index.js";
import BreadcrumbPackage from "@/components/BreadcrumbPackage/index";
import PageGrid from "@/components/PageGrid/index.js";
import Form from "@/components/Form/index.js";
import { getCustomer } from "@/utils/request.js";
import { amountPrecision } from '@/utils/common';

class ReturnOrderList extends PureComponent {
  constructor(props) {
    super(props);
    this.customerRankCode = getCustomer().customerRankCode;
    this.state = {
      visible: false,
      confirmLoading: false
    };
  }
  componentWillMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "returnOrderList/getOrderStatusData",
      payload: null
    });
    this.search();
  }
  // 分页搜索
  search(page = 0, pageSize = 10) {
    const { dispatch } = this.props;
    const searchConditions = this.searchConditions || {};
    searchConditions.page = page ? page : 0;
    searchConditions.size = pageSize ? pageSize : 10;
    searchConditions[`search_EQ_saleModel`] = "02";
    dispatch({
      type: "returnOrderList/getOrderListData",
      payload: searchConditions
    });
  }
  // 详情跳转
  goDetailHandle(data) {
    const { dispatch } = this.props;
    if (data.orderStatusCode == "01") {
      dispatch(
        routerRedux.push({
          pathname: "/buyer/returnOrderEdit",
          orderId: data.id
        })
      );
    } else {
      dispatch(
        routerRedux.push({
          pathname: "/buyer/returnOrderListDetail",
          orderId: data.id
        })
      );
    }
  }
  // 删除操作
  deleteOrder(id) {
    const { dispatch } = this.props;
    dispatch({
      type: "returnOrderList/deleteOrderById",
      payload: { id: id }
    }).finally(() => {
      this.search();
      console.log("执行成功");
    });
  }
  // 修改操作
  updateOrderHandle(id) {
    const { dispatch, location } = this.props;
    dispatch(
      routerRedux.push({
        pathname: "/buyer/returnOrderEdit",
        orderId: id
      })
    );
  }
  // 确认退货
  confirnReturnHandle() {
    const { dispatch } = this.props;
    dispatch({
      type: "returnOrderList/confrimReturnById",
      payload: { id: id }
    }).finally(() => {
      this.search();
      console.log("执行成功");
    });
  }
  render() {
    const { orderStatusData, orderListData } = this.props;
    const {
      visible,
      confirmLoading
    } = this.state;
    // 订单商品名图片渲染
    const orderGoodsHtml = data => {
      if (!data) return null;
      if (data.length > 3) {
        data = data.slice(0, 3);
      }
      const html = data.map(item => (
        <div className={styles.imgBox} key={item.id}>
          <img src={item.goodsImg} alt="" className={styles.img} />
        </div>
      ));
      return html;
    };
    // 订单状态追踪显示
    const orderFlowsHandle = orderFlows => {
      if (!orderFlows) return null;
      orderFlows.sort((pre, next) => {
        return next.creationTime - pre.creationTime;
      });
      return (
        <div className={styles.tailHoverBox}>
          {orderFlows.map(item => (
            <div className={styles.tailItem} key={item.id}>
              <i className={styles.circle}>
                <em className={styles.point} />
              </i>
              <span className={styles.time}>
                {moment(item.creationTime).format("YYYY-MM-DD")}
              </span>
              <span className={styles.cancelType}>{item.orderDescription}</span>
              <span className={styles.cancelName}>{item.creator || ""}</span>
            </div>
          ))}
        </div>
      );
    };
    // 订单按钮显示
    const getButton = record => {
      const status = record.orderStatusCode;
      if (status == "01" || status == "06") {
        return (
          <div className={styles.orderCancelBox}>
            <span
              className={styles.cancelBtn}
              onClick={this.updateOrderHandle.bind(this, record.id)}
            >
              修改
            </span>
            <Popconfirm
              title="确认删除订单？"
              onConfirm={this.deleteOrder.bind(this, record.id)}
            >
              <span className={styles.cancelBtn}>删除</span>
            </Popconfirm>
          </div>
        );
      } else if (status == "07" && this.customerRankCode != "01") { // 非一级渠道商才能手动确认退货
        return (
          <div className={styles.orderCancelBox}>
            <Popconfirm
              title="确认已经将货物发给上游供应商？"
              onConfirm={this.confirnReturnHandle.bind(this, record.id)}
            >
              <span className={styles.cancelBtn}>退货</span>
            </Popconfirm>
          </div>
        );
      }
      return null;
    };
    const columns = [
      {
        title: "商品信息",
        dataIndex: "reqOrderItems",
        className: "thAlignCenter",
        width: "270px",
        key: "reqOrderItems",
        render: (text, record) => {
          if (!text) return null;
          return (
            <div className={styles.orderNameBox}>
              <div style={{ float: "left" }}>{orderGoodsHtml(text)}</div>
              <Icon
                type="ellipsis"
                className={styles.ellipsisIcon}
                style={{
                  display: text.length > 3 ? "inline-block" : "none"
                }}
              />
            </div>
          );
        }
      },
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
        render: (text, record) => (
          <div
            className={styles.orderCodeBox}
            onClick={this.goDetailHandle.bind(this, record)}
          >
            <p className={styles.code}>{text}</p>
            <p className={styles.time}>
              {moment(record.creationTime).format("YYYY-MM-DD HH:mm")}
            </p>
          </div>
        )
      },
      {
        title: "退货数量",
        className: "alignRight",
        dataIndex: "totalOrderNum",
        key: "totalOrderNum",
        render: (text, record) => {
          let totalOrderNum = 0;
          if (record.reqOrderItems) {
            totalOrderNum = record.reqOrderItems.reduce((total, nextItem) => {
              return total + parseFloat(nextItem.orderNum);
            }, 0);
          }
          return (
            <div className={styles.orderPriceBox}>{`${totalOrderNum}`}</div>
          );
        }
      },
      {
        title: "退货金额",
        className: "alignRight",
        dataIndex: "totalReturnAmount",
        key: "totalReturnAmount",
        render: (text, record) => (
          <div className={styles.orderPriceBox}>
            {amountPrecision(text, "amount", record.currencySign, record.currencyAmountScale)}
          </div>
        )
      },
      {
        title: "订单状态",
        className: "alignCenter",
        dataIndex: "orderStatusName",
        key: "orderStatusName",
        render: (text, record) => (
          <div className={styles.orderStatusBox}>{text}</div>
        )
      },
      {
        title: "处理追踪",
        className: "alignCenter",
        dataIndex: "reqOrderLogs",
        key: "reqOrderLogs",
        render: (text, record) => (
          <div className={styles.orderTailBox}>
            <Popover
              content={orderFlowsHandle(text)}
              title={null}
              trigger="hover"
              placement="left"
            >
              <Icon type="clock-circle-o" className={styles.clockIcon} />
            </Popover>
          </div>
        )
      },
      {
        title: "操作",
        className: "alignCenter",
        dataIndex: "orderStatus",
        key: "orderStatus",
        render: (text, record) => getButton(record)
      }
    ];
    const searchAttrs = [
      {
        label: "订单状态",
        key: "orderStatus",
        type: "select",
        sourceData: orderStatusData || []
      },
      {
        label: "订单日期",
        type: "comb",
        children: [
          {
            key: "orderDate",
            type: "daterange",
            startValue: Date.now() - 6 * 86400000,
            endValue: Date.now(),
          },
          {
            key: "orderCode",
            type: "inputSearch",
            placeholder: "请输入退货单编码",
            enterButton: "搜索"
          }
        ]
      }
    ];
    return (
      <div className={styles.returnOrderListBox}>
        {/* <BreadcrumbPackage /> */}
        {/* 搜索 */}
        <div className={styles.searchConditions}>
          <Form
            searchAttrs={searchAttrs}
            setSearchParams={(value, ifSearch) => {
              this.searchConditions = value;
              if (ifSearch) {
                this.search();
              }
            }}
          />
          <Link to="/buyer/returnOrderEdit">
            <Button className={styles.addGoodsBtn} type="primary">
              <Icon type="plus" className={styles.icon} />新增退货单
            </Button>
          </Link>
        </div>
        {/* 搜索--end */}
        {/* 列表 */}
        <PageGrid
          columns={columns}
          pageGridSource={orderListData}
          search={this.search.bind(this)}
        />
      </div>
    );
  }
}
export default connect(state => ({
  orderStatusData: state.returnOrderList.orderStatusData,
  orderListData: state.returnOrderList.orderListData
}))(ReturnOrderList);
