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 { i18next, localize } from '@things-factory/i18n-base'
import { client, PageView, store } from '@things-factory/shell'
import { flattenObject, isMobileDevice } 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 VolumeSummaryReport extends connect(store)(localize(i18next)(PageView)) {
  static get styles() {
    return css`
      :host {
        display: flex;
        flex-direction: column;
        width: 100%;
      }

      search-form {
        overflow: visible;
      }
      data-grist {
        overflow-y: auto;
        flex: 1;
      }

      #total {
        height: 70%;
      }

      data-grist#summary-grist {
        padding-top: 0px;
        height: 100%;
      }

      .summary {
        background-color: var(--main-section-background-color);
        display: flex;
        flex-direction: column;
        overflow-y: auto;
        align-items: flex-end;
        padding: var(--data-list-item-padding);
        display: grid;
        font-size: 14px;
        color: #394e64;
        grid-template-columns: repeat(2, 1fr);
        grid-auto-rows: minmax(24px, auto);
      }
    `
  }

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

  get context() {
    return {
      title: i18next.t('title.volume_summary_report'),
      printable: {
        accept: ['preview'],
        content: this
      },
      exportable: {
        name: i18next.t('title.volume_summary_report'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/report/volume-summary-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>

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

      <data-grist
        .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
        .config=${this._totalConfig}
        .data=${this._totalGristData}
      ></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.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: (() => {
            const max = new Date()
            return formatLocalDate(max)
          })()
        },
        value: formatLocalDate(new Date()),
        handlers: { change: this._submit.bind(this) }
      }
    ]
  }

  get reportConfig() {
    let columns = [
      { type: 'gutter', gutterName: 'sequence' },
      {
        type: 'date',
        name: 'date',
        header: i18next.t('field.date'),
        width: 100
      },
      {
        type: 'number',
        name: 'openingQty',
        header: i18next.t('field.opening_qty'),
        width: 100
      },
      {
        type: 'float',
        name: 'openingVolume',
        header: i18next.t('field.opening_volume'),
        width: 100
      },
      {
        type: 'number',
        name: 'inboundQty',
        header: i18next.t('field.inbound_qty'),
        width: 100
      },
      {
        type: 'float',
        name: 'inboundVolume',
        header: i18next.t('field.inbound_volume'),
        width: 100
      },
      {
        type: 'number',
        name: 'adjustedQty',
        header: i18next.t('field.adjusted_qty'),
        width: 100
      },
      {
        type: 'float',
        name: 'adjustedVolume',
        header: i18next.t('field.adjusted_volume'),
        width: 100
      },
      {
        type: 'number',
        name: 'missingQty',
        header: i18next.t('field.missing_qty'),
        width: 100
      },
      {
        type: 'float',
        name: 'missingVolume',
        header: i18next.t('field.missing_volume'),
        width: 100
      },
      {
        type: 'number',
        name: 'outboundQty',
        header: i18next.t('field.outbound_qty'),
        width: 100
      },
      {
        type: 'float',
        name: 'outboundVolume',
        header: i18next.t('field.outbound_volume'),
        width: 100
      },
      {
        type: 'number',
        name: 'closingQty',
        header: i18next.t('field.closing_qty'),
        width: 100
      },
      {
        type: 'float',
        name: 'closingVolume',
        header: i18next.t('field.closing_volume'),
        width: 100
      }
    ]

    return {
      list: {
        fields: [
          'date',
          'openingQty',
          'openingVolume',
          'inboundQty',
          'inboundVolume',
          'adjustmentQty',
          'adjustmentVolume',
          'missingQty',
          'missingVolume',
          'closingQty',
          'closingVolume'
        ]
      },
      pagination: { limit: 50, pages: [50, 100, 200, 500, 1000] },
      rows: {
        selectable: false,
        insertable: false,
        appendable: false
      },
      columns: columns
    }
  }

  get totalConfig() {
    let columns = [
      {
        type: 'string',
        name: 'name',
        header: '',
        width: 100
      },
      {
        type: 'float',
        name: 'opening',
        header: i18next.t('field.opening'),
        width: 100
      },
      {
        type: 'float',
        name: 'inbound',
        header: i18next.t('field.inbound'),
        width: 100
      },
      {
        type: 'float',
        name: 'adjustment',
        header: i18next.t('field.adjusted'),
        width: 100
      },
      {
        type: 'float',
        name: 'missing',
        header: i18next.t('field.missing'),
        width: 100
      },
      {
        type: 'float',
        name: 'outbound',
        header: i18next.t('field.outbound'),
        width: 100
      },
      {
        type: 'float',
        name: 'closing',
        header: i18next.t('field.closing'),
        width: 100
      }
    ]

    return {
      list: {
        fields: [
          'totalopeningQty',
          'totalopeningVolume',
          'totalinboundQty',
          'totalinboundVolume',
          'totaladjustmentQty',
          'totaladjustmentVolume',
          'totalmissingQty',
          'totalmissingVolume',
          'totalclosingQty',
          'totalclosingVolume'
        ]
      },
      pagination: { infinite: true },
      rows: {
        selectable: false,
        insertable: false,
        appendable: false
      },
      columns: columns
    }
  }

  async pageInitialized() {
    this._gristData = { total: 0, records: [] }
    this._totalGristData = { total: 0, records: [] }
    this._partners = [...(await this._fetchPartners())]

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

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

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      this._validate()
      let filter = this.searchForm.queryFilters
      const response = await client.query({
        query: gql`
          query inventoryHistoryVolumeSummaryReport(
            $filters: [Filter!]
            $pagination: Pagination
            $sortings: [Sorting!]
          ) {
            inventoryHistoryVolumeSummaryReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                date
                openingQty
                openingVolume
                inboundQty
                inboundVolume
                adjustedQty
                adjustedVolume
                missingQty
                missingVolume
                outboundQty
                outboundVolume
                closingQty
                closingVolume
              }
              total
              totalOpeningQty
              totalOpeningVolume
              totalInboundQty
              totalInboundVolume
              totalAdjustedQty
              totalAdjustedVolume
              totalMissingQty
              totalMissingVolume
              totalOutboundQty
              totalOutboundVolume
              totalClosingQty
              totalClosingVolume
            }
          }
        `,
        variables: { filters: filter, pagination: { page, limit }, sortings: sorters }
      })

      if (!response.errors) {
        const report = response.data.inventoryHistoryVolumeSummaryReport

        const data = {
          total: report.total,
          records: report.items.map(itm => {
            return {
              ...itm,
              openingQty: itm.openingQty || 0,
              inboundQty: itm.inboundQty || 0,
              adjustedQty: itm.adjustedQty || 0,
              missingQty: itm.missingQty || 0,
              outboundQty: itm.outboundQty || 0,
              closingQty: itm.closingQty || 0,
              openingVolume: parseFloat(itm.openingVolume || 0).toFixed(2),
              inboundVolume: parseFloat(itm.inboundVolume || 0).toFixed(2),
              adjustedVolume: parseFloat(itm.adjustedVolume || 0).toFixed(2),
              missingVolume: parseFloat(itm.missingVolume || 0).toFixed(2),
              outboundVolume: parseFloat(itm.outboundVolume || 0).toFixed(2),
              closingVolume: parseFloat(itm.closingVolume || 0).toFixed(2)
            }
          })
        }

        this._gristData = {
          ...data
        }

        this._totalGristData = {
          total: 2,
          records: [
            {
              name: 'Quantity',
              opening: report.totalOpeningQty || 0,
              inbound: report.totalInboundQty || 0,
              adjustment: report.totalAdjustedQty || 0,
              missing: report.totalMissingQty || 0,
              outbound: report.totalOutboundQty || 0,
              closing: report.totalClosingQty || 0
            },
            {
              name: 'Volume',
              opening: parseFloat(report.totalOpeningVolume || 0).toFixed(2),
              inbound: parseFloat(report.totalInboundVolume || 0).toFixed(2),
              adjustment: parseFloat(report.totalAdjustedVolume || 0).toFixed(2),
              missing: parseFloat(report.totalMissingVolume || 0).toFixed(2),
              outbound: parseFloat(report.totalOutboundVolume || 0).toFixed(2),
              closing: parseFloat(report.totalClosingVolume || 0).toFixed(2)
            }
          ]
        }

        return data
      } else {
        this._gristData = { total: 0, records: [] }
        this._totalGristData = { total: 0, records: [] }
      }
    } 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
              company {
                id
                domainId
              }
            }
          }
        }
      `,
      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'))
    if (this._fromDateInput.value > this._toDateInput.value)
      throw new Error(i18next.t('text.to_date_cannot_be_before_from_date'))
  }

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

  _modifyDateRange(e) {
    const fromDate = e.currentTarget.value

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

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

    const maxDate = new Date(minDate)
    maxDate.setMonth(maxDate.getMonth() + 1)

    const min = formatLocalDate(minDate)
    const max = formatLocalDate(maxDate)

    if (this._toDateInput.value > max) this._toDateInput.value = max

    this._toDateInput.min = min
    this._toDateInput.max = max
    this._submit()
  }

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

  async _exportableData() {
    try {
      var headerSetting = [
        { header: i18next.t('field.date'), key: 'date', width: 30, type: 'date' },
        { header: i18next.t('field.opening_qty'), key: 'openingQty', width: 30, type: 'float' },
        { header: i18next.t('field.opening_volume'), key: 'openingVolume', width: 30, type: 'float' },
        { header: i18next.t('field.inbound_qty'), key: 'inboundQty', width: 30, type: 'float' },
        { header: i18next.t('field.inbound_volume'), key: 'inboundVolume', width: 30, type: 'float' },
        { header: i18next.t('field.adjusted_qty'), key: 'adjustedQty', width: 30, type: 'float' },
        { header: i18next.t('field.adjusted_volume'), key: 'adjustedVolume', width: 30, type: 'float' },
        { header: i18next.t('field.missing_qty'), key: 'missingQty', width: 30, type: 'float' },
        { header: i18next.t('field.missing_volume'), key: 'missingVolume', width: 30, type: 'float' },
        { header: i18next.t('field.outbound_qty'), key: 'outboundQty', width: 30, type: 'float' },
        { header: i18next.t('field.outbound_volume'), key: 'outboundVolume', width: 30, type: 'float' },
        { header: i18next.t('field.closing_qty'), key: 'closingQty', width: 30, type: 'float' },
        { header: i18next.t('field.closing_volume'), key: 'closingVolume', width: 30, type: 'float' }
      ]

      var exportData = {
        header: [...headerSetting],
        data: (await this.fetchHandler({ page: 1, limit: 9999999 })).records
      }

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

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

window.customElements.define('volume-summary-report', VolumeSummaryReport)
