import React, { PureComponent } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import {
  Icon,
  Checkbox,
  Select,
  Input,
  DatePicker,
  Popover,
  Button,
  notification,
  message,
  Layout,
  Row,
  Col,
  Affix,
  Upload,
  Popconfirm,
  Spin
} from "antd";
import moment from "moment";
import styles from "./index.less";
import ReturnOrderGoodsList from "@/components/ReturnOrderGoodsList/index.js";
import TreeListModal from "@/components/SelectDialog/TreeList/index";
import InvoiceDialog from "@/components/InvoiceDialog/index";
import BreadcrumbPackage from "@/components/BreadcrumbPackage/index.js";
import { getCustomer, getDefaultCurrency } from "@/utils/request.js";
import {
  setItemsDefaultData,
  ifSupplierIsOrg,
  fillDefalutInfoForUpload,
  translateItemBomFromItem
} from "../orderEdit/orderTools";

const { Header, Content } = Layout;
// 获取默认币种
const currency = {
  id: getDefaultCurrency().id || "",
  currencySign: getDefaultCurrency().currencySign || "￥",
  currencyPriceScale: getDefaultCurrency().currencyPriceScale || 2,
  currencyAmountScale: getDefaultCurrency().currencyAmountScale || 2
};

class OrderEidt extends PureComponent {
  constructor(props) {
    super(props);
    this.customerId = getCustomer().id;
    this.customerRankCode = getCustomer().customerRankCode;
    this.ifFillBom = false; // 是否重新补充BOM信息
    this.state = {
      ref: {},
      addressData: [], // 收货地址
      invoiceInfoData: [], // 发票
      btnTxt: "展开地址",
      iconType: "down",
      isShow: false, // 控制地址收起展开
      totalWeight: 0, // 总质量
      totalVolume: 0, // 总体积
      totalDealAmount: 0, // 订单成交金额
      totalAmount: 0, // 商品总金额（订单原金额）
      totalNum: 0, // 总数量
      totalReturnAmount: 0, // 实际总退货金额
      supplierId: "", // 供应商
      remark: "", // 订单备注
      logistics: "", // 物流公司
      logisticsBillCode: "", // 物流单号
      returnReasonId: "", // 退货原因
      headFileList: [], // 退货单表头附件
      deliveryDate: Date.now(), // 期望收货日期
      haveChecked: false, // 订单编辑
      supplierDisabled: false, // 供应商不可编辑,默认false
      srcOrderId: "", // 来源单据(原单主键)
      srcOrderCode: "", // 来源单据编号
      ifBaseReturnOrder: false, // 是否基于原单退单
      ifEditOrder: false, // 是否订单编辑
      loading: false,
      ifOneSupplier: true // 是否一级渠道商
    };
  }

  componentWillMount() {
    const { dispatch, location } = this.props;
    // 获取订单主键（编辑）
    const orderId = location[`orderId`];

    // 基于原单
    const query = location[`query`];

    dispatch({
      type: "returnOrderEdit/getSupplierData",
      payload: null
    })
      .finally(() => {
        const { supplierData } = this.props;
        const { supplierId } = this.state;
        if (supplierId) {
          const isOrg = ifSupplierIsOrg(supplierId, supplierData);
          // 供应商是组织时，只设置ifOneSupplier为true，适配货补
          if (isOrg) {
            this.setState({
              ifOneSupplier: true
            });
          } else {
            this.setState({
              ifOneSupplier: false
            });
          }
        }
      });
    dispatch({
      type: "returnOrderEdit/getAddressData",
      payload: null
    })
      .finally(() => {
        const { addressData, orderEditData } = this.props;
        if (orderEditData && orderEditData.reqOrderReceiveAddress &&
          orderEditData.reqOrderReceiveAddress.receiveAddressId && addressData
        ) {
          addressData.forEach(item => {
            item.isSelected = "0";
          });
          (
            addressData.find(
              item =>
                item.id ==
                orderEditData.reqOrderReceiveAddress.receiveAddressId
            ) || {}
          ).isSelected =
            "1";
          this.setState({
            addressData: addressData
          });
        }
      });
    dispatch({
      type: "returnOrderEdit/getLogisticsData",
      payload: null
    });
    dispatch({
      type: "returnOrderEdit/getSettlementData",
      payload: null
    });
    dispatch({
      type: "returnOrderEdit/getInvoiceInfoData",
      payload: null
    })
      .finally(() => {
        const { invoiceInfoData, orderEditData } = this.props;
        if (orderEditData && orderEditData.reqOrderInvoice &&
          orderEditData.reqOrderInvoice.invoiceId && invoiceInfoData
        ) {
          invoiceInfoData.forEach(item => {
            item.isDefault = "0";
          });
          (
            invoiceInfoData.find(
              item => item.id == orderEditData.reqOrderInvoice.invoiceId
            ) || {}
          ).isDefault =
            "1";
          this.setState({
            invoiceInfoData: invoiceInfoData
          });
        }
      });
    dispatch({
      type: "returnOrderEdit/getAllReturnCause",
      payload: null
    });
    dispatch({
      type: "returnOrderEdit/getAllReturnType",
      payload: null
    });
    // 防止有历史数据，先清空退货单商品行信息等
    dispatch({
      type: "returnOrderEdit/orderEditData",
      orderEditData: null
    });
    dispatch({
      type: "returnOrderEdit/orderCartData",
      orderCartData: []
    });
    // 订单编辑 （例如：订单驳回编辑）
    if (orderId) {
      dispatch({
        type: "returnOrderEdit/getOrderEditData",
        payload: {
          id: orderId
        }
      });
      this.setState({
        ifEditOrder: true,
        haveChecked: true
      });
    }
    // 退货单复制
    if (query && query.orderId && !query.ifBaseReturnOrder) {
      dispatch({
        type: "returnOrderEdit/getOrderEditDataForCopy",
        payload: {
          id: query.orderId
        }
      });
      this.setState({
        srcOrderId: query.orderId,
        srcOrderCode: query.orderCode,
        haveChecked: true
      });
    }
    // 基于原单退货
    if (query && query.orderId && query.ifBaseReturnOrder) {
      dispatch({
        type: "returnOrderEdit/getOrderEditDataForBase",
        payload: {
          id: query.orderId
        }
      });
      this.setState({
        srcOrderId: query.orderId,
        srcOrderCode: query.orderCode,
        haveChecked: true,
        ifBaseReturnOrder: true
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    const { dispatch } = this.props;

    if ("addressData" in nextProps) {
      const addressData = nextProps.addressData;
      this.setState({
        addressData: addressData
      });
    }
    if ("invoiceInfoData" in nextProps) {
      const invoiceInfoData = nextProps.invoiceInfoData;
      this.setState({
        invoiceInfoData: invoiceInfoData
      });
    }
    if ("orderCartData" in nextProps) {
      const orderCartData = nextProps.orderCartData;
      if (orderCartData && orderCartData.length > 0) {
        if (this.state.haveChecked) {
          this.ifFillBom = true;
          this.setState({
            haveChecked: false
          });
        }
      }
    }
    // 退货单编辑
    if ("orderEditData" in nextProps) {
      const orderEditData = nextProps.orderEditData;
      if (orderEditData && (orderEditData.id || this.state.ifBaseReturnOrder)) {
        if (this.state.haveChecked) {
          // todo...
          this.setState({
            supplierDisabled: (orderEditData.saleOrgId || orderEditData.supplierId) ? true : false,
            supplierId: orderEditData.saleOrgId || orderEditData.supplierId, // 供应商
            remark: orderEditData.remark, // 订单备注
            deliveryDate: Date.now(), // 期望收货日期
            logistics: orderEditData.logistics, // 物流公司
            logisticsBillCode: orderEditData.logisticsBillCode, // 物流单号
            returnReasonId: orderEditData.returnReasonId, // 退货原因
            headFileList: orderEditData.reqOrderAttachments // 退货单表头附件
          });
          // todo...
          if (orderEditData.reqOrderItems.length > 0) {
            dispatch({
              type: "returnOrderEdit/orderCartData",
              orderCartData: orderEditData.reqOrderItems
            });
            const { addressData, invoiceInfoData } = nextProps;
            if (
              orderEditData.reqOrderReceiveAddress &&
              orderEditData.reqOrderReceiveAddress.receiveAddressId
            ) {
              addressData.forEach(item => {
                item.isSelected = "0";
              });
              (
                addressData.find(
                  item =>
                    item.id ==
                    orderEditData.reqOrderReceiveAddress.receiveAddressId
                ) || {}
              ).isSelected =
                "1";
            }
            if (
              orderEditData.reqOrderInvoice &&
              orderEditData.reqOrderInvoice.invoiceId
            ) {
              invoiceInfoData.forEach(item => {
                item.isDefault = "0";
              });
              (
                invoiceInfoData.find(
                  item => item.id == orderEditData.reqOrderInvoice.invoiceId
                ) || {}
              ).isDefault =
                "1";
            }
          }
        }
      }
    }
    // 订单暂存、提交返回结果 todo...
    if ("resultOrder" in nextProps) {
      const resultOrder = nextProps.resultOrder;
      if (!resultOrder) return null;
      if (resultOrder.id) {
        const msg = "退货单提交成功";
        notification.success({
          message: msg,
          description: `退货单号为${
            resultOrder.orderCode
            },2秒后跳转到退货单列表页`,
          duration: 2
        });
        setTimeout(() => {
          dispatch(routerRedux.push("/buyer/returnOrderList"));
        }, 2000);
        dispatch({
          type: "returnOrderEdit/resultOrder",
          resultOrder: null
        });
      } else {
        const msg = "退货单提交失败";
        notification.error({
          message: msg,
          duration: 3
        });
        dispatch({
          type: "returnOrderEdit/resultOrder",
          resultOrder: null
        });
      }
    }
  }

  componentDidUpdate() {
    // 重新补充BOM信息
    if (this.ifFillBom) {
      const { dispatch, orderCartData } = this.props;
      dispatch({
        type: "returnOrderEdit/getItemBomInfo",
        payload: {
          reqOrderItems: orderCartData // 商品行信息
        }
      });
      this.ifFillBom = false;
    }
  }

  // 封装上传默认参数
  getUploadParams(id) {
    const pk = this.generateMixed();
    const params = {
      fileElementId: `${id ? id : "uploadbatch_id"}${Math.random()}`, // 【必填】文件上传空间的id属性  <input type="file" id="id_file" name="file" />,可以修改，主要看你使用的 id是什么
      filepath: pk, // 【必填】单据相关的唯一标示，一般包含单据ID，如果有多个附件的时候由业务自己制定规则
      groupname: pk, // 【必填】分組名称,未来会提供树节点
      permission: "read",
      url: true,
      cross_url: "/iuap-saas-filesystem-service/"
    };
    // const params = {
    //   name: 'file',
    //   // accept: "image/*",
    //   size: 10240000,
    //   headers: {
    //     authorization: 'authorization-text',
    //   }
    // };
    return params;
  }

  // 设为默认地址
  setDefaultHandle(index) {
    let { addressData } = this.state;
    addressData = Array.isArray(addressData)
      ? addressData
      : Object.values(addressData);

    // 设置默认收获地址
    this.props.dispatch({
      type: "orderEdit/setDefaultAddress",
      payload: {
        customer: this.customerId, // 客户id
        id: addressData[index].id // 收获地址id
      }
    })
      .finally((res) => {
        res.forEach(item => {
          if ( !!item.isDefault ) item.isSelected = "1";
          else  item.isSelected = "0";
        })
        /*
        if (res) {
          addressData.forEach(item => {
            item.isDefault = "0";
            item.isSelected = "0";
          });
          addressData[index].isDefault = "1";
          addressData[index].isSelected = "1";
        }
        */
        this.setState({
          addressData: Object.assign({}, res)
        });
      });

    /*
    addressData.forEach(item => {
      item.isDefault = "0";
      item.isSelected = "0";
    });
    addressData[index].isDefault = "1";
    addressData[index].isSelected = "1";

    this.setState({
      addressData: Object.assign({}, addressData)
    });
    */
  }

  /*
  // 设为默认地址
  setDefaultHandle(index) {
    let { addressData } = this.state;
    addressData = Array.isArray(addressData)
      ? addressData
      : Object.values(addressData);
    addressData.forEach(item => {
      item.isDefault = "0";
      item.isSelected = "0";
    });
    addressData[index].isDefault = "1";
    addressData[index].isSelected = "1";
    this.setState({
      addressData: Object.assign({}, addressData)
    });
  }
  */

  // 结算方式改变
  settlementChange(value) {
    this.setState({
      settleModeId: value
    });
  }

  selectAddressHandle(index) {
    let { addressData } = this.state;
    addressData = Array.isArray(addressData)
      ? addressData
      : Object.values(addressData);
    addressData.forEach(item => {
      item.isSelected = "0";
    });
    addressData[index].isSelected = "1";
    this.setState({
      addressData: Object.assign({}, addressData)
    });
  }

  // 备注改变
  inputValueChage(field, e) {
    e.preventDefault();
    this.headValueChange(field, e.target.value);
  }

  headValueChange(field, value) {
    this.setState({
      [`${field}`]: value
    });
  }

  // 收货日期改变
  dateChange(date, datestring) {
    this.setState({
      deliveryDate: datestring
    });
  }

  // 供应商改变
  supplierChange(value) {
    const { dispatch, supplierData } = this.props;
    // 判断供应商是否为组织
    const isOrg = ifSupplierIsOrg(value, supplierData);
    if (isOrg) {
      this.setState({
        supplierId: value,
        ifOneSupplier: true
      });
    } else {
      this.setState({
        supplierId: value,
        ifOneSupplier: false
      });
    }
    dispatch({
      type: "returnOrderEdit/orderCartData",
      orderCartData: []
    });
  }

  // 获取商品信息
  goodsInfoChange(value) {
    this.setState({
      totalDealAmount: value.newTotalDealAmount,
      totalAmount: value.newTotalAmount,
      totalReturnAmount: value.newTotaltotalReturnAmount,
      totalWeight: value.newAllWeight,
      totalVolume: value.newAllVolume,
      totalNum: value.newTotalNum
    });
  }

  // 展开收起地址
  showAddressClick() {
    this.setState({
      btnTxt: this.state.btnTxt == "展开地址" ? "收起地址" : "展开地址",
      iconType: this.state.iconType == "down" ? "up" : "down",
      isShow: !this.state.isShow
    });
  }

  // 取消
  cancelHandle() {
    const { dispatch } = this.props;
    dispatch(routerRedux.push("/buyer/returnOrderList"));
  }

  // 提交
  okHandle() {
    const { dispatch } = this.props;
    const { ifBaseReturnOrder, id } = this.state;
    let postData = this.packageOrderData();
    postData = this.fillGoodsBomInfo(postData);
    const warnInfo = this.validOrderData(postData);
    if (warnInfo) {
      message.warning(warnInfo);
      return false;
    }
    this.setState({
      loading: true
    });
    dispatch({
      type: "returnOrderEdit/submitOrder",
      payload: postData
    })
      .finally(() => {
        this.setState({
          loading: false
        });
      });
  }

  // 校验订单数据
  validOrderData(postData) {
    if (!postData) return "订单信息有误，请重新下单！";
    let msg = "";
    if (!this.state.supplierId) {
      msg += "供应商不能为空！";
    }
    if (!postData.deliveryDate) {
      msg += "预计发货日期不能为空！";
    }
    if (
      !postData.reqOrderReceiveAddress ||
      !postData.reqOrderReceiveAddress.receiveAddressId
    ) {
      msg += "收货地址信息不能为空！";
    }
    if (!postData.reqOrderInvoice || !postData.reqOrderInvoice.invoiceId) {
      msg += "发票信息不能为空！";
    }
    if (!postData.reqOrderItems || postData.reqOrderItems.length < 1) {
      msg += "商品信息不能为空！";
    }
    return msg;
  }

  // 封装订单信息
  packageOrderData() {
    const { orderCartData, location, orderEditData } = this.props;
    const {
      id,
      supplierId,
      transportModeId,
      settleModeId,
      remark,
      logistics,
      logisticsBillCode,
      returnReasonId,
      deliveryDate,
      invoiceInfoData,
      totalAmount,
      totalDealAmount,
      totalReturnAmount,
      totalWeight,
      totalVolume,
      totalNum,
      headFileList,
      srcOrderId,
      srcOrderCode,
      ifEditOrder,
      ifOneSupplier
    } = this.state;
    // 过滤上传失败的附件
    const newHeadFileList = (headFileList || []).filter(
      file => !!file.attachmentUrl
    );
    // 默认地址
    let addressData = this.state.addressData;
    addressData = Array.isArray(addressData)
      ? addressData
      : Object.values(addressData);
    const addressDefault = addressData.find(item => item.isSelected == "1") || {};
    // 默认发票
    const invoiceInfoDefault = invoiceInfoData.find(
      item => item.isDefault == "1"
    ) || {};
    // todo...
    orderCartData.forEach(item => {
      item.reqOrderId = id;
      item.id = null;
    });
    const postData = {
      // todo...
      id: ifEditOrder ? orderEditData.id : "",
      orderCode: ifEditOrder ? orderEditData.orderCode : "",
      customerId: this.customerId,
      saleOrgId: ifOneSupplier ? supplierId : "", // 销售组织 （一级经销商）
      supplierId: ifOneSupplier ? "" : supplierId, // 供应商（非一级经销商）
      saleModel: "02", // 销售模式，退货是默认为02
      transportModeId: transportModeId, // 运输方式
      settleModeId: settleModeId, // 结算方式
      deliveryDate: deliveryDate, // 期望收货日期
      totalNum: "", // 总数量
      currency: currency.id, // 币种
      currencySign: currency.currencySign, // 币符
      currencyPriceScale: currency.currencyPriceScale, // 币种单价精度
      currencyAmountScale: currency.currencyAmountScale, // 币种金额精度
      totalDealAmount: totalAmount, // 冲抵前金额
      totalDealAmount: totalDealAmount, // 成交金额
      totalReturnAmount: totalReturnAmount, // 实际退货金额
      totalWeight: totalWeight, // 总重量
      totoalVolume: totalVolume, // 总体积
      totalNum: totalNum, // 总数量
      reqOrderSource: "01", // 门户
      srcOrderId: srcOrderId, // 来源单据主键 （原单主键）
      srcOrderCode: srcOrderCode, // 来源单据编号
      originalOrderCode: srcOrderCode, // 原单编号
      remark: remark, // 订单备注
      logistics: logistics,
      logisticsBillCode: logisticsBillCode,
      returnReasonId: returnReasonId,
      reqOrderAttachments: newHeadFileList, // 附件
      reqOrderReceiveAddress: {
        reqOrderId: id,
        receiveAddressId: addressDefault.id, // 收货地址id
        receiver: addressDefault.receiver, // 收货人
        receiverTel: addressDefault.receiverTel, // 电话
        receiverPhone: addressDefault.receiverPhone, // 手机
        countryId: addressDefault.countryId,
        receiverProvince: addressDefault.receiverProvince, // 省
        receiverProvinceId: addressDefault.receiveAddressId,
        receiverCity: addressDefault.receiverCity, // 市
        receiverCityId: addressDefault.receiverCityId,
        receiverCounty: addressDefault.receiverCounty, // 县
        receiverCountyId: addressDefault.receiverCountyId,
        receiverTown: addressDefault.receiverTown, // 镇
        receiverTownId: addressDefault.receiverTownId,
        receiverAddress: addressDefault.receiverAddress, // 详细地址
        receiverZipcode: addressDefault.receiverZipcode // 邮编
      },
      reqOrderInvoice: {
        reqOrderId: id,
        invoiceId: invoiceInfoDefault.id, // 发票id
        invoiceType: invoiceInfoDefault.invoiceType, // 发票类型
        invoiceContent: invoiceInfoDefault.invoiceContent, // 开票项目
        invoiceTitle: invoiceInfoDefault.invoiceTitle, // 发票抬头
        invoiceTaxId: invoiceInfoDefault.invoiceTaxId, // 纳税人识别码
        invoiceBank: invoiceInfoDefault.invoiceBank, // 开户银行
        invoiceAccount: invoiceInfoDefault.invoiceAccount, // 开户账户
        invoiceSubBank: invoiceInfoDefault.invoiceSubBank // 支行
      },
      reqOrderItems: orderCartData
    };
    return Object.assign({}, postData);
  }

  fillGoodsBomInfo(postData) {
    const reqOrderItems = postData.reqOrderItems;
    const reqOrderItemBoms = translateItemBomFromItem(reqOrderItems);
    postData.reqOrderItems = reqOrderItems;
    postData.reqOrderItemBoms = reqOrderItemBoms;
    return postData;
  }

  // showCustfeeDialog() {
  //   this.props.dispatch({
  //     type: "global/custfeeVisible",
  //     payload: true
  //   });
  // }
  // 退货单表头附件上传
  filehandleChange(info) {
    let fileList = info.fileList;
    fileList = fileList.slice(-3);
    fileList = fileList.map(file => {
      if (file.response && file.response.data) {
        file.attachmentUrl = file.response.data[0].url;
        file.attachmentName = file.response.data[0].filename;
      }
      return file;
    });
    fileList = fileList.filter(file => {
      if (file.response) {
        return !!file.attachmentUrl;
      }
      return true;
    });

    this.setState({
      headFileList: fileList
    });
  }

  generateMixed() {
    var chars = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
      "G",
      "H",
      "I",
      "J",
      "K",
      "L",
      "M",
      "N",
      "O",
      "P",
      "Q",
      "R",
      "S",
      "T",
      "U",
      "V",
      "W",
      "X",
      "Y",
      "Z"
    ];
    var result = "";
    for (var i = 0; i < 20; i++) {
      var id = Math.ceil(Math.random() * 35);
      result += chars[id];
    }
    return result;
  }

  showInvoiceDialog() {
    this.props.dispatch({
      type: "global/invoiceVisible",
      payload: true
    });
  }

  showModal() {
    const { supplierId } = this.state;
    if (!supplierId) {
      message.info("请选择供应商后再添加商品！");
      return false;
    }
    this.props.dispatch({
      type: "global/treeListVisible",
      payload: true
    });
  }

  addGoodsInfo(treeListSelectedRows) {
    const { orderCartData, dispatch } = this.props;
    let newOrderCartData = [];
    if (typeof orderCartData == "object") {
      newOrderCartData = orderCartData.concat([]);
    }
    // 判断添加的商品是否重复 todo...
    treeListSelectedRows.forEach(addRow => {
      let repeat = false;
      const conversionRate = parseFloat(addRow.conversionRate || "1");
      newOrderCartData.forEach(item => {
        // 重复，则累加订货数量、主数量
        if (item.goodsId == addRow.id) {
          item.orderNum += 1;
          item.mainNum += conversionRate;
          repeat = true;
        }
      });
      if (!repeat) {
        addRow.orderNum = 1;
        addRow.mainNum = conversionRate;
        const addRows = setItemsDefaultData([addRow], true);
        newOrderCartData = newOrderCartData.concat(addRows);
      }
    });
    dispatch({
      type: "returnOrderEdit/orderCartData",
      orderCartData: newOrderCartData
    });
    // 重新询BOM信息
    this.ifFillBom = true;
  }

  render() {
    const {
      btnTxt,
      iconType,
      isShow,
      totalAmount,
      totalDealAmount,
      promAmount,
      totalReturnAmount,
      totalWeight,
      totalVolume,
      invoiceInfoData,
      supplierId,
      transportModeId,
      settleModeId,
      supplierDisabled,
      ifBaseReturnOrder
    } = this.state;
    const {
      logisticsData,
      settlementData,
      orderCartData,
      supplierData,
      returnCauseData
    } = this.props;
    let addressData = this.state.addressData;
    addressData = Array.isArray(addressData)
      ? addressData
      : Object.values(addressData);
    // 收货地址
    const addressHtml = () => {
      if (!addressData) return null;
      const htmlArr = [];
      let defaultHtml;
      for (let i = 0; i < addressData.length; i++) {
        const index = i;
        if (addressData[i].isSelected == 1) {
          defaultHtml = (
            <li className={styles.addressItem} key={addressData[i].id}>
              <span
                className={styles.name}
                style={{ border: "2px solid #E14C46" }}
              >
                {addressData[i].receiver}
              </span>
              <div className={styles.infoBox}>
                <span className={styles.addressTxt}>
                  {addressData[i].receiverProvince}{" "}
                  {addressData[i].receiverCity}{" "}
                  {addressData[i].receiverCounty}{" "}
                  {addressData[i].receiverTown} {addressData[i].receiverAddress}
                </span>
                <span className={styles.phoneNumber}>
                  {addressData[i].receiverPhone ? addressData[i].receiverPhone.substr(0, 3) + "****" + addressData[i].receiverPhone.substring(7, 11) : ""}
                </span>
                <span
                  style={{
                    display:
                      addressData[i].isDefault == 1 ? "inline-block" : "none"
                  }}
                  className={styles.defaultBtn}
                >
                  默认地址
                </span>
                <span
                  className={
                    addressData[i].isDefault == 1
                      ? styles.defaultAdr
                      : styles.setDefault
                  }
                  onClick={this.setDefaultHandle.bind(this, index)}
                >
                  设为默认
                </span>
              </div>
            </li>
          );
        } else {
          const html = (
            <li
              className={styles.addressItem}
              key={addressData[i].id}
              style={{ display: isShow ? "block" : "none" }}
            >
              <span
                className={styles.name}
                onClick={this.selectAddressHandle.bind(this, index)}
              >
                {addressData[i].receiver}
              </span>
              <div className={styles.infoBox}>
                <span className={styles.addressTxt}>
                  {addressData[i].receiverProvince}{" "}
                  {addressData[i].receiverCity}{" "}
                  {addressData[i].receiverCounty}{" "}
                  {addressData[i].receiverTown} {addressData[i].receiverAddress}
                </span>
                <span className={styles.phoneNumber}>
                  {addressData[i].receiverPhone ? addressData[i].receiverPhone.substr(0, 3) + "****" + addressData[i].receiverPhone.substring(7, 11) : ""}
                </span>
                <span
                  style={{
                    display:
                      addressData[i].isDefault == 1 ? "inline-block" : "none"
                  }}
                  className={styles.defaultBtn}
                >
                  默认地址
                </span>
                <span
                  className={
                    addressData[i].isDefault == 1
                      ? styles.defaultAdr
                      : styles.setDefault
                  }
                  onClick={this.setDefaultHandle.bind(this, index)}
                >
                  设为默认
                </span>
              </div>
            </li>
          );
          htmlArr.push(html);
        }
      }
      htmlArr.unshift(defaultHtml);
      return htmlArr;
    };
    // 拼接下拉框选项
    const selectOptionHtml = listData => {
      if (!listData || listData.length < 1) return null;
      const optionHtmls = listData.map(item => (
        <Select.Option key={item.id} value={item.id}>
          {item.name}
        </Select.Option>
      ));
      return optionHtmls;
    };
    // 发票信息
    const invoiceInfoHtml = () => {
      if (!invoiceInfoData) return null;
      const invoiceInfo = invoiceInfoData.find(item => item.isDefault == 1);
      let html;
      if (!invoiceInfo) {
        html = (
          <Row className={styles.invoiceInfo}>
            <Col span={2}/>
            <Col span={4}/>
            <Col span={2} className={styles.taxpayersNum}>
              纳税人识别号：
            </Col>
            <Col span={4}/>
            <Col span={2} className={styles.bank}>
              开户行：
            </Col>
            <Col span={4}/>
            <Col span={1} className={styles.account}>
              账号：
            </Col>
            <Col span={4}/>
            <Col span={1}>
              <span
                className={styles.selectBtn}
                onClick={this.showInvoiceDialog.bind(this)}
              >
                选择
              </span>
            </Col>
          </Row>
        );
      } else {
        html = (
          <Row className={styles.invoiceInfo}>
            <Col span={2}>{invoiceInfo.invoiceType}</Col>
            <Col span={4} title={invoiceInfo.invoiceTitle}>
              {invoiceInfo.invoiceTitle}
            </Col>
            <Col span={2} className={styles.taxpayersNum}>
              纳税人识别号：
            </Col>
            <Col span={4} title={invoiceInfo.invoiceTaxId}>
              <em>{invoiceInfo.invoiceTaxId}</em>
            </Col>
            <Col span={2} className={styles.bank}>
              开户行：
            </Col>
            <Col span={4} title={invoiceInfo.invoiceBank}>
              <em>{invoiceInfo.invoiceBank}</em>
            </Col>
            <Col span={1} className={styles.account}>
              账号：
            </Col>
            <Col span={4} title={invoiceInfo.invoiceAccount}>
              <em>{invoiceInfo.invoiceAccount}</em>
            </Col>
            <Col span={1}>
              <span
                className={styles.selectBtn}
                onClick={this.showInvoiceDialog.bind(this)}
              >
                选择
              </span>
            </Col>
          </Row>
        );
      }
      return html;
    };
    const disabledDate = current => {
      return current && current.valueOf() <= Date.now() - 86400000;
    };
    const fileProps = {
      // action: '/b2b/req-file/upload',
      // action: '/wbalone/userMGT/fastDfs/imgUpload',
      action: "/iuap-saas-filesystem-service/file/upload",
      data: this.getUploadParams.bind(this, "head-upload"),
      fileList: this.state.headFileList || [],
      onChange: this.filehandleChange.bind(this)
    };
    return (
      <div className={styles.returnOrderEidtBox}>
        {/* <BreadcrumbPackage additems={BreadcrumbPaths} /> */}
        <Spin spinning={this.state.loading}>
          <div className={styles.supplierBox}>
            <span className={styles.name}>
              {supplierDisabled ? "供应商" : "请选择供应商"}
            </span>
            <Select
              className={styles.supplierSelect}
              value={supplierId}
              disabled={supplierDisabled}
              onChange={this.supplierChange.bind(this)}
            >
              {selectOptionHtml(supplierData)}
            </Select>
          </div>
          {/* 订单信息 */}
          <div className={styles.orderInfoBox}>
            {/* 收货地址 */}
            <div className={styles.consigneeInfo}>
              <p className={styles.consigneeInfoTxt}>发货人信息</p>
              <div className={styles.addressListBox}>
                <div className={styles.scrollbar}>
                  <ul className={styles.addressList}>{addressHtml()}</ul>
                </div>
              </div>
              <span
                className={styles.showBtn}
                onClick={this.showAddressClick.bind(this)}
              >
                {btnTxt}
                <Icon type={`${iconType}`} className={styles.icon}/>
              </span>
            </div>
            {/* 收货地址-- 结束 */}
            {/* 发票信息 */}
            <div className={styles.logisticsSettlement}>
              <p className={styles.logisticsSettlementTxt}>发票信息</p>
              <div className={styles.logistics}>{invoiceInfoHtml()}</div>
            </div>
            {/* 发票信息--end */}
            {/* 退货信息 --start */}
            <div className={styles.logisticsSettlement}>
              <p className={styles.logisticsSettlementTxt}>退货信息</p>
              <div className={styles.returnInfo}>
                <Row className={styles.returnRow}>
                  <Col span={2} className={styles.returnLabel}>
                    物流/快递公司
                  </Col>
                  <Col span={3}>
                    <Input
                      className={styles.iptBox}
                      value={this.state.logistics}
                      onChange={this.inputValueChage.bind(this, "logistics")}
                    />
                  </Col>
                  <Col span={2} className={styles.returnLabel}>
                    单号
                  </Col>
                  <Col span={4}>
                    <Input
                      className={styles.iptBox}
                      value={this.state.logisticsBillCode}
                      onChange={this.inputValueChage.bind(
                        this,
                        "logisticsBillCode"
                      )}
                    />
                  </Col>
                  <Col span={3} className={styles.returnLabel}>
                    预计发货日期
                  </Col>
                  <Col span={3}>
                    <DatePicker
                      className={styles.datePickerBox}
                      defaultValue={moment(this.state.deliveryDate)}
                      disabledDate={disabledDate}
                      onChange={this.dateChange.bind(this)}
                    />
                  </Col>
                  <Col span={3} className={styles.returnLabel}>
                    退货原因
                  </Col>
                  <Col span={4}>
                    <Select
                      className={styles.selectBox}
                      value={this.state.returnReasonId}
                      onChange={this.headValueChange.bind(
                        this,
                        "returnReasonId"
                      )}
                    >
                      {selectOptionHtml(this.props.returnCauseData)}
                    </Select>
                  </Col>
                </Row>
                <Row className={styles.returnRow}>
                  <Col span={2} className={styles.returnLabel}>
                    附件
                  </Col>
                  <Col span={12}>
                    <Upload {...fileProps} className={styles.headUpload} key="head-upload">
                      <Button className={styles.btnBox}>上传</Button>
                    </Upload>
                    <div className={styles.uploadTip}>(提示：最多上传三张)</div>
                  </Col>
                  <Col span={10} className={styles.taxpayersNum}>
                    <Input
                      className={styles.iptBox}
                      placeholder="备注说明内容"
                      value={this.state.remark}
                      onChange={this.inputValueChage.bind(this, "remark")}
                    />
                  </Col>
                </Row>
              </div>
            </div>
            {/* 退货信息 --end */}
          </div>
          {/* 订单信息--结束 */}
          <Button
            style={{ display: ifBaseReturnOrder ? "none" : "inline-block" }}
            className={styles.addGoodsBtn}
            onClick={this.showModal.bind(this)}
          >
            <Icon type="plus" className={styles.icon}/>增加商品
          </Button>
          {/* 商品 */}
          <ReturnOrderGoodsList
            getUploadParams={this.getUploadParams.bind(this)}
            orderCartData={orderCartData}
            returnTypeData={this.props.returnTypeData}
            returnCauseData={returnCauseData}
            ifBaseReturnOrder={ifBaseReturnOrder}
            onChange={this.goodsInfoChange.bind(this)}
            {...this.props}
            ref={c => {
              this.ReturnOrderGoodsList = c;
            }}
          />
          {/* 商品--end */}
          {/* 订单底部信息 */}
          <div className={styles.orderGoodsTotal}>
            <div className={styles.totalDealAmount}>
              <span className={styles.name}>退货总金额：</span>
              <span className={styles.valueBox}>￥{totalDealAmount.toFixed(currency.currencyAmountScale)}</span>
            </div>
            {/* <div className={styles.totalDealAmount}>
              <span className={styles.name}>实际退货总金额：</span>
              <span className={styles.valueBox}>￥{totalReturnAmount.toFixed(currency.currencyAmountScale)}</span>
            </div> */}
            <div className={styles.btnBox}>
              <div className={styles.cancelBtn}>
                <Popconfirm
                  title="是否确定取消？"
                  onConfirm={this.cancelHandle.bind(this)}
                >
                  <Button className={styles.btn}>取消</Button>
                </Popconfirm>
                <Button
                  className={styles.btn}
                  onClick={this.okHandle.bind(this)}
                >
                  提交
                </Button>
              </div>
            </div>
          </div>
          {/* 订单底部信息--end */}

          <TreeListModal
            ref={ref => (this.state.ref.treeListModal = ref)}
            title="请选择商品"
            supplierId={this.state.supplierId}
            treeUrl="/buyer/goods-category/tree"
            listUrl="/b2b/goods/find-by-customer"
            saleModel="03"
            onConfirm={this.addGoodsInfo.bind(this)}
          />
          <InvoiceDialog invoiceInfoData={invoiceInfoData} orderType="return"/>
        </Spin>
      </div>
    );
  }
}

export default connect(state => ({
  supplierData: state.returnOrderEdit.supplierData,
  addressData: state.returnOrderEdit.addressData,
  invoiceInfoData: state.returnOrderEdit.invoiceInfoData,
  orderCartData: state.returnOrderEdit.orderCartData,
  resultOrder: state.returnOrderEdit.resultOrder,
  orderEditData: state.returnOrderEdit.orderEditData,
  returnCauseData: state.returnOrderEdit.returnCauseData,
  returnTypeData: state.returnOrderEdit.returnTypeData
}))(OrderEidt);
