import '@things-factory/barcode-ui'
import '@things-factory/grist-ui'
import '../components/popup-note'

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

import {
  MultiColumnFormStyles,
  SingleColumnFormStyles
} from '@things-factory/form-ui'
import {
  i18next,
  localize
} from '@things-factory/i18n-base'
import { client } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'

export class VasListPopup extends localize(i18next)(LitElement) {
  static get styles() {
    return [
      SingleColumnFormStyles,
      MultiColumnFormStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
        }
        .info-form {
          overflow: visible;
        }
        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        .button-container {
          padding: 10px 0 12px 0;
          text-align: center;
        }
      `
    ]
  }

  static get properties() {
    return {
      config: Object
    }
  }

  get productInfoInput() {
    return this.shadowRoot.querySelector('barcode-scanable-input[name=productInfo]').shadowRoot.querySelector('input')
  }

  get dataGrist() {
    return this.shadowRoot.querySelector('data-grist')
  }

  render() {
    return html`
      <form id="info-form" class="multi-column-form">
        <fieldset>
          <legend>${i18next.t('title.scan_area')}</legend>
          <label>${i18next.t('label.pallet_ref_no')}</label>
          <barcode-scanable-input
            name="productInfo"
            custom-input
            @keypress="${e => {
              if (e.keyCode === 13) {
                e.preventDefault()
                if (this.productInfoInput.value) {
                  this.productInfoInput.value = ''
                }
              }
            }}"
          ></barcode-scanable-input>
        </fieldset>
      </form>

      <div class="grist">
        <data-grist
          .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
          .config=${this.config}
          .data=${this.orderVasData}
        ></data-grist>
      </div>

      <div class="button-container">
        <mwc-button
          label="${`${i18next.t('button.close')}`}"
          @click="${() => {
            this.dispatchEvent(new CustomEvent('reassignment-completed'))
            history.back()
          }}"
          raised
        ></mwc-button>
      </div>
    `
  }

  async firstUpdated() {
    this.orderVasData = await this.fetchOrderVas()
    this.config = {
      pagination: { infinite: true },
      rows: { appendable: false },
      list: {
        fields: [
          'batchId',
          'sku',
          'qty',
          'packingType',
          'uom',
          'uomValue',
          'vas',
          'vasQty',
          'newSKU',
          'newPackingType',
          'newUom',
          'newUomValue',
          'outputQty',
          'remark'
        ]
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'close',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              this.orderVasData = {
                ...this.orderVasData,
                records: data.records.filter((record, idx) => idx !== rowIndex)
              }
            }
          }
        },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_no'),
          width: 150
        },
        {
          type: 'string',
          name: 'sku',
          header: i18next.t('field.sku'),
          width: 150
        },
        {
          type: 'integer',
          name: 'qty',
          header: i18next.t('field.qty'),
          record: { editable: false },
          width: 100
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type_sku', { sku: 'SKU' }),
          width: 150
        },
        {
          type: 'integer',
          name: 'uom',
          header: i18next.t('field.uom_sku', { sku: 'SKU' }),
          width: 150
        },
        {
          type: 'integer',
          name: 'uomValue',
          header: i18next.t('field.uom_value_sku', { sku: 'SKU' }),
          width: 150
        },
        {
          type: 'object',
          name: 'vas',
          header: i18next.t('field.vas'),
          record: { editable: false },
          width: 250
        },
        {
          type: 'integer',
          name: 'vasQty',
          header: i18next.t('field.vas_qty'),
          record: { editable: false, options: { min: 0 } },
          width: 100
        },
        {
          type: 'string',
          name: 'newSKU',
          header: i18next.t('field.new_sku'),
          record: { editable: false },
          width: 150
        },
        {
          type: 'code',
          name: 'newPackingType',
          header: i18next.t('field.packing_type_sku', { sku: 'NEW SKU' }),
          record: {
            editable: false,
            codeName: 'PACKING_TYPES'
          },
          width: 150
        },
        {
          type: 'code',
          name: 'newUom',
          header: i18next.t('field.uom_sku', { sku: 'NEW SKU' }),
          record: { editable: false, codeName: 'UOM' },
          width: 150
        },
        {
          type: 'integer',
          name: 'newUomValue',
          header: i18next.t('field.uom_value_sku', { sku: 'NEW SKU' }),
          record: { editable: false },
          width: 150
        },
        {
          type: 'integer',
          name: 'outputQty',
          header: i18next.t('field.output_qty'),
          record: { editable: false, options: { min: 0 } },
          width: 100
        },
        {
          type: 'string',
          name: 'remark',
          header: i18next.t('field.remark'),
          record: { editable: false },
          width: 250
        }
      ]
    }
    if (!this.orderVasData) {
      this.orderVasData = { records: [] }
    } else {
      this.orderVasData = { ...this.orderVasData }
    }
  }

  async fetchOrderVas() {
    this.dataGrist.showSpinner()
    try {
      let filters = []

      if (this.orderType == 'RELEASE_GOODS') {
        filters.push({ name: 'releaseGood', operator: 'eq', value: this.orderId })
      }
      const response = await client.query({
        query: gql`
          query orderVass($filters: [Filter!]) {
            orderVass(filters: $filters) {
              items {
                id
                name
                qty
                outputQty
                batchId
                product {
                  id
                  name
                  sku
                }
                uom
                uomValue
                packingType
                newProduct {
                  id
                  name
                  sku
                }
                newUom
                newUomValue
                newPackingType
                orderVasItems {
                  id
                  vas {
                    id
                    name
                    description
                  }
                  vasQty
                }
                remark
              }
              total
            }
          }
        `,
        variables: {
          filters
        }
      })

      if (!response.errors) {
        if (response?.data?.orderVass?.items) {
          // if (!this.orderVasData.records.find(itm => itm.name === response.data.orderVass.item.name))
          const records = response.data.orderVass.items.map(record => {
            return {
              ...record,
              sku: record.product?.sku,
              newSKU: record.product?.sku
            }
          })
          return { records: this.formatData(records) }
        } else if (response?.data?.orderVass?.error) {
          return { message: response.data.orderVass.error }
        }
      }
    } catch (error) {
      this._showToast({ message: error })
    }
    this.dataGrist.hideSpinner()
  }

  formatData(records) {
    let orderVasData = []
    records
      .filter(ov => ov.orderVasItems)
      .map(ov => {
        if (ov.orderVasItems.length > 1) {
          for (let i = 0; i < ov.orderVasItems.length; i++) {
            if (i == 0) {
              orderVasData.push({
                ...ov,
                orderVasItems: ov.orderVasItems[i]
              })
            } else {
              orderVasData.push({ orderVasItems: ov.orderVasItems[i] })
            }
          }
        } else {
          for (let i = 0; i < ov.orderVasItems.length; i++) {
            orderVasData.push({
              ...ov,
              orderVasItems: ov.orderVasItems[i]
            })
          }
        }
      })
    return orderVasData.map(record => {
      return {
        ...record,
        sku: record?.product?.sku,
        outputQty: record?.outputQty,
        newSKU: record?.newProduct?.sku,
        qty: record?.qty,
        vas: record?.orderVasItems?.vas,
        vasQty: record?.orderVasItems?.vasQty,
        done: record?.orderVasItems?.executedAt !== null ? true : false
      }
    })
  }

  _showToast({ type, message }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message
        }
      })
    )
  }
}
window.customElements.define('vas-list-popup', VasListPopup)
