import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import '../inventory/inventory-by-product-detail'

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

import { getCodeByName } from '@things-factory/code-base'
import { i18next, localize } from '@things-factory/i18n-base'
import { client, gqlContext, PageView, store } from '@things-factory/shell'
import { flattenObject, isMobileDevice } from '@things-factory/utils'

class ReleaseInventoryReport extends connect(store)(localize(i18next)(PageView)) {
  static get styles() {
    return css`
      :host {
        display: flex;
        flex-direction: column;
        width: 100%;
      }

      data-grist {
        overflow-y: auto;
        flex: 1;
      }
    `
  }

  static get properties() {
    return {
      _searchFields: Object,
      _config: Object,
      _gristData: Object,
      data: Object
    }
  }

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

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

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

  get _bizplaceSelector() {
    return this.searchForm.shadowRoot.querySelector('select[name=bizplace]')
  }

  get _fromDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=fromDate]')
  }

  get _toDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=toDate]')
  }

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

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

  get searchFields() {
    return [
      {
        label: i18next.t('field.company'),
        name: 'bizplace',
        type: 'select',
        options: [
          { value: '' },
          ...this._partners
            .map(partner => {
              return {
                name: `${partner.name} ${partner.description ? `(${partner.description})` : ''}`,
                value: partner.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.product_info'),
        name: 'product',
        type: 'string',
        props: { searchOper: 'in' }
      },
      {
        label: i18next.t('field.order_info'),
        name: 'order',
        type: 'string',
        props: { searchOper: 'in' }
      },
      {
        label: i18next.t('field.order_date'),
        name: 'orderDate',
        type: 'date',
        props: {
          searchOper: 'eq'
        }
      },
      {
        label: i18next.t('field.lot_id'),
        name: 'palletId',
        type: 'text',
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.carton_id'),
        name: 'cartonId',
        type: 'text',
        props: { searchOper: 'eq' }
      }
    ]
  }

  get reportConfig() {
    let columns = [
      { type: 'gutter', gutterName: 'sequence' },
      {
        type: 'string',
        name: 'bizplace|name',
        header: i18next.t('field.company'),
        width: 200
      },
      {
        type: 'string',
        name: 'product|sku',
        header: i18next.t('field.sku'),
        width: 150
      },
      {
        type: 'string',
        name: 'product|name',
        header: i18next.t('field.product_name'),
        width: 200
      },
      {
        type: 'string',
        name: 'product|description',
        header: i18next.t('field.product_description'),
        width: 300
      },
      {
        type: 'string',
        name: 'product|brand',
        header: i18next.t('field.product_brand'),
        width: 150
      },
      {
        type: 'string',
        name: 'packingType',
        header: i18next.t('field.packing_type'),
        width: 150
      },
      {
        type: 'float',
        name: 'assignedQty',
        header: i18next.t('field.assigned_qty'),
        width: 120
      },
      {
        type: 'float',
        name: 'assignedUomValue',
        header: i18next.t('field.assigned_uom_value'),
        width: 120
      },
      {
        type: 'float',
        name: 'assignedUom',
        header: i18next.t('field.assigned_uom'),
        width: 120
      },
      {
        type: 'string',
        name: 'orderNo',
        header: i18next.t('field.order_no'),
        width: 150
      },
      {
        type: 'string',
        name: 'type',
        header: i18next.t('field.order_type'),
        width: 100
      },
      {
        type: 'datetime',
        name: 'orderAt',
        header: i18next.t('field.order_date'),
        width: 170
      },
      {
        type: 'string',
        name: 'releaseDate',
        header: i18next.t('field.execute_date'),
        width: 170
      },
      {
        type: 'string',
        name: 'palletId',
        header: i18next.t('field.lot_id'),
        width: 150
      },
      {
        type: 'string',
        name: 'cartonId',
        header: i18next.t('field.carton_id'),
        width: 150
      },
      {
        type: 'string',
        name: 'batchId',
        header: i18next.t('field.batch_id'),
        width: 150
      },
      {
        type: 'string',
        name: 'batchIdRef',
        header: i18next.t('field.batch_id_ref'),
        width: 150
      },
      {
        type: 'string',
        name: 'expirationDate',
        header: i18next.t('field.exp_date'),
        width: 170
      },
      {
        type: 'string',
        name: 'manufactureDate',
        header: i18next.t('field.manufacture_date'),
        width: 170
      },
      {
        type: 'string',
        name: 'location|name',
        header: i18next.t('field.location'),
        width: 150
      }
    ]
    let list = {
      fields: [
        'bizplace|name',
        'product|sku',
        'product|name',
        'product|description',
        'product|brand',
        'packingType',
        'assignedQty',
        'assignedUomValue',
        'assignedUom',
        'orderNo',
        'type',
        'orderAt',
        'releaseDate',
        'palletId',
        'cartonId',
        'batchId',
        'batchIdRef',
        'expirationDate',
        'manufactureDate',
        'location|name'
      ]
    }

    return {
      columns: columns,
      list,
      pagination: { limit: 100, pages: [100, 200, 500, 1000] },
      rows: {
        selectable: false,
        insertable: false,
        appendable: false
      }
    }
  }

  async pageInitialized() {
    this._gristData = { total: 0, records: [] }
    this._products = []

    const [_partnersReq] = await Promise.allSettled([this._fetchPartners()])

    this._partners = _partnersReq.status == 'fulfilled' ? _partnersReq.value : []

    this._searchFields = this.searchFields
    this._config = this.reportConfig
  }

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

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      this._validate()
      let filters = this.searchForm.queryFilters.map(filter => {
        switch (filter.name) {
          case 'orderDate':
            let orderDt = new Date(filter.value)
            orderDt.setHours(0)
            filter.value = orderDt.toISOString()
            break
          default:
            break
        }
        return filter
      })

      const pagination = { page, limit }
      const sortings = sorters

      const response = await client.query({
        query: gql`
          query releaseInventoryReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            releaseInventoryReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                bizplace {
                  name
                  description
                }
                product {
                  sku
                  name
                  description
                  brand
                }
                packingType
                assignedQty
                assignedUomValue
                assignedUom
                orderNo
                type
                orderAt
                releaseDate
                palletId
                cartonId
                batchId
                batchIdRef
                expirationDate
                manufactureDate
                location {
                  name
                }
              }
              total
            }
          }
        `,
        variables: { filters, pagination, sortings },
        context: gqlContext()
      })

      const data = {
        total: response.data.releaseInventoryReport.total,
        records:
          response.data.releaseInventoryReport.items.map(itm => {
            return flattenObject({
              ...itm,
              releaseDate: itm.releaseDate ? new Date(itm.releaseDate).toLocaleDateString() : '',
              expirationDate: itm.expirationDate ? new Date(parseInt(itm.expirationDate)).toLocaleDateString() : '',
              manufactureDate: itm.manufactureDate ? new Date(parseInt(itm.manufactureDate)).toLocaleDateString() : ''
            })
          }) || []
      }

      this._gristData = {
        ...data
      }

      return 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
    }
  }
  _validate() {
    if (!this.searchForm.shadowRoot.querySelector('form').checkValidity())
      throw new Error(i18next.t('text.invalid_form_value'))
    if (!this._bizplaceSelector.value) throw new Error(i18next.t('text.no_company_selected'))
  }

  _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
    }
  }

  _submit(e) {
    this._config = { ...this.reportConfig }
    this.searchForm.submit()
  }

  async _exportableData() {
    try {
      var headerSetting = [
        { header: i18next.t('field.company'), key: 'bizplace|name', width: 60, type: 'string' },
        { header: i18next.t('field.sku'), key: 'product|sku', width: 25, type: 'string' },
        { header: i18next.t('field.product_name'), key: 'product|name', width: 50, type: 'string' },
        { header: i18next.t('field.product_description'), key: 'product|description', width: 50, type: 'string' },
        { header: i18next.t('field.product_brand'), key: 'product|brand', width: 25, type: 'string' },
        { header: i18next.t('field.packing_type'), key: 'packingType', width: 30, type: 'string' },
        { header: i18next.t('field.assigned_qty'), key: 'assignedQty', width: 20, type: 'string' },
        { header: i18next.t('field.assigned_uom_value'), key: 'assignedUomValue', width: 20, type: 'string' },
        { header: i18next.t('field.assigned_uom'), key: 'assignedUom', width: 20, type: 'string' },
        { header: i18next.t('field.order_no'), key: 'orderNo', width: 30, type: 'string' },
        { header: i18next.t('field.order_type'), key: 'type', width: 20, type: 'string' },
        { header: i18next.t('field.order_date'), key: 'orderAt', width: 15, type: 'string' },
        { header: i18next.t('field.execute_date'), key: 'releaseDate', width: 15, type: 'string' },
        { header: i18next.t('field.lot_id'), key: 'palletId', width: 20, type: 'string' },
        { header: i18next.t('field.carton_id'), key: 'cartonId', width: 20, type: 'string' },
        { header: i18next.t('field.batch_id'), key: 'batchId', width: 20, type: 'string' },
        { header: i18next.t('field.batch_id_ref'), key: 'batchIdRef', width: 20, type: 'string' },
        { header: i18next.t('field.exp_date'), key: 'expirationDate', width: 15, type: 'string' },
        { header: i18next.t('field.manufacture_date'), key: 'manufactureDate', width: 15, type: 'string' },
        { header: i18next.t('field.location'), key: 'location|name', width: 15, type: 'string' }
      ]

      let data = (await this.fetchHandler({ page: 1, limit: 9999999 })).records.map(itm => {
        return {
          ...itm,
          orderAt: itm.orderAt ? new Date(parseInt(itm.orderAt)).toLocaleString() : ''
        }
      })
      var exportData = {
        header: [...headerSetting],
        data
      }

      return exportData
    } catch (e) {
      this._showToast(e)
    }
  }

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

window.customElements.define('release-inventory-report', ReleaseInventoryReport)
