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

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

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

import { REPLENISHMENT_STATUS } from '../constants'

class ReplenishmentReport extends 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 {
      _searchFields: Array,
      config: Object,
      data: Object
    }
  }

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

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

  get context() {
    return {
      title: i18next.t('title.replenishment_report'),
      exportable: {
        name: i18next.t('title.replenishment_report'),
        data: this._exportableData.bind(this)
      }
    }
  }

  async pageInitialized() {
    const _replenishmentStatus = await getCodeByName('REPLENISHMENT_STATUS')
    const partners = [...(await this._fetchPartners())]

    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' }
      },
      {
        label: i18next.t('field.order_no'),
        name: 'orderNo',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.product_info'),
        name: 'productInfo',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        name: 'status',
        label: i18next.t('label.status'),
        type: 'select',
        options: [
          { value: '' },
          { name: REPLENISHMENT_STATUS.PICKING.name, value: REPLENISHMENT_STATUS.PICKING.value },
          { name: REPLENISHMENT_STATUS.PUTAWAY.name, value: REPLENISHMENT_STATUS.PUTAWAY.value },
          ..._replenishmentStatus.map(status => {
            return { name: i18next.t(`label.${status.description}`), value: status.name }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.picking_bin'),
        name: 'pickingBin',
        type: 'text',
        props: { searchOper: 'eq' }
      }
    ]

    this.config = {
      pagination: { limit: 100, pages: [100, 200, 500, 1000] },
      rows: { selectable: { multiple: true } },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          imex: {
            type: 'string',
            header: i18next.t('field.company'),
            key: 'bizplace.name',
            width: 30
          },
          label: true,
          sortable: true,
          width: 250
        },
        {
          type: 'string',
          name: 'orderNo',
          header: i18next.t('field.order_no'),
          imex: {
            type: 'string',
            header: i18next.t('field.order_no'),
            key: 'orderNo',
            width: 30
          },
          label: true,
          sortable: true,
          width: 250
        },
        {
          type: 'string',
          name: 'productSKU',
          header: i18next.t('field.sku'),
          imex: {
            type: 'string',
            key: 'productSKU',
            header: i18next.t('field.sku'),
            width: 30
          },
          label: true,
          sortable: true,
          width: 200
        },
        {
          type: 'string',
          name: 'pickingBin',
          header: i18next.t('field.picking_bin'),
          imex: {
            type: 'string',
            key: 'pickingBin',
            header: i18next.t('field.picking_bin'),
            width: 40
          },
          label: true,
          sortable: true,
          width: 300
        },
        {
          type: 'float',
          name: 'transferQty',
          header: i18next.t('field.transfer_qty'),
          imex: {
            type: 'float',
            key: 'transferQty',
            header: i18next.t('field.transfer_qty'),
            width: 30
          },
          label: true,
          sortable: true,
          width: 200
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          imex: {
            type: 'string',
            key: 'status',
            header: i18next.t('field.status'),
            width: 30
          },
          label: true,
          sortable: true,
          width: 200
        }
      ]
    }
  }

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

  async fetchHandler({ page, limit, sorters = [] }) {
    const response = await client.query({
      query: gql`
        query replenishmentReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          replenishmentReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              productSKU
              transferQty
              status
              orderNo
              pickingBin
              bizplace {
                id
                name
              }
            }
            total
          }
        }
      `,
      variables: {
        filters: await this.searchForm.getQueryFilters(),
        pagination: { page, limit },
        sortings: sorters
      }
    })

    if (!response.errors) {
      this.searchForm.form.reset()
      return {
        total: response.data.replenishmentReport.total || 0,
        records: response.data.replenishmentReport.items || []
      }
    }
  }

  async _fetchPartners() {
    const filters = []
    const response = await client.query({
      query: gql`
        query partnersBizplaces($filters: [Filter!]) {
          partnersBizplaces(filters: $filters) {
            items {
              id
              name
              description
              domain {
                id
                name
              }
            }
          }
        }
      `,
      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
    }
  }

  async _exportableData() {
    let records = []
    if (this.dataGrist.selected && this.dataGrist.selected.length > 0) {
      records = this.dataGrist.selected
    } else {
      records = this.dataGrist.data.records
    }

    var headerSetting = this.dataGrist._config.columns
      .filter(column => column.type !== 'gutter' && column.imex !== undefined)
      .map(column => {
        return column.imex
      })

    var data = records.map(item => {
      return {
        id: item.id,
        ...this.config.columns
          .filter(column => column.type !== 'gutter' && column.imex !== undefined)
          .reduce((record, column) => {
            record[column.imex.key] = column.imex.key
              .split('.')
              .reduce((obj, key) => (obj && obj[key] !== 'undefined' ? obj[key] : undefined), item)
            return record
          }, {})
      }
    })

    return { header: headerSetting, data: data }
  }

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

  get searchForm() {
    return this.shadowRoot.querySelector('search-form')
  }
}
window.customElements.define('replenishment-report', ReplenishmentReport)
