import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import './upload-delivery-note'

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

  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 context() {
    return {
      title: i18next.t('title.delivery_orders'),
      exportable: {
        name: i18next.t('title.delivery_orders'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/transport-order/delivery-order-list'
    }
  }

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

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

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

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

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

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

  async pageInitialized() {
    const _deliveryStatus = await getCodeByName('DELIVERY_STATUS')
    const partners = await this.fetchBizplaces()

    this._searchFields = [
      {
        name: 'name',
        label: i18next.t('field.do_no'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.order_info'),
        name: 'orderInfo',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.company'),
        name: 'bizplaceId',
        type: 'select',
        options: [
          { value: '' },
          ...partners
            .map(partner => {
              return {
                name: `${partner.name} ${partner.description ? `(${partner.description})` : ''}`,
                value: partner.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      {
        name: 'status',
        label: i18next.t('label.status'),
        type: 'select',
        options: [
          { value: '' },
          ..._deliveryStatus.map(status => {
            return { name: i18next.t(`label.${status.description}`), value: status.name }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.from'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq'
        },
        value: (() => {
          let date = new Date()
          date.setMonth(date.getMonth() - 6)
          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() - 6)
            return date.toISOString().split('T')[0]
          })()
        },
        value: new Date().toISOString().split('T')[0]
      },
      {
        label: i18next.t('field.business_rest_day'),
        name: 'businessRestDayFilter',
        type: 'select',
        options: [
          { name: i18next.t('label.all'), value: '' },
          { name: i18next.t('label.not_within_business_rest_day'), value: 'not_within' },
          { name: i18next.t('label.within_business_rest_day'), value: 'within' }
        ],
        props: { searchOper: 'eq' },
        value: ''
      }
    ]

    this.config = {
      list: { fields: ['name', 'refNo', 'bizplace', 'deliveryDate', 'ownCollection', 'status', 'updatedAt'] },
      rows: { selectable: { multiple: true }, appendable: false },
      pagination: { limit: 100, pages: [20, 50, 100, 200, 500] },
      columns: [
        { type: 'gutter', gutterName: 'dirty' },
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              if (record.releaseGood) {
                navigate(`print_delivery_note/${record.name}`)
              } else {
                navigate(`view_delivery_note/${record.name}`)
              }
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.do_no'),
          imex: { header: i18next.t('field.do_no'), key: 'name', width: 30, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'object',
          name: 'releaseGood',
          header: i18next.t('field.ro_no'),
          imex: { header: i18next.t('field.ro_no'), key: 'releaseGood.name', width: 30, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          imex: { header: i18next.t('field.ref_no'), key: 'refNo', width: 25, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo2',
          header: i18next.t('field.ref_no_2'),
          imex: { header: i18next.t('field.ref_no_2'), key: 'refNo2', width: 25, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo3',
          header: i18next.t('field.ref_no_3'),
          imex: { header: i18next.t('field.ref_no_3'), key: 'refNo3', width: 25, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          imex: { header: i18next.t('field.company'), key: 'bizplace.name', width: 30, type: 'string' },
          sortable: true,
          width: 200
        },
        {
          type: 'date',
          name: 'deliveryDate',
          header: i18next.t('field.delivery_date'),
          imex: { header: i18next.t('field.delivery_date'), key: 'deliveryDate', width: 20, type: 'string' },
          sortable: true,
          width: 160
        },
        {
          type: 'string',
          name: 'businessRestDay',
          header: i18next.t('field.business_rest_day'),
          imex: {
            header: i18next.t('field.business_rest_day'),
            key: 'businessRestDay',
            width: 30,
            type: 'string'
          },
          sortable: false,
          width: 200
        },
        {
          type: 'boolean',
          name: 'ownCollection',
          header: i18next.t('field.own_collection'),
          imex: { header: i18next.t('field.own_collection'), key: 'ownCollection', width: 20, type: 'string' },
          sortable: true,
          width: 100
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          imex: { header: i18next.t('field.status'), key: 'status', width: 20, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'palletQty',
          header: i18next.t('field.total_pallet'),
          imex: { header: i18next.t('field.total_pallet'), key: 'palletQty', width: 15, type: 'datetime' },
          sortable: true,
          width: 100
        },
        {
          type: 'string',
          name: 'deliveryAddress1',
          header: i18next.t('field.delivery_address'),
          imex: { header: i18next.t('field.delivery_address'), key: 'deliveryAddress1', width: 70, type: 'datetime' },
          sortable: true,
          width: 300
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          imex: { header: i18next.t('field.created_at'), key: 'createdAt', width: 30, type: 'datetime' },
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          imex: { header: i18next.t('field.updated_at'), key: 'updatedAt', width: 30, type: 'datetime' },
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          imex: { header: i18next.t('field.updater'), key: 'updater.name', width: 30, type: 'string' },
          sortable: true,
          width: 160
        }
      ]
    }
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    let filters = this.searchForm.queryFilters
    var tzoffset = new Date().getTimezoneOffset() * 60
    if (!this._validateDateRange()) return

    const response = await client.query({
      query: gql`
        query deliveryOrders($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          deliveryOrders(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              deliveryAddress1
              palletQty
              bizplace {
                id
                name
                description
              }
              to
              deliveryDate
              status
              releaseGood {
                id
                name
                description
                refNo
                refNo2
                refNo3
                deliverTo {
                  id
                  name
                  businessRestDay
                }
              }
              ownCollection
              createdAt
              updatedAt
              updater {
                id
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: {
        filters: [
          ...filters,
          { name: 'status', operator: 'notin', value: ['CANCELLED'] },
          { name: 'tzoffset', operator: 'custom', value: tzoffset }
        ],
        pagination: { page, limit },
        sortings: sorters
      }
    })

    if (!response.errors) {
      return {
        total: response.data.deliveryOrders.total || 0,
        records:
          response.data.deliveryOrders.items.map(dord => {
            return {
              ...dord,
              refNo: dord?.releaseGood?.refNo || '',
              refNo2: dord?.releaseGood?.refNo2 || '',
              refNo3: dord?.releaseGood?.refNo3 || '',
              businessRestDay: dord?.releaseGood?.deliverTo?.businessRestDay || ''
            }
          }) || []
      }
    }
  }

  async fetchBizplaces(bizplace = []) {
    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
    }
  }

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

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

  _exportableData() {
    let records = []
    if (this.dataGrist.selected && this.dataGrist.selected.length > 0) {
      records = this.dataGrist.selected
    } else {
      records = this.dataGrist.data.records
    }

    var headerSetting = this.dataGrist._config.columns
      .filter(column => column.type !== 'gutter' && column.record !== undefined && column.imex !== undefined)
      .map(column => {
        return column.imex
      })

    var data = records.map(item => {
      return {
        id: item.id,
        ...this._columns
          .filter(column => column.type !== 'gutter' && column.imex !== undefined)
          .reduce((record, column) => {
            record[column.imex.key] = column.imex.key
              .split('.')
              .reduce((obj, key) => (obj && obj[key] !== 'undefined' ? obj[key] : undefined), item)
            if (column.type === 'datetime') {
              record[column.imex.key] = new Date(parseInt(record[column.imex.key])).toLocaleString()
            }
            if (record[column.imex.key] === 'Invalid Date') {
              record[column.imex.key] = ''
            }
            return record
          }, {})
      }
    })
    return { header: headerSetting, data: data }
  }

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

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

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

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

    this._toDateInput.min = min
  }

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

window.customElements.define('delivery-order-list', DeliveryOrderList)
