import React, { PureComponent } from "react";
import { connect } from "dva";
import moment from "moment";
import { Link, routerRedux } from "dva/router";
import {
  Icon,
  Checkbox,
  Select,
  Input,
  DatePicker,
  Popover,
  Button,
  Pagination,
  Steps,
  Row,
  Col,
  Table,
  Timeline,
  Tabs
} from "antd";
import GoodsOptsDialog from "@/components/GoodsOptsDialog/index";
import iconfontStyles from "../../../iconfont/iconfont.css";
import styles from "./index.less";
import imgSrc from "./goods-img.png";
import { goodsVersion, amountPrecision } from '@/utils/common';
const TabPane = Tabs.TabPane;
const Step = Steps.Step;

const getFileListHtml = fileList => {
  fileList = fileList || [];
  if (!fileList) return null;
  return fileList.map(file => (
    <div className={styles.fileName} title={file.name} key={file.id}>
      <a href={file.attachmentUrl} rel="noopener noreferrer" target="_blank">
        <Icon type="paper-clip" />
        <span style={{ marginLeft: "5px" }}>{file.attachmentName}</span>
      </a>
    </div>
  ));
};

class RetrunOrderListDetail extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      goodsOptsParam: {
        rowData: {}
      },
      logsDirect: "up"
    };
    // 订单列表列
    this.orderColumns = [
      {
        title: "商品",
        dataIndex: "goodsId",
        key: "goodsId",
        width: "20%",
        render: (text, record, index) => (
          <div className={styles.goodsNameBox}>
            <div className={styles.imgBox}>
              <img src={record.goodsImg} alt="" />
            </div>
            <div className={styles.goodsInfo}>
              <p className={styles.goodsTitleName} title={record.goodsDisplayName}>
                {record.goodsDisplayName}
              </p>
              <p className={styles.goodsCode}>{record.goodsCode}{goodsVersion(record.version)}</p>
              <p className={record.isGift == 1 ? styles.goodsStatus : ""}>
                <span className={styles.goodsStatusTxt}>
                  {record.isGift == 1 ? "赠" : ""}
                </span>
              </p>
            </div>
          </div>
        )
      },
      {
        title: "商品选配",
        dataIndex: "salePrice",
        key: "salePrice",
        align: "right",
        render: (text, record, index) => {
          if (record.isOptional || record.baseGoodsOptValue) {
            return (
              <span className={styles.goodsOpt} onClick={this.onGoodsOptionalHandle.bind(this, record, index)}>
                {record.baseGoodsOptValue || "添加选配"}
              </span>
            );
          } else {
            return null;
          }
        }
      },
      // {
      //   title: "单价",
      //   dataIndex: "salePrice",
      //   key: "salePrice",
      //   className: "alignRight",
      //   width: "8%",
      //   render: (text, record, index) => (
      //     <span>
      //       ￥{record.salePrice}
      //       <em className={styles.em}>/{record.mainNumUnitName}</em>
      //     </span>
      //   )
      // },
      {
        title: "成交价",
        dataIndex: "dealPrice",
        key: "dealPrice",
        className: "alignRight",
        width: "8%",
        render: (text, record, index) => (
          <span>
            <span className={styles.fontRed}>{amountPrecision(text, "price", record.currencySign, record.currencyPriceScale)}</span>
            <em className={styles.em}>/{record.mainNumUnitName}</em>
          </span>
        )
      },
      {
        title: "退货量",
        dataIndex: "orderNum",
        key: "orderNum",
        className: "alignRight",
        width: "8%",
        render: (text, record, index) => (
          <span className={styles.orderNum}>
            {record.orderNum}
            <em className={styles.em}>/{record.orderNumUnitName}</em>
          </span>
        )
      },
      {
        title: "退货主数量",
        dataIndex: "mainNum",
        key: "mainNum",
        className: "alignRight",
        width: "8%",
        render: (text, record, index) => (
          <span>
            {record.mainNum}
            <em className={styles.em}>/{record.mainNumUnitName}</em>
          </span>
        )
      },
      // {
      //   title: "金额小计",
      //   dataIndex: "dealAmount",
      //   key: "dealAmount",
      //   className: "alignRight",
      //   width: "8%",
      //   render: (text, record, index) => (
      //     <span>
      //       ￥{parseFloat(record.dealAmount).toFixed(
      //         record.currencyAmountScale
      //       )}
      //     </span>
      //   )
      // },
      {
        title: "退货金额",
        dataIndex: "totalReturnAmount",
        key: "totalReturnAmount",
        className: "alignRight",
        width: "8%",
        render: (text, record, index) => (
          <span className={styles.fontRed}>
            {amountPrecision(record.totalReturnAmount, "amount", record.currencySign, record.currencyAmountScale)}
          </span>
        )
      },
      {
        title: "退货类型",
        dataIndex: "returnTypeName",
        key: "returnTypeName",
        width: "8%",
        render: (text, record, index) => <span>{text || "退货"}</span>
      },
      {
        title: "退货原因",
        dataIndex: "returnReasonName",
        key: "returnReasonName",
        width: "12%",
        render: (text, record, index) => (
          <div className={styles.returnReason} title={record.returnReasonName}>
            {text}
          </div>
        )
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        width: "12%",
        render: (text, record, index) => (
          <span>{getFileListHtml(record.reqOrderAttachments)}</span>
        )
      }
    ];
    this.bomColumns = [
      {
        title: "商品",
        dataIndex: "goodsId",
        key: "goodsId-bom",
        width: "25%",
        render: (text, record, index) => (
          <div className={styles.goodsNameBox}>
            <div className={styles.imgBox}>
              <img src={record.goodsImg} alt="" />
            </div>
            <div className={styles.goodsInfo}>
              <p className={styles.goodsTitleName} title={record.goodsDisplayName || record.goodsName}>
                {record.goodsDisplayName}
              </p>
              <p className={styles.goodsCode}>{record.goodsCode}{goodsVersion(record.version)}</p>
              <p className={record.isGift == 1 ? styles.goodsStatus : ""}>
                <span className={styles.goodsStatusTxt}>
                  {record.isGift == 1 ? "赠" : ""}
                </span>
              </p>
            </div>
          </div>
        )
      },
      {
        title: "选配",
        dataIndex: "baseGoodsOptValue",
        key: "baseGoodsOptValue-bom",
        width: "15%",
        render: (text, record, index) => (
          <span className={styles.valBox} title={record.baseGoodsOptValue}>
            {record.baseGoodsOptValue}
          </span>
        )
      },
      {
        title: "母件行号",
        dataIndex: "parentRowNum",
        key: "parentRowNum",
        width: "10%",
        className: "alignRight",
        render: (text, record, index) => (
          <span>
            <span>{text}</span>
          </span>
        )
      },
      {
        title: "母件商品名称",
        dataIndex: "parentGoodsName",
        key: "parentGoodsName",
        width: "12%",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.valBox} title={text}>
            {text}
          </span>
        )
      },
      {
        title: "母件商品编码",
        dataIndex: "parentGoodsCode",
        key: "parentGoodsCode",
        width: "12%",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.valBox} title={text}>
            {text}
          </span>
        )
      },
      // {
      //   title: "重量",
      //   dataIndex: "rowWeight",
      //   key: "rowWeight-bom",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span className={styles.MainNum}>
      //       <span className={styles.textBox}>{(text || 0).toFixed(record.weightUnitPrecision || 2)}</span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>{record.weightUnitName || ""}</em>
      //     </span>
      //   )
      // },
      // {
      //   title: "单价",
      //   dataIndex: "salePrice",
      //   key: "salePrice-bom",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span>
      //       <span className={`${styles.fontRed} ${styles.textBox}`}>
      //       {amountPrecision(record.salePrice, "price", record.currencySign, record.currencyPriceScale)}
      //       </span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>
      //         /{record.mainNumUnitName}
      //       </em>
      //     </span>
      //   )
      // },
      // {
      //   title: "成交价",
      //   dataIndex: "dealPrice",
      //   key: "dealPrice-bom",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span>
      //       <span className={`${styles.fontRed} ${styles.textBox}`}>
      //       {amountPrecision(record.dealPrice, "price", record.currencySign, record.currencyPriceScale)}
      //       </span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>
      //         /{record.mainNumUnitName}
      //       </em>
      //     </span>
      //   )
      // },
      {
        title: "订货量",
        dataIndex: "orderNum",
        key: "orderNum-bom",
        width: "12%",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.orderNum}>
            <span className={styles.textBox}>{record.orderNum}</span>
            <em className={`${styles.em} ${styles.unitBox}`}>
              {record.orderNumUnitName}
            </em>
          </span>
        )
      },
      {
        title: "主数量",
        dataIndex: "mainNum",
        key: "mainNum-bom",
        width: "12%",
        className: "alignRight",
        render: (text, record, index) => (
          <span className={styles.MainNum}>
            <span className={styles.textBox}>{record.mainNum}</span>
            <em className={`${styles.em} ${styles.unitBox}`}>
              {record.mainNumUnitName}
            </em>
          </span>
        )
      },
      // {
      //   title: "重量",
      //   dataIndex: "rowWeight",
      //   key: "rowWeight-bom",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span className={styles.MainNum}>
      //       <span className={styles.textBox}>{(text || 0).toFixed(record.weightUnitPrecision || 2)}</span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>{record.weightUnitName || ""}</em>
      //     </span>
      //   )
      // },
      // {
      //   title: "体积",
      //   dataIndex: "rowVolume",
      //   key: "rowVolume-bom",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span className={styles.MainNum}>
      //       <span className={styles.textBox}>{(text || 0).toFixed(record.volumeUnitPrecision || 2)}</span>
      //       <em className={`${styles.em} ${styles.unitBox}`}>{record.volumeUnitName || ""}</em>
      //     </span>
      //   )
      // },
      // {
      //   title: "金额",
      //   dataIndex: "amount",
      //   key: "amount-bom",
      //   width: "100px",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <span className={styles.MainNum}>
      //       {amountPrecision(record.amount, "amount", record.currencySign, record.currencyAmountScale)}
      //     </span>
      //   )
      // },
      // {
      //   title: "成交金额",
      //   dataIndex: "dealAmount",
      //   key: "dealAmount-bom",
      //   width: "100px",
      //   className: "alignRight",
      //   render: (text, record, index) => (
      //     <div className={styles.dealAmount}>
      //       <span className={styles.fontRed}>
      //         {amountPrecision(record.dealAmount, "amount", record.currencySign, record.currencyAmountScale)}
      //       </span>
      //     </div>
      //   )
      // }
    ];
  }
  componentWillMount() {
    const { dispatch, location } = this.props;
    // 清空
    dispatch({
      type: "returnOrderListDetail/orderDetailData",
      orderDetailData: null
    });
    const id = location[`orderId`];
    // 如果id为空，返回订单列表页
    if (!id) {
      dispatch(
        routerRedux.push({
          pathname: "/buyer/returnOrderList"
        })
      );
      return false;
    }
    // 获取订单详情页
    dispatch({
      type: "returnOrderListDetail/getOrderDetailData",
      payload: {
        id: id
      }
    });
  }
  onGoodsOptionalHandle(goods, index) {
    const goodsOptsParam =  {
      rowData: goods,
      goodsId: goods.goodsId,
      baseGoodsOptId: goods.baseGoodsOptId,
      rowIndex: index
    };
    this.setState({
      goodsOptsParam: goodsOptsParam
    }, () => {
      this.props.dispatch({
        type: "global/goodsOptsVisible",
        payload: true
      });
    });
  }
  // 是否显示操作日志
  logsHandle() {
    const { logsDirect } = this.state;
    this.setState({
      logsDirect: logsDirect == "down" ? "up" : "down"
    });
  }
  // 复制订单，跳转至订单编辑页面
  copyOrderHandle(data) {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: "/buyer/returnOrderEdit",
        query: {
          orderId: data.id,
          orderCode: data.orderCode
        }
      })
    );
  }
  // 导出订单
  exportOrderHandle() {
    window.print();
  }
  render() {
    const { orderDetailData } = this.props;
    if (!orderDetailData) return null;
    // todo...
    const {
      reqOrderReceiveAddress,
      reqOrderInvoice,
      reqOrderItems,
      reqOrderItemBoms,
      reqOrderTracks,
      reqOrderLogs
    } = orderDetailData;
    // 订单列表列
    const orderColumns = this.orderColumns;
    const deliveryColumns = this.deliveryColumns;
    const iconType = value => {
      let name;
      switch (value) {
        case "订单提交":
          name = `${iconfontStyles["buyer-iconfont"]} ${
            iconfontStyles["icon-icon-SubmitOrder"]
          }`;
          break;
        case "订单审核":
          name = `${iconfontStyles["buyer-iconfont"]} ${
            iconfontStyles["icon-icon-ReviewOrder"]
          }`;
          break;
        case "退货中":
          name = `${iconfontStyles["buyer-iconfont"]} ${
            iconfontStyles["icon-icon-Inreturn"]
          }`;
          break;
        case "订单完成":
          name = `${iconfontStyles["buyer-iconfont"]} ${
            iconfontStyles["icon-icon-CompleteOrder"]
          }`;
          break;
      }
      return name;
    };
    // 订单状态 todo...
    const trackingsHtml = () => {
      if (!orderDetailData) return null;
      const reqOrderTracks = orderDetailData.reqOrderTracks;
      const trackings = [
        {
          status: "wait",
          code: "commit",
          name: "订单提交"
        },
        {
          status: "wait",
          code: "approve",
          name: "订单审核"
        },
        {
          status: "wait",
          code: "approve",
          name: "退货中"
        },
        {
          status: "wait",
          code: "finish",
          name: "订单完成"
        }
      ];
      trackings.forEach(track => {
        const reqTrack =
          reqOrderTracks.find(item => item.node == track.code) || {};
        if (reqTrack.finish && reqTrack.finish == 1) {
          track.status = "finish";
          track.operateDate = reqTrack.operateTime ? moment(reqTrack.operateTime).format("YYYY-MM-DD") : "";
          track.operateTime = reqTrack.operateTime ? moment(reqTrack.operateTime).format("HH:mm:ss") : "";
        }
      });
      const html = trackings.map(item => {
        return (
          <Step
            key={item.name}
            status={item.status}
            title={item.name}
            description={
              <div style={{ fontSize: "12px" }}>
                <div>{item.operateDate}</div>
                <div style={{ "paddingLeft": "10px" }}>{item.operateTime}</div>
              </div>
            }
            icon={
              <i className={`${styles.trackIcon} ${iconType(item.name)}`} />
            }
          />
        );
      });
      return html;
    };
    // 操作日志
    const getStepTtile = item => {
      const weekDay = moment(item.creationTime).format("d");
      let weekDayName = "";
      switch (weekDay) {
        case "1":
          weekDayName = "周一";
          break;
        case "2":
          weekDayName = "周二";
          break;
        case "3":
          weekDayName = "周三";
          break;
        case "4":
          weekDayName = "周四";
          break;
        case "5":
          weekDayName = "周五";
          break;
        case "6":
          weekDayName = "周六";
          break;
        case "7":
          weekDayName = "周日";
          break;
        default:
          break;
      }
      return (
        <Row>
          <Col span={4}>
            {`${moment(item.creationTime).format("YYYY-MM-DD")}/${weekDayName}`}
          </Col>
          <Col span={3}>{moment(item.creationTime).format("HH:mm:ss")}</Col>
          <Col span={16}>
            {item.content} {item.orderDescription}
          </Col>
        </Row>
      );
    };
    const logsHtml = () => {
      if (!reqOrderLogs) return null;
      // 对日志进行排序
      reqOrderLogs.sort((pre, next) => {
        return next.creationTime - pre.creationTime;
      });
      const html = reqOrderLogs.map(item => (
        <Timeline.Item key={item.id}>{getStepTtile(item)}</Timeline.Item>
      ));
      return html;
    };
    return (
      <div className={styles.orderListDetailBox}>
        {/* <BreadcrumbPackage additems={BreadcrumbPaths} /> */}
        {/* 订单状态 */}
        <div className={styles.orderStatusBox}>
          <div className={styles.leftBox}>
            <p className={styles.orderCode}>
              订单号: {orderDetailData.orderCode}
            </p>
            <p className={styles.orderStatus}>
              {/* {this.orderStatusHandle(orderDetailData.orderStatus)} */}
              {orderDetailData.orderStatusName}
            </p>
            <p className={styles.btnBox}>
              <Button
                className={styles.btn}
                onClick={this.copyOrderHandle.bind(this, orderDetailData)}
              >
                复制本单
              </Button>
              <Button className={styles.btn} onClick={this.exportOrderHandle}>
                订单导出
              </Button>
            </p>
            <p className={styles.orderCode}>
              总金额: {amountPrecision(orderDetailData.totalReturnAmount, "amount", orderDetailData.currencySign, orderDetailData.currencyAmountScale)}
            </p>
          </div>
          <div className={styles.rightBox}>
            <Steps style={{ height: "83%" }}>{trackingsHtml()}</Steps>
            <div
              style={{ display: orderDetailData.rejectReason ? "" : "none" }}
            >
              <span>驳回原因：</span>
              <span>{orderDetailData.rejectReason}</span>
            </div>
          </div>
        </div>
        {/* 订单状态--end */}
        {/* 收货信息 */}
        <div className={styles.infoBox}>
          <div className={styles.infoItem}>
            <p className={styles.title}>收货人信息</p>
            <div className={styles.info}>
              <span className={styles.name}>收货人:</span>
              <div className={styles.value}>
                {reqOrderReceiveAddress && reqOrderReceiveAddress.receiver}
              </div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>地址:</span>
              <div className={styles.value}>
                {`${reqOrderReceiveAddress && reqOrderReceiveAddress.receiverProvince ||
                  ""} ${reqOrderReceiveAddress && reqOrderReceiveAddress.receiverCity ||
                  ""} ${reqOrderReceiveAddress && reqOrderReceiveAddress.receiverCounty ||
                  ""} ${reqOrderReceiveAddress && reqOrderReceiveAddress.receiverTown ||
                  ""} ${reqOrderReceiveAddress && reqOrderReceiveAddress.receiverAddress || ""}`}
              </div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>手机号:</span>
              <div className={styles.value}>
                {reqOrderReceiveAddress && reqOrderReceiveAddress.receiverPhone}
              </div>
            </div>
          </div>
          <div className={styles.infoItem}>
            <p className={styles.title}>运输与结算</p>
            <div className={styles.info}>
              <span className={styles.name}>物流公司:</span>
              <div className={styles.value}>{orderDetailData.logistics}</div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>物流单号:</span>
              <div className={styles.value}>
                {orderDetailData.logisticsBillCode}
              </div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>账期:</span>
              <div className={styles.value}>
                {orderDetailData.accountPeriodName}
              </div>
            </div>
          </div>
          <div className={styles.infoItem}>
            <p className={styles.title}>发票信息</p>
            <div className={styles.info}>
              <span className={styles.name}>发票类型:</span>
              <div className={styles.value}>{reqOrderInvoice && reqOrderInvoice.invoiceType}</div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>发票抬头:</span>
              <div className={styles.value}>{reqOrderInvoice && reqOrderInvoice.invoiceTitle}</div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>纳税人号:</span>
              <div className={styles.value}>{reqOrderInvoice && reqOrderInvoice.invoiceTaxId}</div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>开户行:</span>
              <div className={styles.value}>{reqOrderInvoice && reqOrderInvoice.invoiceBank}</div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>账号:</span>
              <div className={styles.value}>
                {reqOrderInvoice && reqOrderInvoice.invoiceAccount}
              </div>
            </div>
          </div>
          <div className={styles.infoItem}>
            <p className={styles.title}>退货信息</p>
            <div className={styles.info}>
              <span className={styles.name}>退货原因:</span>
              <div className={styles.value}>
                {orderDetailData.returnReasonName}
              </div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>退货备注:</span>
              <div className={styles.value}>{orderDetailData.remark}</div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>附件:</span>
              <div className={styles.value}>
                {getFileListHtml(orderDetailData.reqOrderAttachments)}
              </div>
            </div>
            <div className={styles.info}>
              <span className={styles.name}>退货日期:</span>
              <div className={styles.value}>
                {moment(orderDetailData.creationTime).format("YYYY-MM-DD")}
              </div>
            </div>
          </div>
        </div>
        {/* 订单商品信息 */}
        <div className={styles.orderGoodsListBox}>
          <Tabs defaultActiveKey="product-tab" type="card">
            <TabPane tab="商品信息" key="product-tab">
              <Table
                scroll={{ y: 550 }}
                pagination={false}
                dataSource={reqOrderItems}
                columns={orderColumns}
              />
            </TabPane>
            {/* <TabPane tab="商品BOM信息" key="product-bom-tab">
              <Table
                scroll={{ y: 550 }}
                pagination={false}
                dataSource={reqOrderItemBoms || []}
                columns={this.bomColumns}
              />
            </TabPane> */}
          </Tabs>
        </div>
        <div className={styles.orderGoodsInfo}>
          <div className={styles.item} style={{ marginTop: 10 }}>
            <span
              className={styles.valueBox}
              style={{ fontSize: 24, color: "#D81719" }}
            >
              {amountPrecision(orderDetailData.totalDealAmount, "amount", orderDetailData.currencySign, orderDetailData.currencyAmountScale)}
            </span>
            <span className={styles.name}>退货总金额:</span>
          </div>
          <div className={styles.item} style={{ marginTop: 10 }}>
            <span
              className={styles.valueBox}
              style={{ fontSize: 24, color: "#D81719" }}
            >
              {amountPrecision(orderDetailData.totalReturnAmount, "amount", orderDetailData.currencySign, orderDetailData.currencyAmountScale)}
            </span>
            <span className={styles.name}>实际退货总金额:</span>
          </div>
        </div>
        {/* 订单商品信息--end */}
        {/* 操作日志 */}
        <div className={styles.deliveryInfoBox}>
          <p>
            <span className={styles.title} onClick={this.logsHandle.bind(this)}>
              操作日志<Icon
                type={this.state.logsDirect}
                className={styles.icon}
              />
            </span>
          </p>
          <div
            className={styles.logsBox}
            style={{
              display: this.state.logsDirect == "down" ? "block" : "none"
            }}
          >
            {/* <div className={styles.scrollbar}>{logsHtml()}</div> */}
            <div className={styles.scrollbar}>
              <Timeline className={styles.timelineBox}>{logsHtml()}</Timeline>
            </div>
          </div>
        </div>
        <GoodsOptsDialog
          title="商品选配"
          goodsOptsParam={this.state.goodsOptsParam}
          ifFooterNul={!!1}
        />
        {/* 操作日志--end */}
      </div>
    );
  }
}
export default connect(state => ({
  orderDetailData: state.returnOrderListDetail.orderDetailData
}))(RetrunOrderListDetail);
