import React, { PureComponent } from "react";
import moment from "moment";
import { connect } from "dva";
import { Link, routerRedux } from "dva/router";
import {
  Icon,
  Popover,
  Button,
  Popconfirm
} from "antd";
import styles from "./index.less";
import PageGrid from "@/components/PageGrid/index.js";
import Form from "@/components/Form/index.js";
import { amountPrecision } from '@/utils/common';
import FormPayforDialog from "@/components/PayforDialog/index";

class OrderList extends PureComponent {
  constructor(props) {
    super(props);
    const match = this.props.match;
    this.defaultStatus = match.params && match.params.orderStatus || "";
    this.searchConditions = {};
    this.state = {
      visible: false,
      confirmLoading: false,
      payNeedData:{},
      // modalResultVisible:false,
    };
  }
  componentWillMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "orderList/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_IN_saleModel`] = "01,03";
    dispatch({
      type: "orderList/getOrderListData",
      payload: searchConditions
    });
  }
  // 编辑跳转
  goEditHandle(data) {
    const { dispatch } = this.props;
    if (data.orderStatusCode == "01") {
      dispatch(
        routerRedux.push({
          pathname: "/buyer/orderEdit",
          orderId: data.id
        })
      );
    }
  }
  // 详情跳转
  goDetailHandle(data) {
    const { dispatch } = this.props;
      dispatch(
        routerRedux.push({
          pathname: "/buyer/orderListDetail",
          orderId: data.id
        })
      );    
  }
  // 删除操作
  deleteOrder(id) {
    const { dispatch } = this.props;
    console.log(
      dispatch({
        type: "orderList/deleteOrderById",
        payload: { id: id }
      }).finally(() => {
        this.search();
        console.log("执行成功");
      })
    );
  }
  // 修改支付方式操作
  maintenPayType(order){
    const { dispatch, location } = this.props;
    const currencyName =JSON.parse(localStorage["_A_P_currency"]).name;
    this.props.dispatch({
      type: "global/orderListVisible",
      payload: true
    });
    let payBillDatalist = {
      id: order.id   
    }
    this.state.payNeedData={
      'total_amount':order.totalDealAmount,
      'out_trade_no':order.orderCode,
      'paymentModeName':order.paymentModeName,
      'currencyName':currencyName,
      'payBillData':payBillDatalist
    };
    
    
    dispatch({
      type: "paymentNotice/orderPayBillSet", 
      orderPayBillSet: this.state.payNeedData
    });
  }
  // 复制操作
  copyOrder(order) {
    const { dispatch, location } = this.props;
    localStorage.setItem("orderId", order.id);
    dispatch(
      routerRedux.push({
        pathname: "/buyer/orderEdit",
        query: {
          orderId: order.id,
          orderCode: order.orderCode
        }
      })
    );
  }
  // 修改操作
  updateOrderHandle(id) {
    const { dispatch, location } = this.props;
    dispatch(
      routerRedux.push({
        pathname: "/buyer/orderEdit",
        orderId: id
      })
    );
  }
  returnOrderHandle(record) {
    const { dispatch, match } = this.props;
    var id = match.params.id;
    dispatch(
      routerRedux.push({
        pathname: "/buyer/returnOrderEdit",
        query: {
          orderId: record.id,
          orderCode: record.orderCode,
          ifBaseReturnOrder: true
        }
      })
    );
  }
  // setModalResultVisible = (modalResultVisible) =>  {
  //   this.setState({ modalResultVisible });
  // }
  render() {
    const { orderStatusData, orderListData } = this.props;
    console.log(orderListData);
    const { visible, confirmLoading, orderStartDate, orderEndDate } = 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="imgBox" key={item.id}>
          <img src={item.goodsImg} alt="" className="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") {
       const paymentStatusCode = record.paymentStatusCode;
       if (paymentStatusCode =='0'){
        return (
          <div className={styles.orderCancelBox}>
            <span
              className={styles.cancelBtn}
              onClick={this.copyOrder.bind(this, record)}
            >
              复制
            </span>
          </div>
        );
       }else if(paymentStatusCode == null || paymentStatusCode =='' ){
        return (
        <div className={styles.orderCancelBox}>
          <span
            className={styles.cancelBtn}
            onClick={this.goEditHandle.bind(this, record)}
          >
            修改
          </span>
          <Popconfirm
            title="确认删除订单？"
            onConfirm={this.deleteOrder.bind(this, record.id)}
          >
            <span className={styles.cancelBtn}>删除</span>
          </Popconfirm>
        </div>
        );
       }else if( paymentStatusCode =='-1'){       
          return (
            <div className={styles.orderCancelBox}>
              <span
                  className={styles.cancelBtn}
                  onClick={this.maintenPayType.bind(this, record)}
                >
                  修改
                </span>
              <Popconfirm
                title="确认删除订单？"
                onConfirm={this.deleteOrder.bind(this, record.id)}
              >
                <span className={styles.cancelBtn}>删除</span>
              </Popconfirm>
              <span
                className={styles.cancelBtn}
                onClick={this.copyOrder.bind(this, record)}
              >
                复制
              </span>
            </div>
          );
        }
      } else if (status == "02") {
        return (
          <div className={styles.orderCancelBox}>
            <span
              className={styles.cancelBtn}
              onClick={this.copyOrder.bind(this, record)}
            >
              复制
            </span>
          </div>
        );
      } else if (status == "03" || status == "04" || status == "05") {
        let returnButtonShow = false;
        // 货补订单不能进行退货
        if (record.saleModel != "03") {
          const reqOrderItems = record.reqOrderItems;
          if (!reqOrderItems) return returnButtonShow;
          for (const item of reqOrderItems) {
            // 存在商品行：主数量 - 累计退货数量 > 0, 则显示退货按钮
            const returnNum = parseFloat(item.mainNum || "0") - parseFloat(item.returnNum || "0");
            if (returnNum > 0) {
              returnButtonShow = true;
              break;
            }
          }
        }
        return (
          <div className={styles.orderCancelBox}>
            <span
              className={styles.cancelBtn}
              onClick={this.copyOrder.bind(this, record)}
            >
              复制
            </span>
            <span
              style={{ display: returnButtonShow ? "inline-block" : "none" }}
              className={styles.cancelBtn}
              onClick={this.returnOrderHandle.bind(this, record)}
            >
              退货
            </span>
          </div>
        );
      } else if (status == "06") {
        let updateButtonShow = true;
        // 货补订单不允许修改
        if (record.saleModel == "03") {
          updateButtonShow = false;
        }
        return (
          <div className={styles.orderCancelBox}>
            <span
              className={styles.cancelBtn}
              style={{ display: updateButtonShow ? "inline-block" : "none" }}
              onClick={this.updateOrderHandle.bind(this, record.id)}
            >
              修改
            </span>
            <Popconfirm
              title="确认删除订单？"
              onConfirm={this.deleteOrder.bind(this, record.id)}
            >
              <span className={styles.cancelBtn}>删除</span>
            </Popconfirm>
            <span
              className={styles.cancelBtn}
              onClick={this.copyOrder.bind(this, record)}
            >
              复制
            </span>
          </div>
        );
      }
    };
    const columns = [
      {
        title: "商品信息",
        dataIndex: "reqOrderItems",
        key: "reqOrderItems",
        className: "thAlignCenter",
        width: "270px",
        render: (text, record) => {
          if (!text) return null;
          return (
            <div className="orderNameBox">
              {orderGoodsHtml(text)}
                <Icon
                  type="ellipsis"
                  className="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: "订单金额",
        dataIndex: "totalDealAmount",
        key: "totalDealAmount",
        className: "alignRight",
        render: (text, record) => (
          <div className={styles.orderPriceBox}>
            {amountPrecision(text, "amount", record.currencySign, record.currencyAmountScale)}
          </div>
        )
      },
      {
        title: "订单状态",
        dataIndex: "orderStatusName",
        key: "orderStatusName",
        className: "alignCenter",
        render: (text, record) => (
          <div className={styles.orderStatusBox}>{text}</div>
        )
      },
      {
        title: "支付状态",
        dataIndex: "paymentStatusName",
        key: "paymentStatusName",
        className: "alignCenter",
        render: (text, record) => (
          <div className={styles.orderStatusBox}>{text}</div>
        )
      },
      {
        title: "处理追踪",
        dataIndex: "reqOrderLogs",
        key: "reqOrderLogs",
        className: "alignCenter",
        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: "操作",
        dataIndex: "orderStatus",
        key: "orderStatus",
        className: "alignCenter",
        render: (text, record) => getButton(record)
      }
    ];
    const searchAttrs = [
      {
        label: "订单状态",
        key: "orderStatus",
        type: "select",
        defaultValue: this.defaultStatus || "",
        sourceData: orderStatusData || []
      },
      {
        label: "订单日期",
        type: "comb",
        children: [
          {
            key: "orderDate",
            type: "daterange",
            startValue: this.defaultStatus ? null : Date.now() - 6 * 86400000,
            endValue: this.defaultStatus ? null : Date.now(),
          },
          {
            key: "orderCode",
            type: "inputSearch",
            placeholder: "请输入订单编码",
            enterButton: "搜索"
          }
        ]
      }
    ];
    return (
      <div className={styles.orderListBox}>
        {/* <BreadcrumbPackage /> */}
        {/* 搜索 */}
        <div className={styles.searchConditions}>
          <Form
            searchAttrs={searchAttrs}
            setSearchParams={(value, ifSearch) => {
              this.searchConditions = value;
              if (ifSearch) {
                this.search();
              }
            }}
          />
          <Link to="/buyer/orderEdit">
            <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)}
        />
        {/* 列表--end */}
         {/* 支付方式弹窗--start */}
        <FormPayforDialog
          payNeedData={this.state.payNeedData}
          orderPayBillSet={this.props.orderPayBillSet}
          backToWho={'orderList'}
        />        
      </div>
    );
  }
}
export default connect(state => ({
  orderStatusData: state.orderList.orderStatusData,
  orderListData: state.orderList.orderListData,
  orderPayBillSet: state.paymentNotice.orderPayBillSet,
}))(OrderList);
