import '@things-factory/barcode-ui'
import '@things-factory/grist-ui'
import './logistics-init/logistics-init-popup'

import gql from 'graphql-tag'
import { css, html } from 'lit-element'

import { MultiColumnFormStyles } from '@things-factory/form-ui'
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 { CommonButtonStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

import { MARKETPLACE_STATUS, WORKSHEET_STATUS } from '../constants'

class WorksheetPacking extends localize(i18next)(PageView) {
  static get properties() {
    return {
      _worksheetStatus: String,
      _marketplaceStatus: String,
      _trackingNo: String,
      _roNo: String,
      orderInformation: Object,
      wsdGristConfig: Object,
      worksheetDetailData: Object,
      _logisticsInitiated: Boolean,
      _isManifested: Boolean
    }
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow-x: auto;
        }
        .form-container {
          display: flex;
        }
        .form-container > form {
          flex: 1;
        }
        barcode-tag {
          width: 100px;
          height: 100px;
          margin: 10px;
        }
        .grist {
          background-color: var(--main-section-background-color);
          display: flex;
          flex-direction: row;
          flex: 1;
          overflow-y: auto;
        }
        .grist-column {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: auto;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        h2 {
          padding: var(--subtitle-padding);
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
          border-bottom: var(--subtitle-border-bottom);
        }
        .grist h2 {
          margin: var(--grist-title-margin);
          border: var(--grist-title-border);
          font: var(--grist-title-font);
          color: var(--secondary-color);
        }

        .grist h2 mwc-icon {
          vertical-align: middle;
          margin: var(--grist-title-icon-margin);
          font-size: var(--grist-title-icon-size);
          color: var(--grist-title-icon-color);
        }

        h2 + data-grist {
          padding-top: var(--grist-title-with-grid-padding);
        }
      `
    ]
  }

  constructor() {
    super()
    this.worksheetDetailData = { records: [] }
    this._logisticsInitiated = false
  }

  get context() {
    var actions = [
      {
        title: i18next.t('button.back'),
        action: () => history.back(),
        ...CommonButtonStyles.back
      }
    ]

    if (this._worksheetStatus === WORKSHEET_STATUS.DEACTIVATED.value) {
      actions.push({
        title: i18next.t('button.activate'),
        action: this._activateWorksheet.bind(this),
        ...CommonButtonStyles.activate
      })

      if (
        this._marketplaceStatus === MARKETPLACE_STATUS.READY_TO_SHIP.value &&
        !this._trackingNo &&
        !this._logisticsInitiated
      ) {
        actions.push({
          title: i18next.t('button.init_logistics'),
          action: this._initLogistics.bind(this),
          ...CommonButtonStyles.logistics
        })
      }

      if (!this._trackingNo) {
        actions.push({
          title: i18next.t('button.get_tracking_no'),
          action: this._syncMarketplaceOrder.bind(this),
          ...CommonButtonStyles.sync
        })
      }
    }

    return {
      title: i18next.t('title.worksheet_packing'),
      actions,
      printable: {
        accept: ['preview'],
        content: this
      },
      help: 'operato-wms/outbound/worksheet-packing'
    }
  }

  render() {
    return html`
      <div class="form-container">
        <form class="multi-column-form">
          <fieldset>
            <legend>${i18next.t('title.packing')}</legend>
            <label>${i18next.t('label.release_good_no')}</label>
            <input name="releaseGood" readonly />

            <label>${i18next.t('label.company')}</label>
            <input name="bizplace" readonly />

            <label>${i18next.t('label.release_date')}</label>
            <input name="releaseDate" type="date" readonly />

            <label>${i18next.t('label.ref_no')}</label>
            <input name="refNo" readonly />

            <label>${i18next.t('label.ref_no_2')}</label>
            <input name="refNo2" readonly />

            <label>${i18next.t('label.ref_no_3')}</label>
            <input name="refNo3" readonly />

            <label>${i18next.t('label.transporter')}</label>
            <input name="shippingProvider" readonly />

            <label>${i18next.t('label.tracking_no')}</label>
            <input name="trackingNo" readonly />

            <label>${i18next.t('label.order_remark')}</label>
            <textarea name="remark" rows="5" readonly></textarea>

            <label>${i18next.t('label.status')}</label>
            <select name="status" disabled>
              ${Object.keys(WORKSHEET_STATUS).map(
                key => html`<option value="${WORKSHEET_STATUS[key].value}">${WORKSHEET_STATUS[key].name}</option>`
              )}
            </select>

            <input id="manifested" type="checkbox" name="manifested" ?checked="${this._isManifested}" disabled />
            <label for="manifested">${i18next.t('label.manifested')}</label>
          </fieldset>
        </form>

        <barcode-tag bcid="qrcode" .value=${this._roNo} showLogo="true"></barcode-tag>
      </div>

      <div class="grist">
        <div class="grist-column">
          <h2><mwc-icon>list_alt</mwc-icon>${i18next.t('title.worksheet_detail')}</h2>
          <data-grist
            id="wsd-grist"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.wsdGristConfig}
            .data="${this.worksheetDetailData}"
          ></data-grist>
        </div>
      </div>
    `
  }

  async pageUpdated(changes) {
    if (this.active && (changes.resourceId || this._worksheetNo)) {
      if (changes.resourceId) {
        this._worksheetNo = changes.resourceId
      }
      await this.fetchWorksheet()
      this.updateContext()
      this._updateGristConfig()
    }
  }

  pageInitialized() {
    this.preWsdGristConfig = {
      list: {
        fields: [
          'batchId',
          'sku',
          'product',
          'packingType',
          'location',
          'releaseQty',
          'releaseUomValueWithUom',
          'status'
        ]
      },
      pagination: { infinite: true },
      rows: { appendable: false },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_id'),
          width: 100
        },
        {
          type: 'string',
          name: 'sku',
          header: i18next.t('field.sku'),
          width: 150
        },
        {
          type: 'object',
          name: 'product',
          header: i18next.t('field.product'),
          width: 250
        },
        {
          type: 'string',
          name: 'brand',
          header: i18next.t('field.brand'),
          width: 150
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          width: 150
        },
        {
          type: 'object',
          name: 'location',
          header: i18next.t('field.location'),
          width: 120
        },
        {
          type: 'float',
          name: 'releaseQty',
          header: i18next.t('field.release_qty'),
          width: 60
        },
        {
          type: 'string',
          name: 'releaseUomValueWithUom',
          header: i18next.t('field.release_uom_value'),
          width: 60
        },
        {
          type: 'string',
          name: 'batchIdRef',
          header: i18next.t('field.batch_no_ref'),
          width: 100
        }
      ]
    }
  }

  get form() {
    return this.shadowRoot.querySelector('form')
  }

  get wsdGrist() {
    return this.shadowRoot.querySelector('data-grist#wsd-grist')
  }

  async fetchWorksheet() {
    if (!this._worksheetNo) return
    const response = await client.query({
      query: gql`
        query worksheet($name: String!) {
          worksheet(name: $name) {
            status
            releaseGood {
              name
              description
              transporter
              trackingNo
              refNo
              refNo2
              refNo3
              ownTransport
              releaseDate
              remark
              orderPackages {
                manifestedAt
              }
            }
            marketplaceOrder {
              name
              orderNo
              marketplaceStore {
                id
                platform
              }
              shippingProvider
              trackingNo
              status
            }
            orderInventories {
              status
              batchId
              batchIdRef
              product {
                id
                name
                description
              }
              packingType
              releaseQty
              releaseUomValue
              inventory {
                qty
                lockedQty
                palletId
                uom
                location {
                  name
                  description
                }
              }
            }
            bizplace {
              id
              name
              description
            }
            worksheetDetails {
              status
              targetInventory {
                batchId
                batchIdRef
                product {
                  id
                  name
                  sku
                  brand
                  description
                }
                packingType
                releaseQty
                releaseUomValue
                status
                inventory {
                  uom
                  product {
                    name
                    sku
                    description
                  }
                  location {
                    id
                    name
                    description
                  }
                }
              }
            }
          }
        }
      `,
      variables: {
        name: this._worksheetNo
      }
    })

    if (!response.errors) {
      const worksheet = response.data.worksheet
      const worksheetDetails = worksheet.worksheetDetails
      this.orderInformation = worksheet.marketplaceOrder
      this._worksheetStatus = worksheet.status
      this._marketplaceStatus = worksheet.marketplaceOrder?.status
      this._trackingNo = worksheet.marketplaceOrder?.trackingNo
      this._refNo = worksheet?.releaseGood?.refNo
      this._roNo = worksheet?.releaseGood?.name || ''
      this._isManifested = !worksheet?.releaseGood?.orderPackages.find(itm => itm.manifestedAt == null)

      this._fillupForm({
        ...worksheet,
        releaseGood: worksheet.releaseGood.name,
        bizplace: worksheet.bizplace.name,
        refNo: worksheet.releaseGood.refNo,
        refNo2: worksheet.releaseGood.refNo2,
        refNo3: worksheet.releaseGood.refNo3,
        ownCollection: worksheet.releaseGood.ownTransport,
        releaseDate: worksheet.releaseGood.releaseDate,
        shippingProvider: worksheet.releaseGood?.transporter
          ? worksheet.releaseGood.transporter == 'EMS'
            ? 'EFMX'
            : worksheet.releaseGood.transporter
          : '',
        trackingNo: worksheet.releaseGood?.trackingNo || '',
        remark: worksheet.releaseGood.remark || ''
      })

      this.worksheetDetailData = {
        records: worksheetDetails.map(worksheetDetail => {
          return {
            ...worksheetDetail.targetInventory.inventory,
            name: worksheetDetail.name,
            batchId: worksheetDetail.targetInventory.batchId,
            batchIdRef: worksheetDetail.targetInventory.batchIdRef,
            sku: worksheetDetail.targetInventory.product.sku,
            brand: worksheetDetail.targetInventory.product.brand,
            status: worksheetDetail.status,
            releaseQty: worksheetDetail.targetInventory.releaseQty,
            releaseUomValueWithUom:
              Math.round(worksheetDetail.targetInventory.releaseUomValue).toFixed(2) +
              ' ' +
              worksheetDetail.targetInventory.inventory.uom,
            packingType: worksheetDetail.targetInventory.packingType,
            location: worksheetDetail.targetInventory.inventory.location
          }
        })
      }
    }
  }

  _updateGristConfig() {
    const statusColumnConfig = {
      type: 'string',
      name: 'status',
      header: i18next.t('field.status'),
      width: 100
    }

    if (
      !this.preWsdGristConfig.columns.some(e => e.name === 'status') &&
      this._worksheetStatus !== WORKSHEET_STATUS.DEACTIVATED.value
    ) {
      this.preWsdGristConfig.columns = [...this.preWsdGristConfig.columns, statusColumnConfig]
    } else if (
      this.preWsdGristConfig.columns.some(e => e.name === 'status') &&
      this._worksheetStatus === WORKSHEET_STATUS.DEACTIVATED.value
    ) {
      this.preWsdGristConfig.columns.splice(this.preWsdGristConfig.columns.map(e => e.name).indexOf('status'))
    }

    this.wsdGristConfig = { ...this.preWsdGristConfig }
  }

  _fillupForm(data) {
    for (let key in data) {
      Array.from(this.form.querySelectorAll('input, select, textarea')).forEach(field => {
        if (field.name === key && field.type === 'checkbox') {
          field.checked = data[key]
        } else if (field.name === key) {
          if (data[key] instanceof Object) {
            const objectData = data[key]
            field.value = `${objectData.name} ${objectData.description ? `(${objectData.description})` : ''}`
          } else {
            field.value = data[key]
          }
        }
      })
    }
  }

  async _activateWorksheet() {
    try {
      const result = await CustomAlert({
        title: i18next.t('title.are_you_sure'),
        text: i18next.t('text.activate_packing_worksheet'),
        confirmButton: { text: i18next.t('button.confirm') },
        cancelButton: { text: i18next.t('button.cancel') }
      })

      if (!result.value) {
        return
      }

      const response = await client.mutate({
        mutation: gql`
          mutation activatePacking($worksheetNo: [String!]!) {
            activatePacking(worksheetNo: $worksheetNo) {
              name
            }
          }
        `,
        variables: {
          worksheetNo: this._worksheetNo
        }
      })
      if (!response.errors) {
        this._showToast({ message: i18next.t('text.worksheet_activated') })
        await this.fetchWorksheet()
        this.updateContext()
        navigate(`packing_worksheet_list`)
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  _initLogistics() {
    openPopup(
      html`
        <logistics-init-popup
          .orderInformation="${this.orderInformation}"
          @order-initialised="${() => {
            setTimeout(() => {
              this._syncMarketplaceOrder()
            }, 5000)
            this._logisticsInitiated = true
          }}"
        ></logistics-init-popup>
      `,
      {
        backdrop: true,
        escapable: false,
        size: 'medium',
        title: i18next.t('title.initialise_logistics')
      }
    )
  }

  async _syncMarketplaceOrder() {
    var now = Date.now()

    var fromDateTimeLocal = new Date(now - 24 * 60 * 60 * 1000).toISOString()
    var toDateTimeLocal = new Date(now).toISOString()

    CustomAlert({
      title: i18next.t('title.fetch_tracking_no'),
      text: i18next.t('text.please_wait'),
      allowOutsideClick: false,
      allowEscapeKey: true
    })

    const response = await client.mutate({
      mutation: gql`
        mutation syncMarketplaceOrder($storeId: String!, $fromDate: String!, $toDate: String!) {
          syncMarketplaceOrder(storeId: $storeId, fromDate: $fromDate, toDate: $toDate)
        }
      `,
      variables: {
        storeId: this.orderInformation.marketplaceStore.id,
        fromDate: fromDateTimeLocal,
        toDate: toDateTimeLocal
      }
    })

    if (!response.errors) {
      await CustomAlert({
        title: i18next.t('title.completed'),
        text: i18next.t('text.successfully_retrieve_tracking_no'),
        confirmButton: { text: i18next.t('button.confirm') }
      })

      await this.fetchWorksheet()
      this.updateContext()
      this._showToast({ message: i18next.t('text.logistics_has_been_initialised') })
    }
  }

  _getPackingWorksheetDetails() {
    return this.wsdGrist.dirtyData.records.map(worksheetDetail => {
      return {
        name: worksheetDetail.name,
        description: worksheetDetail.description
      }
    })
  }

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

window.customElements.define('worksheet-packing', WorksheetPacking)
