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

import gql from 'graphql-tag'
import {
  css,
  html
} from 'lit-element'
import { connect } from 'pwa-helpers/connect-mixin'

import {
  i18next,
  localize
} from '@things-factory/i18n-base'
import {
  client,
  PageView,
  store
} from '@things-factory/shell'
import { ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

class NonLoadedInventory extends connect(store)(localize(i18next)(PageView)) {
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
        }
        search-form {
          overflow: visible;
        }
        data-grist {
          overflow-y: auto;
          flex: 1;
        }
      `
    ]
  }

  static get properties() {
    return {
      _email: String,
      _searchFields: Array,
      _expSearchFields: Array,
      _showExpiration: Boolean,
      config: Object,
      data: Object
    }
  }

  render() {
    return html`
      <search-form id="search-form" .fields=${this._searchFields} @submit=${e => this.dataGrist.fetch()}></search-form>

      ${this._showExpiration
        ? html`<search-form
            id="search-exp-form"
            .fields=${this._expSearchFields}
            .hideSearchButton=${true}
            @submit=${e => this.dataGrist.fetch()}
          ></search-form>`
        : html``}

      <data-grist
        .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
        .config=${this.config}
        .fetchHandler="${this.fetchHandler.bind(this)}"
      ></data-grist>
    `
  }

  get context() {
    return {
      title: i18next.t('title.non_loaded_inventory'),
      exportable: {
        name: i18next.t('title.non_loaded_inventory'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/inventory/non-loaded-inventory'
    }
  }

  async pageInitialized() {
    const partners = await this._fetchPartners()
    this.config = {
      list: {
        fields: [
          'releaseOrderNo',
          'palletId',
          'cartonId',
          'batchId',
          'productSku',
          'product',
          'productBrand',
          'packingType',
          'pickedQty',
          'pickedUomValue',
          'uom',
          'binLocation'
        ]
      },
      pagination: { limit: 50, pages: [50, 100, 200, 500] },
      rows: { appendable: false },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'string',
          name: 'releaseOrderNo',
          header: i18next.t('field.ro_no'),
          label: true,
          width: 150
        },
        {
          type: 'string',
          name: 'bizplaceName',
          header: i18next.t('field.bizplace'),
          label: true,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          label: true,
          width: 150
        },
        {
          type: 'string',
          name: 'palletId',
          header: i18next.t('field.lot_id'),
          label: true,
          width: 150
        },
        {
          type: 'string',
          name: 'cartonId',
          header: i18next.t('field.carton_id'),
          label: true,
          sortable: true,
          width: 120
        },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_id'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'productSku',
          header: i18next.t('field.sku'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'product',
          header: i18next.t('field.product'),
          label: true,
          sortable: true,
          width: 250
        },
        {
          type: 'string',
          name: 'productBrand',
          header: i18next.t('field.brand'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'number',
          name: 'pickedQty',
          header: i18next.t('field.qty'),
          label: true,
          width: 80
        },
        {
          type: 'float',
          name: 'pickedUomValue',
          header: i18next.t('field.total_uom_value'),
          label: true,
          width: 110
        },
        {
          type: 'string',
          name: 'uom',
          header: i18next.t('field.uom'),
          label: true,
          sortable: true,
          width: 80
        },
        {
          type: 'string',
          name: 'binLocation',
          header: i18next.t('field.bin_location'),
          label: true,
          sortable: true,
          width: 120
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          width: 150
        }
      ]
    }

    this._searchFields = [
      {
        label: i18next.t('field.company'),
        name: 'bizplace',
        type: 'select',
        options: [
          { value: '' },
          ...partners
            .map(partner => {
              return {
                name: `${partner.name} ${partner.description ? `(${partner.description})` : ''}`,
                value: partner.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' },
        attrs: ['custom']
      },
      {
        label: i18next.t('field.product_info'),
        name: 'productInfo',
        type: 'text',
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.batch_id'),
        name: 'batchId',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.lot_id'),
        name: 'palletId',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.carton_id'),
        name: 'cartonId',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.ro_no'),
        name: 'roNo',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.ref_no'),
        name: 'refNo',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.bin_location'),
        name: 'binLocation',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.date'),
        name: 'createdAt',
        type: 'date',
        props: {
          searchOper: 'eq',
          max: new Date().toISOString().split('T')[0]
        },
        value: new Date().toISOString().split('T')[0]
      }
    ]
  }

  async pageUpdated(changes, lifecycle) {
    if (this.active) {
      this.dataGrist.fetch()
    }
  }

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

  get searchForm() {
    return this.shadowRoot.querySelector('#search-form')
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    const filters = await this.searchForm.getQueryFilters()
    const response = await client.query({
      query: gql`
        query nonLoadedOrderInventories($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          nonLoadedOrderInventories(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              releaseGood {
                name
                refNo
                bizplace {
                  name
                }
              }
              inventory {
                palletId
                cartonId
              }
              packingType
              batchId
              pickedQty
              pickedUomValue
              uom
              product {
                sku
                name
                brand
                description
              }
              binLocation {
                name
              }
              createdAt
              updatedAt
            }
            total
          }
        }
      `,
      variables: {
        filters: [...filters, { name: 'timezoneOffset', operator: 'eq', value: new Date().getTimezoneOffset() }],
        pagination: { page, limit },
        sortings: sorters
      }
    })

    return {
      total: response.data.nonLoadedOrderInventories.total || 0,
      records:
        response.data.nonLoadedOrderInventories.items.map(item => {
          return {
            ...item,
            product: `${item.product.name} ${item.product.description}`,
            productName: item.product.name,
            productDescription: item.product.description,
            productSku: item.product.sku,
            productBrand: item.product.brand,
            binLocation: item.binLocation.name,
            palletId: item.inventory.palletId,
            cartonId: item.inventory.cartonId,
            releaseOrderNo: item.releaseGood.name,
            bizplaceName: item.releaseGood.bizplace.name,
            refNo: item.releaseGood.refNo
          }
        }) || []
    }
  }

  async _exportableData() {
    try {
      let data = []

      var headerSetting = [
        { header: i18next.t('field.ro_no'), key: 'releaseOrderNo', width: 50, type: 'string' },
        { header: i18next.t('field.bizplace'), key: 'bizplaceName', width: 50, type: 'string' },
        { header: i18next.t('field.ref_no'), key: 'refNo', width: 50, type: 'string' },
        { header: i18next.t('field.lot_id'), key: 'palletId', width: 50, type: 'string' },
        { header: i18next.t('field.carton_id'), key: 'cartonId', width: 50, type: 'string' },
        { header: i18next.t('field.batch_id'), key: 'batchId', width: 25, type: 'string' },
        { header: i18next.t('field.sku'), key: 'productSku', width: 25, type: 'string' },
        { header: i18next.t('field.product'), key: 'productName', width: 25, type: 'string' },
        { header: i18next.t('field.product_description'), key: 'productDescription', width: 25, type: 'string' },
        { header: i18next.t('field.brand'), key: 'productBrand', width: 25, type: 'string' },
        { header: i18next.t('field.packing_type'), key: 'packingType', width: 25, type: 'string' },
        { header: i18next.t('field.qty'), key: 'pickedQty', width: 25, type: 'string' },
        { header: i18next.t('field.total_uom_value'), key: 'pickedUomValue', width: 25, type: 'float' },
        { header: i18next.t('field.uom'), key: 'uom', width: 25, type: 'string' },
        { header: i18next.t('field.bin_location'), key: 'binLocation', width: 25, type: 'string' },
        { header: i18next.t('field.created_at'), key: 'createdAt', width: 25, type: 'datetime' }
      ]

      if (this.dataGrist.selected && this.dataGrist.selected.length > 0) {
        data = this.dataGrist.selected
      } else {
        data = (await this.fetchHandler({ page: 1, limit: 9999999 })).records
      }

      data = data.map(itm => {
        return {
          ...itm,
          createdAt: itm.createdAt ? new Date(parseInt(itm.createdAt)).toLocaleString() : ''
        }
      })

      return { header: headerSetting, data }
    } catch (e) {
      this._showToast(e)
    }
  }

  async _fetchPartners() {
    const filters = []
    const response = await client.query({
      query: gql`
        query partnersBizplaces($filters: [Filter!]) {
          partnersBizplaces(filters: $filters) {
            items {
              id
              name
              description
            }
          }
        }
      `,
      variables: { filters }
    })

    if (!response.errors) {
      return response.data.partnersBizplaces.items
    }
  }

  _compareValues(key, order = 'asc') {
    return function innerSort(a, b) {
      if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
        return 0
      }

      const varA = typeof a[key] === 'string' ? a[key].toUpperCase() : a[key]
      const varB = typeof b[key] === 'string' ? b[key].toUpperCase() : b[key]

      let comparison = 0
      if (varA > varB) {
        comparison = 1
      } else if (varA < varB) {
        comparison = -1
      }
      return order === 'desc' ? comparison * -1 : comparison
    }
  }

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

window.customElements.define('non-loaded-inventory', NonLoadedInventory)
