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, gqlContext, 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 InboundSerialNumberReport 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;
      }

      .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,
      _partners: Object,
      _gristData: Object,
      data: Object
    }
  }

  get context() {
    return {
      title: i18next.t('title.inbound_serial_number_report'),
      printable: {
        accept: ['preview'],
        content: this
      },
      exportable: {
        name: i18next.t('title.inbound_serial_number_report'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/report/inbound-serial-number-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.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._submit.bind(this) }
      },
      {
        label: i18next.t('field.order_no'),
        name: 'orderNo',
        type: 'text',
        props: { searchOper: 'custom' }
      },
      {
        label: i18next.t('field.ref_no'),
        name: 'ref',
        type: 'string',
        props: { searchOper: 'in' }
      },
      {
        label: i18next.t('field.lot_id'),
        name: 'palletId',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.carton_id'),
        name: 'cartonId',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.product_info'),
        name: 'product',
        type: 'string',
        props: { searchOper: 'in' }
      },
      {
        label: i18next.t('field.serial_number'),
        name: 'serialNumber',
        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: 'orderNo',
        header: i18next.t('field.order_no'),
        width: 200
      },
      {
        type: 'string',
        name: 'refNo1',
        header: i18next.t('field.ref_no'),
        width: 150
      },
      {
        type: 'string',
        name: 'refNo2',
        header: i18next.t('field.ref_no_2'),
        width: 150
      },
      {
        type: 'string',
        name: 'refNo3',
        header: i18next.t('field.ref_no_3'),
        width: 150
      },
      {
        type: 'string',
        name: 'palletId',
        header: i18next.t('field.lot_id'),
        width: 200
      },
      {
        type: 'string',
        name: 'cartonId',
        header: i18next.t('field.carton_id'),
        width: 200
      },
      {
        type: 'string',
        name: 'product|sku',
        header: i18next.t('field.sku'),
        width: 150
      },
      {
        type: 'string',
        name: 'product|brandSku',
        header: i18next.t('field.brand_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|type',
        header: i18next.t('field.product_type'),
        width: 150
      },
      {
        type: 'number',
        name: 'product|volume',
        header: i18next.t('field.volume'),
        width: 150
      },
      {
        type: 'string',
        name: 'serialNumber',
        header: i18next.t('field.serial_number'),
        width: 150
      },
      {
        type: 'datetime',
        name: 'etd',
        header: i18next.t('field.etd'),
        width: 170
      }
    ]
    let list = {
      fields: [
        'bizplace|name',
        'orderNo',
        'refNo1',
        'refNo2',
        'refNo3',
        'palletId',
        'cartonId',
        'product|sku',
        'product|brandSku',
        'product|name',
        'product|description',
        'product|type',
        'product|volume',
        'serialNumber',
        'etd'
      ]
    }

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

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

    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 '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
      })

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

      const response = await client.query({
        query: gql`
          query inboundSerialNumberReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            inboundSerialNumberReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                bizplace {
                  name
                  description
                }
                orderNo
                refNo1
                refNo2
                refNo3
                palletId
                cartonId
                product {
                  id
                  sku
                  brandSku
                  name
                  description
                  type
                  volume
                }
                serialNumber
                etd
              }
              total
            }
          }
        `,
        variables: { filters, pagination, sortings },
        context: gqlContext()
      })

      const data = {
        total: response.data.inboundSerialNumberReport.total,
        records:
          response.data.inboundSerialNumberReport.items.map(itm => {
            return flattenObject({ ...itm, bizplace: { name: `${itm.bizplace.name} ${itm.bizplace.description}` } })
          }) || []
      }

      this._gristData = {
        ...data
      }

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

  async _exportableData() {
    try {
      var headerSetting = [
        { header: i18next.t('field.company'), key: 'bizplace|name', width: 25, type: 'string' },
        { header: i18next.t('field.order_no'), key: 'orderNo', width: 25, type: 'string' },
        { header: i18next.t('field.ref_no'), key: 'refNo1', width: 25, type: 'string' },
        { header: i18next.t('field.ref_no_2'), key: 'refNo2', width: 25, type: 'string' },
        { header: i18next.t('field.ref_no_3'), key: 'refNo3', width: 25, type: 'string' },
        { header: i18next.t('field.lot_id'), key: 'palletId', width: 25, type: 'string' },
        { header: i18next.t('field.carton_id'), key: 'cartonId', width: 25, type: 'string' },
        { header: i18next.t('field.sku'), key: 'product|sku', width: 25, type: 'string' },
        { header: i18next.t('field.brand_sku'), key: 'product|brandSku', width: 25, type: 'string' },
        { header: i18next.t('field.product_name'), key: 'product|name', width: 80, type: 'string' },
        { header: i18next.t('field.product_description'), key: 'product|description', width: 25, type: 'string' },
        { header: i18next.t('field.product_type'), key: 'product|type', width: 25, type: 'string' },
        { header: i18next.t('field.volume'), key: 'product|volume', width: 25, type: 'string' },
        { header: i18next.t('field.serial_number'), key: 'serialNumber', width: 25, type: 'string' },
        { header: i18next.t('field.etd'), key: 'etd', width: 25, type: 'datetime' }
      ]

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

      return exportData
    } 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'))
  }

  _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)
    maxDate.setDate(maxDate.getDate() - 1)

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

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

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

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

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

window.customElements.define('inbound-serial-number-report', InboundSerialNumberReport)
