import React from 'react';
import {observer, inject} from 'mobx-react';
import {
  Card, CardTitle, CardText,
  Divider,
  MenuItem,
  FlatButton,
  RaisedButton,
  Table,
  TableBody,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn,
  TextField,
  Toolbar,
  ToolbarGroup,
  ToolbarSeparator, ToolbarTitle, CardHeader, Dialog, FontIcon, Avatar, ListItem
} from 'material-ui';
import {Link} from 'react-router-dom';
import {LINKS} from "../../../routes";
import {DIALOG} from "../../../stores/global_ui";
import AddIcon from 'material-ui/svg-icons/content/add';
import RemoveIcon from 'material-ui/svg-icons/content/remove';
import NavigationArrowBack from 'material-ui/svg-icons/navigation/arrow-back';
import {Timeline, Icon, Affix} from 'antd';
import MakePaymentDialog from './MakePaymentDialog/index';
import CancelPaymentDialog from './CancelPaymentDialog/index';
import moment from "moment";
import get from 'lodash.get';
import DC from 'decimal.js-light';
import NumberFormat from 'react-number-format';
import EmptyComponent from '../../EmptyComponent';
import confirm from '../../../util/confirm';
import {constant} from "../../../config/const";
import MerchantInputShippingCodeDialog from "./MerchantInputShippingCodeDialog";
import GojekDelivery from "./GojekDelivery";
import LoadingDialog from '../../LoadingDialog/index';
import PreorderAddNotes from './PreorderAddNotes';
import '../style.scss'
import {uniqBy,startCase,upperCase,reverse} from 'lodash';
import PrintProvider, {Print, NoPrint} from 'react-easy-print';
import PrintIcon from 'material-ui/svg-icons/action/print';
@inject('appstate')
@observer
export default class OrderDetailComponent extends React.Component {

  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      value: 1,
      searchText: '',
      slideIndex: 0,
      tabSelected: 'gi',
      openModal: false,
      errorBook: false,
      errorMessage: '',
      itemData: {}
    };
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.authStore = props.appstate.auth;
    this.globalUI = props.appstate.globalUI;
    this.order = props.appstate.order;
  }

  componentDidMount() {
    this.order.getDetail(this.props.match.params.id);

  }

  handleUpdateInput = (searchText) => {
    this.setState({
      searchText: searchText,
    });
  };

  handleNewRequest = () => {
    this.setState({
      searchText: '',
    });
  };

  tabsHandleChange = (value) => {
    this.setState({
      slideIndex: value,
    });
  };

  closeError = () => {
    this.setState({
      errorBook: false
    })
  }


  handleChange = (tabSelected) => {
    this.setState({
      tabSelected: tabSelected,
    });
    // this.props.history.push(tabSelected);
  };

  handleCloseModal = () => {
    this.setState({
      openModal: false
    })
  };

  calculatePrice = () => {
    this.globalUI.openLoading();
    this.order.calculatePrice().then(res => {
      this.globalUI.closeLoading();
      this.props.appstate.globalUI.showDialog(DIALOG.ORDER.GOJEK_DELIVERY);
    }).catch(err => {
      this.globalUI.closeLoading();
      this.setState({
        errorBook: true,
        errorMessage: err.message
      });
    })
  }

  handleOpenModal = () => {
    this.setState({
      openModal: true
    })
  }

  openPreorderDialog = (data) => {
    console.log(data, 'ini data');
    this.setState({
      itemData: {
        preorder_store_note: data.preorder_store_note,
        preorder_buyer_note: data.preorder_buyer_note,
        //preorder_price: data.preorder_price || 0,
        preorder_price: data.item.regular_price || 0,
        regular_price: data.item.regular_price,
        preorder_weight: data.preorder_weight || 0,
        user_order_item_id: data.id,
        order_store_id: this.order.selectedOrder.id,
        order_status_id: this.order.selectedOrder.order_status_id,
        item_stock_available : data.item.stock
      }
    }, () => this.props.appstate.globalUI.showDialog(DIALOG.ORDER.PREORDER_ADD_NOTES));
  }

  orderHistoryText = (history)=>{
    if(history.order_status_id == constant.ORDER_STATUSES.PREORDER_WAITING_STORE_RESPONSE){
      return (
        <div>
          Buyer waiting for store response for order items
        </div>
      )
    }
    else if(history.order_status_id == constant.ORDER_STATUSES.PREORDER_WAITING_BUYER_CONFIRMATION){
      return (
        <div>
          Waiting for buyer for confirm new weight and price
        </div>
      )
    }
    else if(history.order_status_id == constant.ORDER_STATUSES.PREORDER_WAITING_PAYMENT){
      return (
        <div>
          Waiting buyer to pay the order
        </div>
      )
    }
    else if(history.order_status_id == constant.ORDER_STATUSES.PENDING_PAYMENT){
      return (
        <div>
          Payment from buyer pending
        </div>
      )
    }
    else if(history.order_status_id == constant.ORDER_STATUSES.PROCESSING){
      return (
        <div>
          Order ready to process
        </div>
      )
    }
    else if(history.order_status_id == constant.ORDER_STATUSES.ON_SHIPPING){
      return (
        <div>
          Order is on shipping
        </div>
      )
    }
    else if(history.order_status_id == constant.ORDER_STATUSES.COMPLETED){
      return (
        <div>
          Order is complete, package accepted by buyer
        </div>
      )
    }
    else if(history.order_status_id == constant.ORDER_STATUSES.PREORDER_BUYER_DECLINE){
      return (
        <div>
          Preorder new weight and price decline by buyer
        </div>
      )
    }
    else{
      return (
        <div>
          {history.status.name}
        </div>
      )
    }
  }

  handlePrint() {
    window.print();
  }

  getStatusDeliveryColor = (type) =>{
    if(type == "delivered"){
      return 'green'
    }else if(type == "on_hold"){
      return 'orange'
    }
    else if(type == "cancelled" || type=='rejected'){
      return 'red'
    }
    else {
      return 'green'
    }
  }

  getShipmentTrackingMessage = (tracking)=>{
    let message = tracking.cancellation_reason.split(' - ');
    let statusColor = 'green';
    let shipmentStatus = '';
    let object = 'Item';

    if(tracking.status == "on_hold"){
      statusColor= 'orange';
      shipmentStatus = 'On Hold'
    }
    else if(tracking.status == 'delivered'){
      shipmentStatus = 'Finished';
    }
    else if(tracking.status == "cancelled" || tracking.status=='rejected' || tracking.status == 'no_driver'){
      statusColor = 'red';
      shipmentStatus = 'Finished'
    }

    if(tracking.type == 'CREATED' || tracking.type =='COMPLETED' || tracking.type == 'SYSTEM_CANCELLED' || tracking.type == 'DRIVER_NOT_FOUND')
    {
      object = 'Booking'
    }else if(tracking.type == 'DRIVER_FOUND'){
      object = 'Driver'
    }
    else if(tracking.type == 'PICKED_UP'){
      object = 'Item'
    }

    return {
      title : upperCase(startCase(tracking.type))+ ` - ${object} `+startCase(tracking.status),
      is_cancelled : !!tracking.cancellation_reason,
      cancellation_reason : message[1]+' - '+startCase(message[0]),
      status : shipmentStatus,
      status_color : statusColor
    }
  }

  _renderShipmentTracking = (data)=>{
      if(data.length > 0 ){
        return (
          <div className="row itenary ">
            <ul>
              {data.map((it,index)=>{
                let shipment_track = this.getShipmentTrackingMessage(it.tracking);
                return (
                  <li key={index}><span/>
                    <div>
                      <div className="title">{shipment_track.title}</div>
                      <div className="info">{moment(it.created_at).format('DD-MM-YYYY HH:mm')}</div>
                      {(shipment_track.is_cancelled) && <div className="info">{shipment_track.cancellation_reason}</div>}
                      <div className="type" style={{color: shipment_track.status_color}}>{shipment_track.status}</div>
                    </div>
                  </li>
                )
            })}
            </ul>
          </div>
        )
      }
      else{
        return <EmptyComponent width="" image="default4" type="empty" header="" content="No history of shipment yet!"/>
      }
  }

  getOrderColor = (statusId) =>{
    const {ORDER_STATUSES} = constant;
    // {(this.order.selectedOrder.order_status.name === "Preorder Buyer Decline") ? 'status red' : (this.order.selectedOrder.order_status.name === 'Processing') ? 'status process' : 'status pending'}
    if(statusId == ORDER_STATUSES.CANCELLED || statusId == ORDER_STATUSES.FAILED || statusId == ORDER_STATUSES.CANCELLED_BY_STORE || statusId == ORDER_STATUSES.PREORDER_BUYER_DECLINE){
      return 'status red'
    }
    else if(  statusId == ORDER_STATUSES.ON_SHIPPING_RETRY ||
        statusId == ORDER_STATUSES.WAITING_STORE_RESPONSE  || statusId == ORDER_STATUSES.PROCESSING ||
        statusId == ORDER_STATUSES.ON_HOLD || statusId == ORDER_STATUSES.PREORDER_WAITING_STORE_RESPONSE|| statusId ==  ORDER_STATUSES.PENDING_PAYMENT || statusId == ORDER_STATUSES.PREORDER_WAITING_PAYMENT || statusId == ORDER_STATUSES.WAITING_PAYMENT_APPROVAL || statusId == ORDER_STATUSES.PREORDER_WAITING_BUYER_CONFIRMATION

    ) {
      return 'status pending';
    }
    else if(statusId == ORDER_STATUSES.COMPLETED  || statusId == ORDER_STATUSES.SHIPPING_COMPLETE
      ||statusId == ORDER_STATUSES.ON_SHIPPING  ){
      return 'status process'
    }

  }

  orderStatusDesc = (statusId) =>{
    const {ORDER_STATUSES} = constant;
    if(statusId == ORDER_STATUSES.WAITING_PAYMENT_APPROVAL){
      return 'Payment is still waiting for approval, please wait'
    }
    else if(statusId == ORDER_STATUSES.ON_SHIPPING){
      return 'Order is on delivery to buyer'
    }
    else if(statusId == ORDER_STATUSES.ON_SHIPPING_RETRY){
      return 'Something wrong in delivery process, please retry or rebook courier'
    }
    else if(statusId == ORDER_STATUSES.SHIPPING_COMPLETE){
      return 'Buyer has accept the order and delivery is completed'
    }
    else if(statusId == ORDER_STATUSES.WAITING_STORE_RESPONSE){
      return 'Order is waiting for you to response'
    }
    else if(statusId == ORDER_STATUSES.CANCELLED_BY_STORE){
      return 'Order is cancelled by you'
    }
    else if(statusId == ORDER_STATUSES.PENDING_PAYMENT){
      return 'Order is waiting buyer to complete the payment'
    }
    else if(statusId == ORDER_STATUSES.FAILED){
      return 'Order is failed for some reason'
    }
    else if(statusId == ORDER_STATUSES.PROCESSING){
      return 'Order is ready to processing'
    }
    else if(statusId == ORDER_STATUSES.COMPLETED){
      return 'Order is completed'
    }
    else if(statusId == ORDER_STATUSES.ON_HOLD){
      return 'Order is on hold'
    }
    else if(statusId == ORDER_STATUSES.CANCELLED){
      return 'Order is cancelled'
    }
    else if(statusId == ORDER_STATUSES.PREORDER_WAITING_STORE_RESPONSE){
      return 'Order is waiting for you to response'
    }
    else if(statusId == ORDER_STATUSES.PREORDER_WAITING_BUYER_CONFIRMATION){
      return 'Order is waiting buyer to confirm the order'
    }
    else if(statusId == ORDER_STATUSES.PREORDER_BUYER_DECLINE){
      return 'Order is decline by buyer'
    }
    else if(statusId == ORDER_STATUSES.PREORDER_WAITING_PAYMENT){
      return 'Order is waiting buyer to complete the payment'
    }
    else {
      return 'This status order to define flow of order';
    }
  }

  render() {
    const customer = {
      name: 'Ridwan Abadi',
      identity_number: '98261536156313561',
      email: 'welove6215@einrot.com',
      address: 'Jalan Pramuka No. 81, Marga Jaya, Bekasi Selatan, Marga Jaya, Bekasi Sel., Kota Bks, Jawa Barat 17141',
      handphone: '081190876',
      phone: '0',
      place_birth: 'Jakarta',
      birth_date: moment().format('DD MMM YYYY'),
      gender: 'Male',
      tax_id: '98261536156313561',
      martial_status: 'Married'
    }

    const order = {
      id: '467d6b50-ade0-4dd0-98ca-35cd083e16e0',
      order_id: 'book_461a1df5',
      package: 'The Exoticsm Of Minang',
      description: 'Feel the joy of wonderful world of exotic, culture, and outstanding view that will amaze you to the bone. Enjoy your holiday in very nice and peaceful place to clear your mind. With great hotel and profesional tour guide, we ensure you that you will have a unforgetable memories and happiness.\n',
      registered: moment(),
      detail_package: [
        {
          name: 'Destination',
          value: 'Bukittinggi, Minangkabau'
        },
        {
          name: 'Transport',
          value: 'Custom'
        },
        {
          name: 'Duration',
          value: '4 day 3 night'
        }
      ],
      payment_type: 'Instalment',
      status: 'active'
    }

    const totalPaid = get(this.order.selectedOrder, 'payments', [])
      .map(pay => (pay.type == 'cancel_payment') ? pay.amount = 0 : pay.amount)
      .reduce((total, v) => total.add(v), new DC(0));

    const priceAfterDisc = get(this.order.selectedOrder, 'price_after_discount', 0);
    const disc = new DC(get(this.order.selectedOrder, 'price') || 0).minus(priceAfterDisc || 0);

    const amountDue = new DC(priceAfterDisc || 0).minus(totalPaid);
    // const amountDue = new DC(0);

    const actionsModals = [
      <FlatButton
        label="Cancel"
        primary={true}
        onClick={this.handleCloseModal}
      />,
      <FlatButton
        label="Ok"
        primary={true}
        onClick={() => {
          this.order.payAirlineTicket().then((airlineTicket) => {
            this.order.setOrderStatus('ticketed');
            this.globalUI.openSnackbar('Payment success');
          });
        }}
      />,
    ];



    return (
      <PrintProvider>
        <NoPrint>
          <div className="orderDetail containerMiddle animated fadeIn">
            <Dialog
              title="Are you sure that all data is correct?"
              actions={actionsModals}
              modal={true}
              open={this.state.openModal}
            >
              You will be charged
            </Dialog>

            <div style={{marginBottom: '10px'}}>
              <FlatButton
                className="headerMenu"
                hoverColor="#f1f5f9"
                style={{background: '#ffffff00'}}
                onClick={() => this.props.history.goBack()}
                label="Back"
                primary={true}
                icon={<NavigationArrowBack/>}
              />
            </div>

            <MakePaymentDialog/>

            <CancelPaymentDialog/>
            <MerchantInputShippingCodeDialog/>
            <GojekDelivery/>
            <PreorderAddNotes defaultValue={this.state.itemData}/>

            <div className="row">
              <div className="col s12 m9 l9" style={{marginBottom: 0}}>
                <Card className="cardLite cardDashboard row alert">
                  <CardHeader
                    title={
                      <Toolbar style={{backgroundColor: '#fff', padding: 0}}>
                        <ToolbarGroup>
                          <CardHeader
                            style={{padding: 0}}
                            subtitle={<p>{this.orderStatusDesc(this.order.selectedOrder.order_status_id)}</p>}
                            title={(this.order.selectedOrder.order_status === null) ? "No Status" : <div style={{
                              fontWeight: '500', fontSize: "1.25rem",
                              lineHeight: 1.2,
                              color: " #334152"
                            }}>
                          <span
                            className={this.getOrderColor(this.order.selectedOrder.order_status_id)}/> {(this.order.selectedOrder.order_status.name).split('Preorder')}
                            </div>}
                          />
                        </ToolbarGroup>
                        <ToolbarGroup>
                          <RaisedButton label="Print" icon={<PrintIcon/>} primary={true} onClick={() => this.handlePrint()}/>
                        </ToolbarGroup>
                        <ToolbarGroup>
                          {this.order.selectedOrder.order_status_id === constant.ORDER_STATUSES.WAITING_STORE_RESPONSE &&
                          <RaisedButton label="Accept Order" primary={true} onClick={() => {
                            confirm('Are you sure want to accept this order').then(() => {
                              this.order.acceptOrder();
                            });
                          }}/>}
                          {this.order.selectedOrder.order_status_id === constant.ORDER_STATUSES.WAITING_STORE_RESPONSE &&
                          <RaisedButton label="Decline Order" primary={true} onClick={() => {
                            this.order.declineOrder();
                          }}/>}
                          {(this.order.selectedOrder.order_status_id === constant.ORDER_STATUSES.PROCESSING && (this.order.selectedOrder.shipping_method_id !== constant.SHIPPING_METHOD.GOJEK_SAME_DAY && this.order.selectedOrder.shipping_method_id !== constant.SHIPPING_METHOD.GOJEK_INSTANT)) &&
                          <RaisedButton label="Input Shipping Code" primary={true} onClick={() => {
                            this.props.appstate.globalUI.showDialog(DIALOG.ORDER.INPUT_SHIPPING_CODE);
                          }}/>}
                          {((this.order.selectedOrder.order_status_id === constant.ORDER_STATUSES.PROCESSING || this.order.selectedOrder.order_status_id === constant.ORDER_STATUSES.ON_SHIPPING_RETRY) && (this.order.selectedOrder.shipping_method_id === constant.SHIPPING_METHOD.GOJEK_SAME_DAY || this.order.selectedOrder.shipping_method_id === constant.SHIPPING_METHOD.GOJEK_INSTANT)) &&
                          <RaisedButton label="Booking Gojek" primary={true} onClick={() => {
                            this.calculatePrice()
                          }}/>}
                        </ToolbarGroup>
                      </Toolbar>
                    }
                  />
                </Card>


                  <Print main name=" foo">
                    <Card className="cardLite cardDashboard row">

                      <div className="flexSpaceBetween">
                        <div className="orderContainerHeader">
                          <CardTitle style={{padding: 0, fontSize: 20}}
                                     titleStyle={{fontSize: 20, color: '#334152', margin: 0}}
                                     title={<div className={'orderFormHeading'}>
                                       <h3 style={{margin: 0}}>Order Details</h3>
                                       <p className={'orderFormDate'}
                                          style={{margin: 0}}>{moment(this.order.selectedOrder.created_at).format("DD MMMM YYYY, HH:mm:ss")}</p>
                                     </div>}
                          />
                          <div>
                            {/*<div className="orderFormLabel">Order #</div>*/}
                            <div className="orderFormLabelNumber">
                              <span style={{color : '#3E4B5B',fontWeight : 'bold'}}>Order #</span> <span>INV/{moment(this.order.selectedOrder.created_at).format("YYYYMMDD")}/XVII/{this.order.selectedOrder.id.split('-')[0]}</span></div>

                          </div>
                          <div>
                            <div className="orderFormLabelNumber">
                              <span style={{color : '#3E4B5B',fontWeight : 'bold'}}>Shipping By</span> : <span>{this.order.selectedOrder.shipping_method.name}</span></div>

                          </div>
                        </div>
                        <ToolbarGroup>
                          {
                            this.order.orderDetail.type === 'packages' && this.order.orderDetail.status !== 'canceled' && (
                              <RaisedButton icon={<AddIcon/>} label="Make Payment" primary={true}
                                            onClick={() => this.globalUI.showDialog(DIALOG.ORDER.MAKE_PAYMENT)}/>)
                          }
                          {
                            this.order.orderDetail.type === 'packages' && this.order.orderDetail.status !== 'canceled' && (
                              <RaisedButton icon={<RemoveIcon/>} label="Cancel Booking" primary={false}
                                            onClick={() => this.globalUI.showDialog(DIALOG.ORDER.CANCEL_PAYMENT)}/>)
                          }
                          {
                            this.order.orderDetail.type === 'airline' && this.order.orderDetail.status === 'booked' &&
                            (<RaisedButton icon={<AddIcon/>} label="Pay" primary={true}
                                           onClick={() => this.handleOpenModal()}/>)
                          }
                          {
                            this.order.orderDetail.type === 'airline' && this.order.orderDetail.status === 'ticketed' &&
                            (<RaisedButton icon={<AddIcon/>} label="Print Ticket" primary={true}
                                           onClick={() => this.globalUI.showDialog(DIALOG.ORDER.MAKE_PAYMENT)}/>)
                          }{
                          this.order.orderDetail.type === 'packages' && this.order.orderDetail.status === 'canceled' && (
                            <p>This order is already Cancelled</p>)
                        }
                        </ToolbarGroup>
                      </div>
                      <Divider/>
                      <CardHeader style={{paddingBottom: 0, paddingTop: 18, paddingLeft: 18, paddingRight: 18}}
                                  subtitle={<h2 style={{fontSize: 12}}>CUSTOMER INFORMATION</h2>}/>
                      <CardText style={{paddingBottom: 0, padding: '8px 18px 0 18px'}}>
                        <div style={{
                          boxShadow: "none",
                          border: "1px solid #d4d4d4",
                          backgroundColor: "#f9f9f9",
                          padding: "10px 10px 10px 20px",
                          marginTop: 0,
                          marginBottom: 0,
                          textAlign: ''
                        }} className="card-panel">
                          <div className="row no-margin">

                            <div className="col s12 m12 l6">
                              <div className="listCustDetail">
                                <div className="listCustDetailItem flex">
                                  <p className="listCustomerDetailItemKey">Name</p>
                                  <p
                                    className="listCustomerDetailItemValue">{(this.order.selectedOrder.user_orders.user.profile.firstname == null) ? 'empty first name' : this.order.selectedOrder.user_orders.user.profile.firstname} {(this.order.selectedOrder.user_orders.user.profile.lastname == null) ? 'empty last name' : this.order.selectedOrder.user_orders.user.profile.lastname}</p>
                                </div>
                                <div className="listCustDetailItem flex">
                                  <span className="listCustomerDetailItemKey">Email</span>
                                  <p
                                    className="listCustomerDetailItemValue" style={{display:'flex',flexWrap: 'wrap'}}>{this.order.selectedOrder.user_orders.user.email}</p>
                                </div>
                                <div className="listCustDetailItem flex">
                                  <p className="listCustomerDetailItemKey">Phone</p>
                                  <p
                                    className="listCustomerDetailItemValue">{(this.order.selectedOrder.user_orders.user.profile.phone == null) ? 'empty phone number' : this.order.selectedOrder.user_orders.user.profile.phone}</p>
                                </div>
                                <div className="listCustDetailItem flex">
                                  <p className="listCustomerDetailItemKey">Gender</p>
                                  <p className="listCustomerDetailItemValue">{(this.order.selectedOrder.user_orders.user.profile.gender == null) ? 'empty gender' : this.order.selectedOrder.user_orders.user.profile.gender }</p>
                                </div>

                              </div>

                            </div>


                            <div className="col s12 m12 l6">

                              <div className="listCustDetail">
                                <div className="listCustDetailItem flex">
                                  <p className="listCustomerDetailItemKey">Receiver's Name</p>
                                  <p
                                    className="listCustomerDetailItemValue">{this.order.selectedOrder.user_address_buyer.receiver_name}</p>
                                </div>
                                <div className="listCustDetailItem flex">
                                  <p className="listCustomerDetailItemKey">Name of Address</p>
                                  <p
                                    className="listCustomerDetailItemValue">{this.order.selectedOrder.user_address_buyer.name}</p>
                                </div>
                                <div className="listCustDetailItem flex">
                                  <p className="listCustomerDetailItemKey">Phone of Address</p>
                                  <p
                                    className="listCustomerDetailItemValue">{this.order.selectedOrder.user_address_buyer.phone_number}</p>
                                </div>
                                <div className="listCustDetailItem flex">
                                  <p className="listCustomerDetailItemKey">City</p>
                                  <p
                                    className="listCustomerDetailItemValue">{this.order.selectedOrder.user_address_buyer.city.name}</p>
                                </div>
                                <div className="listCustDetailItem flex">
                                  <p className="listCustomerDetailItemKey">Province</p>
                                  <p
                                    className="listCustomerDetailItemValue">{this.order.selectedOrder.user_address_buyer.province.name}</p>
                                </div>
                                <div className="listCustDetailItem flex">
                                  <p className="listCustomerDetailItemKey">Address</p>
                                  <p
                                    className="listCustomerDetailItemValue">{this.order.selectedOrder.user_address_buyer.address}</p>
                                </div>
                              </div>


                            </div>

                          </div>
                        </div>
                      </CardText>


                      <div className={' no-hover'} style={{marginTop: 18, marginBottom: 15}}>
                        <Table selectable={false} className="TableOrder">
                          <TableHeader displaySelectAll={false}
                                       adjustForCheckbox={false}
                                       enableSelectAll={false}>
                            <TableRow style={{height: 38, background: '#f6f9fc'}}>

                              <TableHeaderColumn className="TableHeaderColumnAkun"
                                                 style={{height: 'auto'}}>Items</TableHeaderColumn>
                              <TableHeaderColumn className="TableHeaderColumnAkun"
                                                 style={{height: 'auto'}}>Quantity Request</TableHeaderColumn>

                              <TableHeaderColumn className="TableHeaderColumnAkun align-center"
                                                 style={{height: 'auto'}}>Quantity</TableHeaderColumn>
                              <TableHeaderColumn className="TableHeaderColumnAkun align-right"
                                                 style={{height: 'auto'}}>Price</TableHeaderColumn>
                              <TableHeaderColumn className="TableHeaderColumnAkun"
                                                 style={{height: 'auto'}}>Subtotal</TableHeaderColumn>
                            </TableRow>
                          </TableHeader>
                          <TableBody displayRowCheckbox={false}>
                            {
                              (this.order.selectedOrder.user_order_items) ?
                                this.order.selectedOrder.user_order_items.map((data, index) => (
                                  <TableRow>
                                    <TableRowColumn style={{whiteSpace : 'normal !important'}} key={data.id}>
                                      {data.item.name}
                                      <p style={{margin: '2px 0', fontSize: 10,}}>
                                        Detail: <Link className={'viewDetailLink'}
                                                      style={{fontWeight: 'bold', textDecoration: 'underline'}}
                                                      to={`${LINKS.FORM_ITEMS}/edit/${data.item.id}`} target="_blank">View details</Link>
                                      </p>
                                    </TableRowColumn>
                                    {data.is_preorder ?
                                      <TableRowColumn key={data.id}>
                                        {data.preorder_store_note ?
                                          <p style={{margin: 0}}>{(data.preorder_buyer_note)} <span style={{
                                            fontSize: '.72rem',
                                            color: '#71c21a',
                                            fontWeight: 'bold'

                                          }} className={'smaller lighter'}>Responded</span></p> :
                                          <p style={{margin: 0}}>{data.preorder_buyer_note}gr <span style={{
                                            fontSize: '.72rem',
                                            color: 'red',
                                            fontWeight: 'bold'
                                          }} className={'smaller lighter'}>Need Response</span>
                                          </p>}
                                        {data.preorder_buyer_note ?
                                          <div>
                                            <p style={{margin: '2px 0', fontSize: 10}}>
                                              Detail: <a className={'viewDetailLink'} style={{
                                              cursor: 'pointer',
                                              fontWeight: 'bold',
                                              textDecoration: 'underline'
                                            }}
                                                         onClick={() => this.openPreorderDialog(data)}>View notes</a>
                                            </p></div> : <div>-</div>}</TableRowColumn>
                                      :
                                      <TableRowColumn key={data.id}>-</TableRowColumn>
                                    }

                                    <TableRowColumn key={data.id}
                                                    className={'align-center'}>{data.quantity !== 0 ? data.quantity + "pcs" :
                                      <NumberFormat value={data.preorder_weight} displayType={'text'}
                                                    suffix={'gr'}/>}</TableRowColumn>
                                    <TableRowColumn className="align-right"><NumberFormat value={data.price}
                                                                                          displayType={'text'}
                                                                                          thousandSeparator={true}
                                                                                          prefix={'Rp '}/></TableRowColumn>
                                    <TableRowColumn><NumberFormat value={data.subtotal} displayType={'text'}
                                                                  thousandSeparator={true} prefix={'Rp '}/></TableRowColumn>
                                  </TableRow>
                                )) : <EmptyComponent type="empty" header="" content="There is no data in sight"/>
                            }

                            <TableRow displayBorder={false} className="TableRowCondensed TableRowCondensedFirst">
                              <TableRowColumn colSpan={3} className="TableRowColumnCondensed TableRowColumnCondensedFirst"/>
                              <TableRowColumn
                                className="align-right font-500 TableRowColumnCondensed TableRowColumnCondensedFirst">Subtotal</TableRowColumn>
                              <TableRowColumn className="TableRowColumnCondensed TableRowColumnCondensedFirst"><NumberFormat
                                value={this.order.selectedOrder.subtotal} displayType={'text'} thousandSeparator={true}
                                prefix={'Rp '}/></TableRowColumn>
                            </TableRow>
                            <TableRow displayBorder={false} className="TableRowCondensed">
                              <TableRowColumn colSpan={3} className="TableRowColumnCondensed"/>
                              <TableRowColumn className="align-right font-500 TableRowColumnCondensed">Discount</TableRowColumn>
                              <TableRowColumn className="TableRowColumnCondensed"><NumberFormat value={0.00}
                                                                                                displayType={'text'}
                                                                                                thousandSeparator={true}
                                                                                                prefix={'Rp '}/></TableRowColumn>
                            </TableRow>
                            <TableRow displayBorder={false} className="TableRowCondensed">
                              <TableRowColumn colSpan={3} className="TableRowColumnCondensed"/>
                              <TableRowColumn className="align-right font-500 TableRowColumnCondensed">Shipping
                                Fee</TableRowColumn>
                              <TableRowColumn className="TableRowColumnCondensed"><NumberFormat
                                value={this.order.selectedOrder.shipping_price} displayType={'text'} thousandSeparator={true}
                                prefix={'Rp '}/></TableRowColumn>
                            </TableRow>
                            <TableRow displayBorder={false} className="TableRowCondensed">
                              <TableRowColumn colSpan={3} className="TableRowColumnCondensed"/>
                              <TableRowColumn className="align-right font-500 TableRowColumnCondensed">Total</TableRowColumn>
                              <TableRowColumn className="TableRowColumnCondensed "><NumberFormat
                                value={(+this.order.selectedOrder.shipping_price) + (+this.order.selectedOrder.subtotal)}
                                displayType={'text'} thousandSeparator={true} prefix={'Rp '}/>.00</TableRowColumn>
                            </TableRow>
                          </TableBody>
                        </Table>
                      </div>
                    </Card>
                  </Print>


                <Card className="cardLite cardDashboard" style={{marginBottom: 20}}>
                  <CardHeader
                    title={
                      <Toolbar className="toolbarCard" style={{backgroundColor: '#fff'}}>
                        <ToolbarGroup>
                          <CardHeader
                            title="Send Service Information"
                            subtitle="Tracking shipping information"
                            avatar={<Icon type="car" style={{fontSize: 25, color: '#555'}}/>}
                            style={{marginLeft: -25}}
                          />
                        </ToolbarGroup>
                      </Toolbar>
                    }
                    actAsExpander={true}
                    showExpandableButton={true}
                  />
                  <Divider/>

                  <CardText className="" expandable={true}>
                    <div className="">
                      <div className="header-text-mini" style={{fontSize: '1.23em', marginBottom: '20px'}}>{this.order.selectedOrder.shipping_method.name} <a>{this.order.selectedOrder.courier_booking_id}</a>
                      </div>
                      {console.log(get(this.order.selectedOrder,'response_courier', 'kosong'), "get(this.order.selectedOrder,'response_courier', 'kosong') get(this.order.selectedOrder,'response_courier', 'kosong')")}
                      {!!get(this.order.selectedOrder,'response_courier.total_distance_in_kms',false) &&
                        <Card style={{marginBottom : '20px',padding:'20px'}}>
                          {/*{get(this.order.selectedOrder,'response_courier.driver_name',false) && <CardHeader*/}
                            {/*title={`${this.order.selectedOrder.response_courier.driver_name} - Driver`}*/}
                            {/*subtitle={this.order.selectedOrder.response_courier.driver_phone}*/}
                            {/*avatar={this.order.selectedOrder.response_courier.driver_photo_url}*/}
                          {/*/>}*/}
                          <CardHeader
                            title={'Courier Information'}
                          />
                          <div style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-around', marginTop: 15}}>
                            <div>
                              <Avatar
                                src={this.order.selectedOrder.response_courier.driver_photo_url}
                                size={120}
                              />
                            </div>
                            <div>
                              <ListItem
                                disabled={true}
                                leftAvatar={
                                  <Avatar backgroundColor={'#6772e5'} icon={<Icon type="user" />} />
                                }
                                style={{}}
                              >
                                {get(this.order, 'selectedOrder.response_courier.driver_name', 'John Doe')}
                              </ListItem>
                              <ListItem
                                disabled={true}
                                leftAvatar={
                                  <Avatar backgroundColor={'#6772e5'} icon={<Icon type="phone" />} />
                                }
                                style={{}}
                              >
                                {get(this.order, 'selectedOrder.response_courier.driver_phone', '08888xxxxx')}
                              </ListItem>
                              <ListItem
                                disabled={true}
                                leftAvatar={
                                  <Avatar backgroundColor={'#6772e5'} icon={<Icon type="environment-o" />} />
                                }
                                style={{}}
                              >
                                <a href={get(this.order, 'selectedOrder.response_courier.live_tracking_url', '#')} target="_blank">{get(this.order, 'selectedOrder.response_courier.live_tracking_url', 'No URL')}</a>
                              </ListItem>
                            </div>
                            <div style={{
                              width: 1,
                              height: 160,
                              backgroundColor: '#ccc'
                            }}></div>
                            <div>
                              <p style={{textAlign: 'center', fontSize: 20}}>Price ({get(this.order, 'selectedOrder.response_courier.total_distance_in_kms', 0).toFixed(2)} KM)</p>
                              <p style={{textAlign: 'center', color: '#6772e5', fontSize: 25}}><NumberFormat value={get(this.order, 'selectedOrder.response_courier.price', 0)} displayType={'text'} thousandSeparator={true} prefix={'Rp '}/></p>
                            </div>
                          </div>
                          {/*<div className="title">Price : <NumberFormat value={this.order.selectedOrder.response_courier.price} displayType={'text'} thousandSeparator={true} prefix={'Rp '}/></div>   */}
                          {/*<div className="title">Total Distance : {this.order.selectedOrder.response_courier.total_distance_in_kms.toFixed(2)} KM</div>   */}
                          {/*<div className="title">Driver : {get(this.order.selectedOrder,'response_courier.driver_name','-')}</div>   */}
                          {/*<div className="title">No. Handphone : {get(this.order.selectedOrder,'response_courier.driver_phone','-')}</div>   */}
                        </Card>
                      }
                      <div className="itenaryBody" style={{marginLeft: -20}}>
                        {this._renderShipmentTracking(this.order.selectedOrder.tracking)}
                      </div>
                    </div>
                  </CardText>
                </Card>
              </div>

              <div className="col s12 m3 l3" style={{marginBottom: 0}}>
                <section className='row element-wrapper'>

                  <Card className="cardLite cardDashboard padding">
                    {/*<Affix style={{position: 'sticky', top: 1}} offsetTop={80}/>*/}
                    <div className='element-header'>
                      <h3>Activities</h3>
                    </div>
                    {this.order.selectedOrder.histories.length > 0 ?
                      uniqBy(this.order.selectedOrder.histories,'order_status_id').map(it=>(
                        <div className="timed-activities compact">
                          <div className="timed-activity">
                            <div className="ta-date">
                              <span>{moment(it.created_at).format("DD MMMM YYYY")}</span></div>
                            <div className="ta-record-w">
                              <div className="ta-record">
                                <div className="ta-timestamp"><Icon className="ta-timestamp-icon"
                                                                    type="right"/><strong>{moment(it.created_at).format("HH:mm:ss")}</strong>
                                </div>
                                <div className="ta-activity">
                                  {this.orderHistoryText(it)}
                                </div>
                              </div>
                              {/*<div className="ta-record">*/}
                                {/*<div className="ta-timestamp"><strong>2:34</strong> pm</div>*/}
                                {/*<div className="ta-activity">Commented on story <a*/}
                                  {/*href="users_profile_small.html#">How to be a leader</a> in*/}
                                  {/*<a href="users_profile_small.html#">Financial</a> category*/}
                                {/*</div>*/}
                              {/*</div>*/}
                              {/*<div className="ta-record">*/}
                                {/*<div className="ta-timestamp"><strong>7:12</strong> pm</div>*/}
                                {/*<div className="ta-activity">Added <a href="users_profile_small.html#">John*/}
                                  {/*Silver</a> as a friend*/}
                                {/*</div>*/}
                              {/*</div>*/}
                            </div>
                          </div>
                        </div>
                      ))  :

                      <div className="timed-activities compact">
                          <div className="timed-activity">
                            <div className="ta-date">
                              <span>{moment(this.order.selectedOrder.created_at).format("DD MMMM YYYY")}</span></div>
                            <div className="ta-record-w">
                              <div className="ta-record">
                                <div className="ta-timestamp"><Icon className="ta-timestamp-icon"
                                                                    type="right"/><strong>{moment(this.order.selectedOrder.created_at).format("HH:mm:ss")}</strong>
                                </div>
                                <div className="ta-activity">
                                {this.orderHistoryText({status:this.order.selectedOrder.order_status,order_status_id:this.order.selectedOrder.order_status_id})}
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                    }
                  </Card>

                </section>

              </div>

            </div>


            <Dialog
              style={
                {
                  margin: 'auto'
                }
              }
              open={this.globalUI.loadingVisibility
              }>
              <div
                style={
                  {
                    textAlign: 'center'
                  }
                }>
                <LoadingDialog/>
              </div>
            </Dialog>

            <Dialog
              title="Error"
              style={{margin: 'auto'}}
              actions={[<FlatButton primary={false} label="Ok" onClick={this.closeError}/>]}
              open={this.state.errorBook}>
              {this.state.errorMessage}
            </Dialog>
          </div>
        </NoPrint>
      </PrintProvider>
    )
  }
}

