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 { flattenObject } from '@things-factory/utils'

function formatLocalDate(date = new Date()) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

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

      data-report {
        flex: 1;
      }
    `
  }

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

  get context() {
    return {
      title: i18next.t('title.inventory_report'),
      printable: {
        accept: ['preview'],
        content: this
      },
      exportable: {
        name: i18next.t('title.date_inventory_report', {
          state: {
            text: (() => {
              let date = new Date()
              return date.getFullYear().toString() + (date.getMonth() + 1).toString() + date.getDate().toString()
            })()
          }
        }),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/report/inventory-report'
    }
  }

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

  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.report.fetch()}></search-form>

      <data-report .config=${this._config} .fetchHandler=${this.fetchHandler.bind(this)}></data-report>
    `
  }

  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.from_date'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          max: formatLocalDate(new Date())
        },
        value: (() => {
          const date = new Date()
          date.setMonth(date.getMonth() - 1)
          return formatLocalDate(date)
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to_date'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          min: (() => {
            const date = new Date()
            date.setMonth(date.getMonth() - 1)
            return formatLocalDate(date)
          })(),
          max: formatLocalDate(new Date())
        },
        value: formatLocalDate(new Date()),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.product_info'),
        name: 'product',
        type: 'string',
        props: { searchOper: 'in' }
      },
      {
        label: i18next.t('field.batch_id'),
        name: 'batchNo',
        type: 'string',
        props: { searchOper: 'in' }
      },
      {
        label: i18next.t('field.has_transaction_or_balance'),
        name: 'hasTransactionOrBalance',
        type: 'checkbox',
        value: true,
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.by_pallet'),
        name: 'byPallet',
        type: 'checkbox',
        value: false,
        props: { searchOper: 'eq' }
      }
    ]
  }

  get reportConfig() {
    return {
      rows: {
        selectable: false,
        groups: [
          { column: 'product|sku' },
          { column: 'productName' },
          { column: 'product|type' },
          { column: 'packingType', title: 'Sub Total' },
          { column: 'batchId', title: 'Batch Total' },
          { column: 'uom', title: 'UOM' }
        ],
        totals: ['qty', 'uomValue']
      },
      columns: [
        {
          type: 'string',
          name: 'product|sku',
          header: i18next.t('field.sku'),
          sortable: false,
          width: 400
        },
        {
          type: 'string',
          name: 'productName',
          header: i18next.t('field.product'),
          sortable: false,
          width: 400
        },
        {
          type: 'string',
          name: 'product|type',
          header: i18next.t('field.product_type'),
          sortable: false,
          width: 160
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          width: 180
        },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_id'),
          sortable: false,
          width: 200
        },
        {
          type: 'string',
          name: 'uom',
          header: i18next.t('field.uom'),
          width: 80
        },
        {
          type: 'string',
          name: 'orderNo',
          header: i18next.t('field.order_no'),
          sortable: true,
          width: 300
        },
        {
          type: 'string',
          name: 'orderRefNo',
          header: i18next.t('field.ref_no'),
          sortable: true,
          width: 300
        },
        {
          type: 'string',
          name: 'transactionType',
          header: i18next.t('field.transaction_type'),
          sortable: false,
          width: 300
        },
        {
          type: 'string',
          name: 'createdAt',
          header: i18next.t('field.date'),
          sortable: true,
          width: 110
        },
        {
          type: 'number',
          name: 'qty',
          header: i18next.t('field.qty'),
          record: { align: 'center' },
          sortable: true,
          width: 100
        },
        {
          type: 'number',
          name: 'uomValue',
          header: i18next.t('field.uom_value'),
          record: { align: 'center' },
          sortable: true,
          width: 100
        }
      ]
    }
  }

  async pageInitialized() {
    this._products = []
    this._partners = [...(await this._fetchPartners())]

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

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

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      this._validate()

      var tzoffset = new Date().getTimezoneOffset() * 60
      const response = await client.query({
        query: gql`
          query inventoryHistoryReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            inventoryHistoryReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              palletId
              batchId
              bizplace {
                name
                description
              }
              product {
                sku
                name
                description
                type
                auxValue1
              }
              qty
              uom
              uomValue
              packingType
              orderNo
              orderRefNo
              transactionType
              createdAt
            }
          }
        `,
        variables: {
          filters: [
            ...this.searchForm.queryFilters.map(filter => {
              switch (filter.name) {
                case 'fromDate':
                  let fromDt = new Date(filter.value)
                  fromDt.setHours(0)
                  filter.value = fromDt.toISOString()
                  break
                case 'toDate':
                  let toDt = new Date(filter.value)
                  toDt.setHours(23, 59, 59)
                  filter.value = toDt.toISOString()
                  break
                default:
                  break
              }

              return filter
            }),
            { name: 'tzoffset', operator: 'custom', value: tzoffset }
          ],
          pagination: { page, limit },
          sortings: sorters
        }
      })
      return {
        total: 0,
        records:
          response.data.inventoryHistoryReport.map(item => {
            let date = new Date(parseInt(item.createdAt))
            return flattenObject({
              ...item,
              productName: item.product.name + ' ( ' + item.product.description + ' ) ' + item.product.auxValue1,
              createdAt:
                date.getDate().toString() + '/' + (date.getMonth() + 1).toString() + '/' + date.getFullYear().toString()
            })
          }) || []
      }
    } 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'))
    if (!this._fromDateInput.value) throw new Error(i18next.t('text.from_date_is_empty'))
    if (!this._toDateInput.value) throw new Error(i18next.t('text.to_date_is_empty'))
  }

  _modifyDateRange(e) {
    if (e.currentTarget.name == 'fromDate') {
      const fromDate = e.currentTarget.value

      const from = new Date(fromDate)
      if (Number.isNaN(from.getTime())) return

      const maxTo = new Date(from)
      maxTo.setDate(maxTo.getDate() + 31)
      const maxToStr = formatLocalDate(maxTo)

      if (this._toDateInput.value > maxToStr) this._toDateInput.value = maxToStr
      if (this._toDateInput.value < fromDate) this._toDateInput.value = fromDate

      const min = formatLocalDate(from)
      this._toDateInput.min = min
    }
    if (e.currentTarget.name == 'toDate') {
      const toDate = e.currentTarget.value
      const to = new Date(toDate)
      if (Number.isNaN(to.getTime())) return

      const maxFromDate = new Date(to)
      maxFromDate.setDate(maxFromDate.getDate() - 31)
      const maxFromStr = formatLocalDate(maxFromDate)

      if (this._fromDateInput.value < maxFromStr) this._fromDateInput.value = maxFromStr
    }
  }

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

  // unused function ?
  async _bizplaceChange(e) {
    let bizplace = [{ name: 'bizplace', operator: 'eq', value: e.currentTarget.value }]
    if (e.currentTarget.value == '') {
      this.searchFields
      this._searchFields.filter(x => x.name == 'product')[0].options = [{ name: 'All', value: '' }]
      this._searchFields = [...this._searchFields]
    } else {
      const response = await client.query({
        query: gql`
          query productsByBizplace($filters: [Filter!]) {
            productsByBizplace(filters: $filters) {
              items {
                id
                name
              }
            }
          }
        `,
        variables: { filters: [...bizplace] }
      })

      if (!response.errors) {
        this.searchFields
        this._searchFields.filter(x => x.name == 'product')[0].options = [
          { name: 'All', value: '' },
          ...response.data.productsByBizplace.items.map(item => {
            return {
              name: item.name,
              value: item.id
            }
          })
        ]
        this._searchFields = [...this._searchFields]
      }
    }
  }

  _exportableData() {
    try {
      var headerSetting = [
        { header: i18next.t('field.sku'), key: 'product|sku', width: 75, type: 'string' },
        { header: i18next.t('field.product'), key: 'product|name', width: 75, type: 'string' },
        { header: i18next.t('field.product_description'), key: 'product|description', width: 75, type: 'string' },
        { header: i18next.t('field.product_type'), key: 'product|type', width: 25, type: 'string' },
        { header: i18next.t('field.packing_type'), key: 'packingType', width: 25, type: 'string' },
        { header: i18next.t('field.batch_id'), key: 'batchId', width: 25, type: 'string' },
        { header: i18next.t('field.uom'), key: 'uom', width: 10, type: 'string' },
        { header: i18next.t('field.order_no'), key: 'orderNo', width: 25, type: 'string' },
        { header: i18next.t('field.ref_no'), key: 'orderRefNo', width: 25, type: 'string' },
        { header: i18next.t('field.transaction_type'), key: 'transactionType', width: 25, type: 'string' },
        { header: i18next.t('field.date'), key: 'createdAt', width: 25, type: 'string' },
        { header: i18next.t('field.qty'), key: 'qty', width: 25, type: 'string' },
        { header: i18next.t('field.uom_value'), key: 'uomValue', width: 25, type: 'string' }
      ]

      return {
        header: headerSetting,
        data: this.report.data.records,
        groups: this.report._config.rows.groups,
        totals: this.report._config.rows.totals
      }
    } catch (e) {
      this._showToast(e)
    }
  }

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

window.customElements.define('inventory-report', InventoryReport)
