import '@things-factory/grist-ui'
import '@things-factory/biz-ui'

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

import {
  i18next,
  localize
} from '@things-factory/i18n-base'
import { client } from '@things-factory/shell'

class TrackingInformationPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      releaseGoodId: String,
      bizplaceId: String,
      config: Object
    }
  }

  static get styles() {
    return [
      css`
        :host {
          display: flex;
          flex-direction: column;
          width: 100%;
        }

        data-report {
          flex: 1;
        }
      `
    ]
  }

  render() {
    return html`<data-report .config=${this.config} .fetchHandler=${this.fetchOrderPackages.bind(this)}></data-report>`
  }

  async firstUpdated() {
    this.config = {
      rows: {
        selectable: true,
        groups: [{ column: 'trackingNo' }, { column: 'sku' }]
      },
      columns: [
        {
          type: 'string',
          name: 'trackingNo',
          header: i18next.t('field.tracking_no'),
          sortable: false,
          width: 300
        },
        {
          type: 'string',
          name: 'sku',
          header: i18next.t('field.sku'),
          sortable: false,
          width: 300
        },
        {
          type: 'number',
          name: 'releaseQty',
          header: i18next.t('field.release_qty'),
          sortable: false,
          width: 250
        }
      ]
    }
  }

  async fetchOrderPackages() {
    const filters = [
      { name: 'releaseGoodId', operator: 'eq', value: this.releaseGoodId },
      { name: 'bizplaceId', operator: 'eq', value: this.bizplaceId }
    ]

    const response = await client.query({
      query: gql`
        query orderPackageItemsGroup($filters: [Filter!]!) {
          orderPackageItemsGroup(filters: $filters) {
            trackingNo
            sku
            releaseQty
          }
        }
      `,
      variables: { filters }
    })
    if (!response.errors) {
      return {
        total: 0,
        records: response.data.orderPackageItemsGroup || []
      }
    }
  }

  _showToast({ type, message }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message
        }
      })
    )
  }
}
window.customElements.define('tracking-information-popup', TrackingInformationPopup)
