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'

import { WORKSHEET_TYPE } from '../constants'

import { applyParamsToFields } from '../../util'
class InboundWorksheet 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 {
      _email: String,
      _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.inbound_worksheet'),
      exportable: {
        name: i18next.t('title.inbound_worksheet'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/inbound/inbound-worksheet'
    }
  }

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

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

  pageUpdated(changes, lifecycle) {
    if (this.active) {
      let { params } = lifecycle
      if (params && this._searchFields) {
        applyParamsToFields(this._searchFields, params, this.searchForm)
      }
      this.dataGrist.fetch()
    }
  }

  async pageInitialized() {
    const _worksheetTypes = [
      { name: WORKSHEET_TYPE.UNLOADING.name, value: WORKSHEET_TYPE.UNLOADING.value },
      { name: WORKSHEET_TYPE.PUTAWAY.name, value: WORKSHEET_TYPE.PUTAWAY.value }
    ]
    const _worksheetStatus = await getCodeByName('WORKSHEET_STATUS')
    const partners = await this._fetchPartners()

    this._searchFields = [
      {
        name: 'arrivalNoticeNo',
        label: i18next.t('field.arrival_notice'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        name: 'arrivalNoticeRefNo',
        label: i18next.t('field.ref_no'),
        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: 'type',
        label: i18next.t('label.type'),
        type: 'select',
        options: [
          { value: '' },
          ..._worksheetTypes.map(type => {
            return { name: i18next.t(`${type.name}`), value: type.value }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        name: 'status',
        label: i18next.t('label.status'),
        type: 'select',
        options: [
          { value: '' },
          ..._worksheetStatus.map(status => {
            return { name: i18next.t(`label.${status.description}`), value: status.name }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.cross_docking'),
        name: 'arrivalNoticeCrossDocking',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.from_date'),
        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_date'),
        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]
      }
    ]

    this.config = {
      list: {
        fields: [
          'arrivalNotice',
          'bizplace',
          'type',
          'arrivalRefNo',
          'status',
          'createdAt',
          'startedAt',
          'endedAt',
          'updater',
          'updatedAt'
        ]
      },
      rows: { appendable: false, selectable: { multiple: true } },
      pagination: { limit: 100, pages: [20, 50, 100, 200, 500] },
      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) => {
              if (!record.id) return
              const type = record.type

              // Handle UNLOADING
              if (type === WORKSHEET_TYPE.UNLOADING.value) {
                navigate(`worksheet_unloading/${record.name}`)

                // Handle PUTAWAY
              } else if (type === WORKSHEET_TYPE.PUTAWAY.value) {
                navigate(`worksheet_putaway/${record.name}`)
                // Handle VAS
                //vas --inbound
              } else if (type === WORKSHEET_TYPE.VAS.value) {
                navigate(`worksheet_vas/${record.name}`)
              }
            }
          }
        },
        {
          type: 'object',
          name: 'arrivalNotice',
          header: i18next.t('field.arrival_notice'),
          label: true,
          sortable: true,
          width: 160
        },
        {
          type: 'string',
          name: 'arrivalRefNo',
          header: i18next.t('field.ref_no'),
          label: true,
          sortable: true,
          width: 120
        },
        {
          type: 'boolean',
          name: 'arrivalNoticeCrossDocking',
          header: i18next.t('field.cross_docking'),
          label: true,
          width: 100
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          label: true,
          sortable: true,
          width: 200
        },
        {
          type: 'string',
          name: 'type',
          header: i18next.t('field.type'),
          label: true,
          sortable: true,
          width: 120
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          label: true,
          sortable: true,
          width: 120
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          label: true,
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'startedAt',
          header: i18next.t('field.started_at'),
          label: true,
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'endedAt',
          header: i18next.t('field.ended_at'),
          label: true,
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          label: true,
          sortable: true,
          width: 200
        }
      ]
    }
  }

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

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

  async fetchHandler({ page, limit, sorters = [{ name: 'createdAt', desc: true }] }) {
    const filters = this.searchForm.queryFilters
    if (!filters.find(filter => filter.name === 'type')) {
      filters.push({
        name: 'type',
        operator: 'in',
        value: [WORKSHEET_TYPE.UNLOADING.value, WORKSHEET_TYPE.PUTAWAY.value]
      })
    }

    const response = await client.query({
      query: gql`
        query worksheets($filters: [Filter!]!, $pagination: Pagination, $sortings: [Sorting!]!) {
          worksheets(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              arrivalNotice {
                id
                name
                description
                refNo
                crossDocking
              }
              bizplace {
                id
                name
                description
              }
              type
              status
              createdAt
              startedAt
              endedAt
              updater {
                name
                description
              }
              updatedAt
            }
            total
          }
        }
      `,
      variables: { filters, pagination: { page, limit }, sortings: sorters }
    })

    if (!response.errors) {
      return {
        total: response.data.worksheets.total || 0,
        records:
          response.data.worksheets.items.map(item => {
            return {
              ...item,
              arrivalRefNo: item.arrivalNotice.refNo || '',
              arrivalNoticeCrossDocking: item.arrivalNotice.crossDocking
            }
          }) || {}
      }
    }
  }

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

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

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

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

      var headerSetting = [
        { header: i18next.t('field.order_no'), key: 'orderNo', width: 25, type: 'string' },
        { header: i18next.t('field.company'), key: 'bizplaceName', width: 25, type: 'string' },
        { header: i18next.t('field.ref_no'), key: 'arrivalRefNo', width: 25, type: 'string' },
        { header: i18next.t('field.cross_docking'), key: 'arrivalNoticeCrossDocking', width: 30, type: 'string' },
        { header: i18next.t('field.type'), key: 'type', width: 25, type: 'string' },
        { 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.started_at'), key: 'startedAt', width: 30, type: 'date' },
        { header: i18next.t('field.ended_at'), key: 'endedAt', width: 30, type: 'date' },
        { header: i18next.t('field.updated_at'), key: 'updatedAt', width: 30, type: 'date' },
        { header: i18next.t('field.updater'), key: 'updaterName', width: 25, type: 'string' }
      ]

      if (this.dataGrist.selected && this.dataGrist.selected.length > 0) {
        data = this.dataGrist.selected.map(record => {
          return {
            ...record,
            orderNo: record.arrivalNotice?.name,
            bizplaceName: record.bizplace?.name,
            updaterName: record.updater?.name
          }
        })
      } else {
        data = (await this.fetchHandler({ page: 1, limit: 9999999 })).records.map(record => {
          return {
            ...record,
            orderNo: record.arrivalNotice?.name,
            bizplaceName: record.bizplace?.name,
            updaterName: record.updater?.name
          }
        })
      }

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

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

window.customElements.define('inbound-worksheet', InboundWorksheet)
