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

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

import { getCodeByName } from '@things-factory/code-base'
import { i18next, localize } from '@things-factory/i18n-base'
import { client, navigate, PageView } from '@things-factory/shell'
import { ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

class LoadingManifestList 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
    }
  }

  get context() {
    return {
      title: i18next.t('title.manifest_list'),
      exportable: {
        name: i18next.t('title.manifest_list'),
        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')
  }

  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 manifestStatus = await getCodeByName('MANIFEST_STATUS')
    this._searchFields = [
      {
        label: i18next.t('field.manifest_no'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.order_info'),
        name: 'orderInfo',
        type: 'text',
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.transporter'),
        name: 'shippingProvider',
        type: 'select',
        options: [
          { value: '' },
          ...this._shippingProviderList.map(sp => {
            return {
              name: sp,
              value: sp == 'EFMX' ? 'EMS' : sp
            }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.tracking_no'),
        name: 'trackingNo',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.from'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          max: new Date().toISOString().split('T')[0]
        },
        value: (() => {
          let date = new Date()
          date.setMonth(date.getMonth() - 1)
          return date.toISOString().split('T')[0]
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          min: (() => {
            let date = new Date()
            date.setMonth(date.getMonth() - 1)
            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]
      },
      {
        label: i18next.t('field.status'),
        name: 'status',
        type: 'select',
        options: [
          { value: '' },
          ...manifestStatus.map(status => {
            return {
              name: i18next.t(`label.${status.description}`),
              value: status.name
            }
          })
        ],
        props: { searchOper: 'eq' }
      }
    ]

    this.config = {
      list: {
        fields: [
          'name',
          'shippingProvider',
          'status',
          'totalTrackingNo',
          'dispatchedAt',
          'createdAt',
          'updatedAt',
          'creator'
        ]
      },
      rows: { appendable: false, selectable: { multiple: true } },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              navigate(`loading_manifest_detail/${record.name}`)
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.manifest_no'),
          label: true,
          sortable: true,
          width: 180
        },
        {
          type: 'string',
          name: 'shippingProvider',
          header: i18next.t('field.transporter'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'int',
          name: 'totalTrackingNo',
          header: i18next.t('field.total_tracking_no'),
          label: true,
          width: 150
        },
        {
          type: 'datetime',
          name: 'dispatchedAt',
          header: i18next.t('field.dispatch_at'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          label: true,
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'creator',
          header: i18next.t('field.created_by'),
          label: true,
          sortable: true,
          width: 200
        }
      ]
    }
  }

  async fetchHandler({ page, limit, sorters = [{ name: 'createdAt', desc: true }] }) {
    const response = await client.query({
      query: gql`
        query manifests($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          manifests(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              shippingProvider
              dispatchedAt
              status
              totalTrackingNo
              createdAt
              creator {
                id
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: { filters: this.searchForm.queryFilters, pagination: { page, limit }, sortings: sorters }
    })

    if (!response.errors) {
      let shippingProviders = response.data.manifests.items.map(itm =>
        itm.shippingProvider == 'EMS' ? 'EFMX' : itm.shippingProvider
      )
      shippingProviders = [...new Set(shippingProviders)]

      if (this._shippingProviderList.length < shippingProviders.length) {
        this._shippingProviderList = shippingProviders
        this._searchFields.filter(x => x.name == 'shippingProvider')[0].options = [
          { value: '' },
          ...this._shippingProviderList.map(sp => {
            return {
              name: sp,
              value: sp == 'EFMX' ? 'EMS' : sp
            }
          })
        ]
        this._searchFields = [...this._searchFields]
      }
      return {
        total: response.data.manifests.total || 0,
        records:
          response.data.manifests.items.map(itm => {
            if (itm.shippingProvider == 'EMS') {
              return { ...itm, shippingProvider: 'EFMX' }
            }
            return itm
          }) || []
      }
    }
  }

  _modifyDateRange(e) {
    const fromDate = e.currentTarget.value
    if (fromDate == '') return
    if (this._toDateInput.value < fromDate) this._toDateInput.value = fromDate

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

    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
  }

  get _columns() {
    return this.config.columns
  }

  async _exportableData() {
    try {
      let data = []

      var headerSetting = [
        { header: i18next.t('field.manifest_no'), key: 'name', width: 25, type: 'string' },
        { header: i18next.t('field.transporter'), key: 'shippingProvider', width: 25, type: 'string' },
        { header: i18next.t('field.dispatch_at'), key: 'dispatchedAt', width: 25, type: 'date' },
        { header: i18next.t('field.status'), key: 'status', width: 25, type: 'string' },
        { header: i18next.t('field.created_at'), key: 'createdAt', width: 30, type: 'date' },
        { header: i18next.t('field.created_by'), key: 'createdBy', width: 25, type: 'string' }
      ]

      if (this.dataGrist.selected && this.dataGrist.selected.length > 0) {
        data = this.dataGrist.selected.map(record => {
          return {
            ...record,
            createdBy: record.creator.name
          }
        })
      } else {
        data = (await this.fetchHandler({ page: 1, limit: 9999999 })).records.map(record => {
          return {
            ...record,
            createdBy: record.creator.name
          }
        })
      }

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

customElements.define('loading-manifest-list', LoadingManifestList)
