import '@things-factory/form-ui'
import '@things-factory/grist-ui'

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

import { i18next, localize } from '@things-factory/i18n-base'
import { client, gqlContext, PageView } from '@things-factory/shell'
import { ScrollbarStyles } from '@things-factory/styles'
import { 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 ManifestReport 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,
      _shippingProviderList: Array,
      _partners: Object
    }
  }

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

  get _fromDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=fromDate]')
  }

  get _toDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=toDate]')
  }

  get searchForm() {
    return this.shadowRoot.querySelector('search-form')
  }

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

  get _bizplaceSelector() {
    return this.searchForm.shadowRoot.querySelector('select[name=bizplace]')
  }

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

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

  constructor() {
    super()
    this._shippingProviderList = []
  }

  async pageInitialized() {
    const partners = await this._fetchPartners()
    this._searchFields = [
      {
        label: i18next.t('field.company'),
        name: 'bizplace',
        type: 'select',
        options:
          partners?.length == 1
            ? [
                {
                  name: `${partners[0].name} ${partners[0].description ? `(${partners[0].description})` : ''}`,
                  value: partners[0].id
                }
              ]
            : [
                { 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.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',
          max: formatLocalDate(new Date()),
          min: (() => {
            const date = new Date()
            date.setMonth(date.getMonth() - 1)
            return formatLocalDate(date)
          })()
        },
        value: formatLocalDate(new Date())
      },
      {
        label: i18next.t('field.tracking_no'),
        name: 'trackingNo',
        type: 'text',
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.ro_no'),
        name: 'releaseGoodNo',
        type: 'text',
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.tracking_no'),
        name: 'hasTrackingNo',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      }
    ]

    this.config = {
      list: {
        fields: [
          'company',
          'refNo',
          'roNo',
          'status',
          'trackingNo',
          'grossWeight',
          'name',
          'manifestedAt',
          'manifestedBy',
          'createdAt',
          'transporter'
        ]
      },
      rows: { appendable: false, selectable: false },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'bizplace',
          header: i18next.t('field.company'),
          label: true,
          width: 130
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          label: true,
          width: 140
        },
        {
          type: 'string',
          name: 'roNo',
          header: i18next.t('field.ro_no'),
          label: true,
          width: 150
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'trackingNo',
          header: i18next.t('field.tracking_no'),
          label: true,
          width: 120
        },
        {
          type: 'float',
          name: 'grossWeight',
          header: i18next.t('field.gross_weight'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'manifestNo',
          header: i18next.t('field.manifest_no'),
          label: true,
          width: 140
        },
        {
          type: 'datetime',
          name: 'manifestedAt',
          header: i18next.t('field.manifested_at'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'manifestedBy',
          header: i18next.t('field.manifested_by'),
          label: true,
          width: 130
        },
        {
          type: 'datetime',
          name: 'orderedAt',
          header: i18next.t('field.created_at'),
          label: true,
          width: 120
        },
        {
          type: 'string',
          name: 'transporter',
          header: i18next.t('field.transporter'),
          label: true,
          width: 120
        }
      ]
    }
  }

  async fetchHandler({ page, limit, sorters = [{ name: 'createdAt', desc: true }] }) {
    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 response = await client.query({
        query: gql`
          query manifestReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            manifestReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                bizplace
                refNo
                roNo
                status
                grossWeight
                trackingNo
                manifestNo
                manifestedAt
                manifestedBy
                orderedAt
                transporter
              }
              total
            }
          }
        `,
        variables: { filters, pagination: { page, limit }, sortings: sorters },
        context: gqlContext()
      })

      if (!response.errors) {
        return {
          total: response.data.manifestReport.total || 0,
          records: (response.data.manifestReport.items || []).map(item => {
            let transporterData = item?.transporter == 'EMS' ? 'EFMX' : item.transporter
            return {
              ...item,
              transporter: transporterData
            }
          })
        }
      }
    } 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 (fromDate == '') return
    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() + 3)

    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
  }

  async _exportableData() {
    try {
      var headerSetting = [
        { header: i18next.t('field.company'), key: 'bizplace', width: 40, type: 'string' },
        { header: i18next.t('field.ref_no'), key: 'refNo', width: 20, type: 'string' },
        { header: i18next.t('field.ro_no'), key: 'roNo', width: 30, type: 'string' },
        { header: i18next.t('field.status'), key: 'status', width: 15, type: 'string' },
        { header: i18next.t('field.tracking_no'), key: 'trackingNo', width: 15, type: 'string' },
        { header: i18next.t('field.gross_weight'), key: 'grossWeight', width: 15, type: 'number' },
        { header: i18next.t('field.manifest_no'), key: 'manifestNo', width: 20, type: 'string' },
        { header: i18next.t('field.manifested_at'), key: 'manifestedAt', width: 20, type: 'string' },
        { header: i18next.t('field.manifested_by'), key: 'manifestedBy', width: 20, type: 'string' },
        { header: i18next.t('field.created_at'), key: 'orderedAt', width: 20, type: 'string' },
        { header: i18next.t('field.transporter'), key: 'transporter', width: 20, type: 'string' }
      ]

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

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

customElements.define('manifest-report', ManifestReport)
