import { i18next, localize } from '@things-factory/i18n-base'
import { openPopup } from '@things-factory/layout-base'
import { client, CustomAlert, navigate, PageView } from '@things-factory/shell'
import { ScrollbarStyles, CommonButtonStyles } from '@things-factory/styles'
import gql from 'graphql-tag'
import { css, html } from 'lit-element'
import '../../components/popup-note'
import { ORDER_STATUS } from '../../constants'
import './delivery-note-popup'

class ViewDeliveryOrder extends localize(i18next)(PageView) {
  static get properties() {
    return {
      _doNo: String,
      _driverName: String,
      _ownCollection: Boolean,
      _truckNo: String,
      _status: String,
      _date: Date,
      _recipient: String,
      _proceedFlag: Boolean,
      _customerContactPoints: Array,
      _bizplace: Object,
      _orderInfo: Object,
      _isManualDo: Boolean
    }
  }

  constructor() {
    super()
    this._date = ''
    this._status = ''
  }

  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          padding: 0;
        }

        #container {
          flex: 1;
          padding: 0;
          margin: 0;
          border: 0;
        }
      `
    ]
  }

  get context() {
    var actions = [
      {
        title: i18next.t('button.back'),
        action: () => navigate(`delivery_orders`),
        ...CommonButtonStyles.back
      },
      {
        title: i18next.t('button.print'),
        action: () => {
          this.renderRoot.querySelector('iframe').contentWindow.print()
        },
        ...CommonButtonStyles.print
      }
    ]
    if (this._status === ORDER_STATUS.READY_TO_DISPATCH.value || this._status === ORDER_STATUS.DELIVERING.value) {
      actions.push({
        title: i18next.t('button.edit'),
        action: this._editDeliveryNote.bind(this),
        ...CommonButtonStyles.edit
      })
    }

    if (this._status === ORDER_STATUS.DELIVERING.value) {
      actions.push({
        title: i18next.t('button.complete'),
        action: this._checkDeliveredOrder.bind(this),
        ...CommonButtonStyles.save
      })
    }

    return {
      title: i18next.t('title.goods_delivery_note_details'),
      actions
    }
  }

  render() {
    return html` <iframe id="container"></iframe> `
  }

  get _doDocument() {
    return this.shadowRoot.querySelector('#container')
  }

  async pageUpdated(changes) {
    if (this.active) {
      if (changes.resourceId) {
        this._doNo = changes.resourceId
      }

      if (this._doNo) {
        await this._fetchDeliveryOrder(this._doNo)
      }

      this.updateContext()
    }
  }

  async _fetchDeliveryOrder(name) {
    const response = await client.query({
      query: gql`
        query deliveryOrderByWorksheet($name: String!) {
          deliveryOrderByWorksheet(name: $name) {
            deliveryOrderInfo {
              contactName
              createdDate
              deliverTo
              deliveryDate
              doStatus
              driverName
              driverCode
              otherDestination
              otherDriver
              otherDriverCode
              ownCollection
              isManualDo
              remark
              reusablePallet
              truckNo
              bizplace {
                id
                name
              }
            }
            contactPointInfo {
              id
              contactName
              address
              phone
              fax
              email
            }
          }
        }
      `,
      variables: {
        name
      }
    })

    if (!response.errors) {
      const deliveryOrderData = response.data.deliveryOrderByWorksheet

      //var { domain } = getPathInfo(location.pathname) // find out better way later.
      this._doDocument.src = `/view_document_manual_do/${this._doNo}`

      let orderInfo = deliveryOrderData.deliveryOrderInfo
      let contactPoints = deliveryOrderData.contactPointInfo
      this._status = orderInfo.doStatus
      this._ownCollection = orderInfo.ownCollection
      this._truckNo = orderInfo.truckNo
      this._bizplace = orderInfo.bizplace
      this._isManualDo = orderInfo.isManualDo

      let deliverTo = orderInfo.deliverTo
      if (deliverTo !== '') {
        const deliveryContactPoint = contactPoints.filter(contactPoint => contactPoint.id === deliverTo)[0]
        orderInfo = {
          ...orderInfo,
          deliverTo: deliveryContactPoint
        }
      }

      this._orderInfo = orderInfo
    }
  }

  async _checkDeliveredOrder() {
    const popup = openPopup(
      html`
        <popup-note
          .title="${i18next.t('title.remark')}"
          @submit="${async e => {
            try {
              const result = await CustomAlert({
                title: i18next.t('title.are_you_sure'),
                text: i18next.t('text.completed_delivery_order'),
                confirmButton: { text: i18next.t('button.confirm') },
                cancelButton: { text: i18next.t('button.cancel') }
              })

              if (!result.value) {
                return
              }

              const response = await client.mutate({
                mutation: gql`
                  mutation checkDeliveredOrder($name: String!, $patch: DeliveryOrderPatch) {
                    checkDeliveredOrder(name: $name, patch: $patch) {
                      name
                    }
                  }
                `,
                variables: {
                  name: this._doNo,
                  patch: { remark: e.detail.value }
                }
              })

              if (!response.errors) {
                navigate('delivery_orders')
                this._showToast({ message: i18next.t('text.delivery_order_completed') })
              }
            } catch (e) {
              this._showToast(e)
            }
          }}"
        ></popup-note>
      `,
      {
        backdrop: true,
        size: 'medium',
        title: i18next.t('title.completed_delivery_order')
      }
    )
  }

  _editDeliveryNote() {
    openPopup(
      html`
        <delivery-note-popup
          .doNo="${this._doNo}"
          .bizplace="${this._bizplace}"
          .orderInfo="${this._orderInfo}"
          .status="${this._status}"
          .manualDo="${this._isManualDo}"
          @delivery-dispatched="${() => {
            this.pageReset()
          }}"
        ></delivery-note-popup>
      `,
      {
        backdrop: true,
        size: 'large',
        title: i18next.t('title.edit_delivery_note')
      }
    )
  }

  _showToast({ type, message }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message
        }
      })
    )
  }
}

window.customElements.define('view-delivery-note', ViewDeliveryOrder)
