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

class ElcclDeliveryOrderSummary 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,
      _partners: Object,
      data: Object
    }
  }

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

  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: 'bizplaceId',
        type: 'select',
        options: [
          { value: '' },
          ...this._partners.map(partner => {
            return {
              name: partner.name,
              value: partner.id
            }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.from_date'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'gte',
          max: new Date().toISOString().split('T')[0]
        },
        value: (() => {
          let date = new Date()
          date.setMonth(date.getMonth() - 3)
          return date.toISOString().split('T')[0]
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to_date'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'lte',
          min: (() => {
            let date = new Date()
            date.setMonth(date.getMonth() - 3)
            return date.toISOString().split('T')[0]
          })(),
          max: (() => {
            var max = new Date()
            max.setMonth(max.getMonth())
            return max.toISOString().split('T')[0]
          })()
        },
        value: new Date().toISOString().split('T')[0]
      }
    ]
  }

  get gristConfig() {
    return {
      pagination: { limit: 100, pages: [20, 50, 100, 200, 500] },
      rows: {
        selectable: false
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'date',
          name: 'deliveryDate',
          header: i18next.t('field.date'),
          imex: { header: i18next.t('field.date'), key: 'deliveryDate', width: 20, type: 'string' },
          width: 100
        },
        {
          type: 'string',
          name: 'bizplace|name',
          header: i18next.t('field.company'),
          imex: { header: i18next.t('field.company'), key: 'bizplace|name', width: 60, type: 'string' },
          sortable: true,
          width: 300
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.delivery_order'),
          imex: { header: i18next.t('field.delivery_order'), key: 'name', width: 30, type: 'string' },
          width: 130
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          imex: { header: i18next.t('field.status'), key: 'status', width: 25, type: 'string' },
          width: 100
        },
        {
          type: 'string',
          name: 'deliveryAddress1',
          header: i18next.t('field.delivery_address'),
          imex: { header: i18next.t('field.delivery_address'), key: 'deliveryAddress1', width: 70, type: 'string' },
          width: 300
        },
        {
          type: 'string',
          name: 'palletQty',
          header: i18next.t('field.total_pallet'),
          imex: { header: i18next.t('field.total_pallet'), key: 'palletQty', width: 15, type: 'string' },
          width: 100
        },
        {
          type: 'float',
          name: 'remark',
          header: i18next.t('field.remark'),
          imex: { header: i18next.t('field.remark'), key: 'remark', width: 70, type: 'string' },
          width: 500
        }
      ]
    }
  }

  async pageInitialized() {
    this._products = []
    this._partners = [...(await this._fetchPartners())]
    this._searchFields = this.searchFields
    this._config = this.gristConfig
  }

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

  async fetchHandler({ page, limit, sorters = [{ name: 'createdAt' }] }) {
    if (!this._validateDateRange()) return
    let filters = this.searchForm.queryFilters
    let dates = filters
      .filter(x => x.name == 'fromDate' || x.name == 'toDate')
      .map(itm => {
        switch (itm.name) {
          case 'fromDate':
            let fromDt = new Date(itm.value)
            fromDt.setHours(0)

            itm = {
              ...itm,
              value: fromDt.toISOString(),
              name: 'deliveryDate'
            }
            break
          case 'toDate':
            let toDt = new Date(itm.value)
            toDt.setHours(23, 59, 59)

            itm = {
              ...itm,
              value: toDt.toISOString(),
              name: 'deliveryDate'
            }
            break
          default:
            break
        }

        return itm
      })

    filters = [
      ...filters.filter(x => x.name != 'fromDate' && x.name != 'toDate'),
      ...dates,
      { name: 'status', operator: 'noteq', value: 'CANCELLED' }
    ]

    const response = await client.query({
      query: gql`
        query deliveryOrderReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          deliveryOrderReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              bizplace {
                id
                name
              }
              status
              orderInventories {
                inventory {
                  batchId
                  product {
                    name
                    description
                  }
                  reusablePallet {
                    id
                    name
                  }
                  remark
                }
                crossDocking
                remark
              }
              remark
              palletQty
              deliveryAddress1
              deliveryDate
              createdAt
            }
            total
          }
        }
      `,
      variables: {
        filters: [...filters],
        pagination: { page, limit },
        sortings: sorters
      }
    })

    if (!response.errors) {
      return {
        total: response.data.deliveryOrderReport.total || 0,
        records:
          response.data.deliveryOrderReport.items.map(itm => {
            let remarks = (itm.orderInventories || []).reduce((acc, itm) => {
              let dt = {
                product_name: `${itm.inventory?.product?.name} (${itm.inventory?.product?.description})`,
                product_batch: itm.inventory?.batchId,
                remark: itm?.remark,
                inventory_remark: itm.inventory?.remark,
                pallet:
                  itm.inventory?.reusablePallet && itm.inventory?.reusablePallet?.name
                    ? itm.inventory?.reusablePallet?.name
                    : ''
              }

              let idx = acc.findIndex(
                newItem =>
                  newItem.product_name === dt.product_name &&
                  newItem.product_batch === dt.product_batch &&
                  newItem.cross_docking === dt.cross_docking &&
                  newItem.pallet === dt.pallet &&
                  newItem.remark === dt.remark
              )

              dt = {
                ...dt,
                palletQty: (acc[idx]?.palletQty || 0) + 1
              }

              dt.consolidatedRemarks = this.massageRemarks(dt)

              if (idx < 0) {
                acc = [...acc, dt]
              } else {
                acc[idx] = {
                  ...acc[idx],
                  palletQty: dt.palletQty,
                  consolidatedRemarks: dt.consolidatedRemarks
                }
              }

              return acc
            }, [])

            return flattenObject({ ...itm, remark: remarks.map(itm => itm.consolidatedRemarks).join(', ') })
          }) || []
      }
    }
  }

  massageRemarks(dt) {
    return dt?.remark
      ? dt.remark
      : dt.cross_docking
      ? dt.pallet === ''
        ? `${dt.palletQty} PALLET(S) [C/D]`
        : `${dt.palletQty} PALLET(S) (${dt.pallet}) [C/D]`
      : dt.pallet === ''
      ? `${dt.palletQty} PALLET(S)`
      : `${dt.palletQty} PALLET(S) (${dt.pallet})`
  }

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

    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._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) {
    const fromDate = e.currentTarget.value

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

    let min = new Date(fromDate)
    let max = new Date(fromDate)
    max.setMonth(max.getMonth() + 3)

    let today = new Date()
    today.setHours(0, 0, 0, 0)

    min = min.toISOString().split('T')[0]
    max = max.toISOString().split('T')[0]

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

    this._toDateInput.min = min
    this._toDateInput.max = max
  }

  async _exportableData() {
    try {
      let header = [
        ...this.dataGrist._config.columns
          .filter(column => column.type !== 'gutter' && column.record !== undefined && column.imex !== undefined)
          .map(column => {
            return column.imex
          })
      ]

      let data = (await this.fetchHandler({ page: 1, limit: 9999999 })).records

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

  _validateDateRange() {
    if (this._fromDateInput.value === '') {
      this._showToast({ message: i18next.t('text.from_date_cannot_be_empty') })
      return false
    } else if (this._toDateInput.value === '') {
      this._showToast({ message: i18next.t('text.to_date_cannot_be_empty') })
      return false
    } else if (this._fromDateInput.value > this._toDateInput.value) {
      this._showToast({ message: i18next.t('text.to_date_cannot_be_before_from_date') })
      return false
    }
    return true
  }

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

window.customElements.define('elccl-delivery-order-summary', ElcclDeliveryOrderSummary)
