import '../../vas/reverse-kitting/popup-reverse-kitting-template'
import '../../components/popup-note'

import gql from 'graphql-tag'
import { css, html, LitElement } 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 } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'

class PopupCombinationSets extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      orderNo: String,
      data: Object,
      productCombinationSetsConfig: Object,
      productCombinationSets: Object
    }
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow-x: overlay;
          background-color: var(--main-section-background-color);
        }
        .container {
          display: flex;
          flex-direction: column;
          flex: 1;
        }
        .container > textarea {
          flex: 1;
          resize: none;
          border-color: var(--primary-color);
          padding: 5px;
          margin: 10px;
          outline: none;
        }
        h2 {
          padding: var(--subtitle-padding);
          font: var(--grist-title-font);
          margin: var(--grist-title-margin);
          border: var(--grist-title-border);
          color: var(--secondary-color);
        }
        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);
        }
        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        .button-container {
          padding: 10px 0 12px 0;
          text-align: center;
        }
      `
    ]
  }

  firstUpdated() {
    this.productCombinationSetsConfig = {
      pagination: { infinite: true },
      list: { fields: ['completed', 'productSku', 'qty', 'actualQty'] },
      rows: {
        appendable: false,
        handlers: {
          click: (columns, data, column, record, rowIndex) => {
            this._openPopupReverseKittingTemplate(record)
          }
        }
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'boolean',
          name: 'completed',
          header: i18next.t('field.completed'),
          label: true,
          width: 40
        },
        {
          type: 'string',
          name: 'productSku',
          header: i18next.t('field.sku'),
          label: true,
          width: 150
        },
        {
          type: 'integer',
          name: 'qty',
          header: i18next.t('field.qty'),
          record: { editable: true },
          label: true,
          width: 60
        },
        {
          type: 'integer',
          name: 'actualQty',
          header: i18next.t('field.actual_qty'),
          label: true,
          width: 60
        }
      ]
    }

    this.getProductCombination()
  }

  render() {
    return html`
      <form class="multi-column-form" id="combination-form">
        <legend>${`${i18next.t('title.combination_sets')}`}</legend>
      </form>

      ${this.productCombinationSets?.records?.length
        ? html`<div class="grist">
            <data-grist
              id="combination-grist"
              .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
              .config=${this.productCombinationSetsConfig}
              .data=${this.productCombinationSets}
            ></data-grist>
          </div>`
        : ''}
      ${this.data
        ? html`<div class="button-container">
            <mwc-button
              raised
              @click=${this._openIssueNote.bind(this)}
              label="${i18next.t('button.issue')}"
            ></mwc-button>
            <mwc-button raised @click=${this._closePopup.bind(this)} label="${i18next.t('button.back')}"></mwc-button>
          </div>`
        : html`<div class="button-container">
            <mwc-button raised @click=${this._closePopup.bind(this)} label="${i18next.t('button.back')}"></mwc-button>
          </div>`}
    `
  }

  async fetchReverseKittingOrder() {
    if (!this.orderNo) return
    const response = await client.mutate({
      mutation: gql`
        mutation executingReverseKittingOrder($name: String!) {
          executingReverseKittingOrder(name: $name) {
            id
            name
            status
            bizplace {
              id
              name
              description
            }
            reverseKittingOrderInventories {
              id
              name
              set
              targetType
              targetBatchId
              targetProduct {
                id
                name
                description
              }
              inventory {
                id
                name
                batchId
                batchIdRef
                palletId
                product {
                  id
                  sku
                  name
                  description
                }
                productName
                packingType
                packingSize
                uom
                location {
                  id
                  name
                }
                status
              }
              qty
              uomValue
              otherTarget
              operationGuide
              status
              description
              remark
            }
          }
        }
      `,
      variables: { name: this.orderNo }
    })

    if (!response.errors) {
      const reverseKittingOrder = response.data.executingReverseKittingOrder
      const reverseKittingOIs = reverseKittingOrder.reverseKittingOrderInventories

      const prevReverseKittingOIName = this.data.name
      const matchedReverseKittingOI = reverseKittingOIs
        .filter(item => item.name === prevReverseKittingOIName)
        .map(reverseKittingOI => {
          const inventory = reverseKittingOI.inventory
          return {
            ...reverseKittingOI,
            batchId: inventory.batchId,
            palletId: inventory.palletId,
            location: inventory.location,
            product: inventory.product
          }
        })

      this.data = { ...matchedReverseKittingOI[0] }

      this.getProductCombination()
    }
  }

  async updateReverseKittingIssue(reverseKittingOrder, issue) {
    try {
      if (!issue) return
      const response = await client.mutate({
        mutation: gql`
          mutation updateReverseKittingOrderInventory($id: String!, $patch: ReverseKittingOrderInventoryPatch!) {
            updateReverseKittingOrderInventory(id: $id, patch: $patch) {
              id
              name
            }
          }
        `,
        variables: { id: reverseKittingOrder.id, patch: { issue, cuFlag: 'M' } }
      })

      if (!response.errors) {
        this._showToast({ message: i18next.t('text.issue_updated') })
        this.dispatchEvent(new CustomEvent('order-reverse-kitting-data', { detail: this.data }))
        history.back()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  getProductCombination() {
    let operationGuide = JSON.parse(this.data.operationGuide)
    this.productCombinationSets = {
      records: operationGuide.data.productCombinationSets.map(item => {
        if (item.qty === item.actualQty) {
          item.completed = true
        } else {
          item.completed = false
        }

        return item
      })
    }
  }

  _openIssueNote() {
    openPopup(
      html`
        <popup-note
          .title="${i18next.t('title.issue')}"
          .value="${this.data.issue}"
          @submit="${async e => {
            await this.updateReverseKittingIssue(this.data, e.detail.value)
          }}"
        ></popup-note>
      `,
      {
        backdrop: true,
        size: 'medium',
        title: i18next.t('title.issue')
      }
    )
  }

  _openPopupReverseKittingTemplate(record) {
    openPopup(
      html`
        <popup-reverse-kitting-template
          .reverseKittingOIName="${this.data.name}"
          .data="${record}"
          @updated="${async () => {
            await this.fetchReverseKittingOrder()
          }}"
        ></popup-reverse-kitting-template>
      `,
      {
        backdrop: true,
        escapable: false,
        closable: false,
        size: 'large',
        title: i18next.t('title.reverse_kitting')
      }
    )
  }

  _closePopup() {
    this.dispatchEvent(new CustomEvent('order-reverse-kitting-data', { detail: {} }))
    history.back()
  }

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

window.customElements.define('popup-combination-sets', PopupCombinationSets)
