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 { ORDER_STATUS } from '../../constants'

class ArrivalNoticeRequests 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.arrival_notice_requests'),
      exportable: {
        name: i18next.t('title.arrival_notice_requests'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/arrival-notice/arrival-notice-requests'
    }
  }

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

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

  pageUpdated(changes, lifecycle) {
    if (changes?.params) {
      this.fillUpSearchForm(changes.params)
    }

    if (this.active) {
      this.dataGrist.fetch()
    }
  }

  fillUpSearchForm(params) {
    for (let fieldName in params) {
      const input = this.searchForm.shadowRoot.querySelector(`[name=${fieldName}]`)
      if (input) {
        input.value = params[fieldName]
      }
    }
  }

  async pageInitialized() {
    const [_orderStatusReq, _bizplacesReq] = await Promise.allSettled([
      getCodeByName('GAN_REQUESTS_STATUS'),
      this._fetchBizplaces()
    ])

    const _orderStatus = _orderStatusReq.status == 'fulfilled' ? _orderStatusReq.value : []
    const _bizplaces = _bizplacesReq.status == 'fulfilled' ? _bizplacesReq.value : []

    this._searchFields = [
      {
        label: i18next.t('field.gan'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.company'),
        name: 'bizplaceId',
        type: 'select',
        options: [
          { value: '' },
          ..._bizplaces
            .map(bizplace => {
              return {
                name: `${bizplace.name} ${bizplace.description ? `(${bizplace.description})` : ''}`,
                value: bizplace.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.eta'),
        name: 'etaDate',
        type: 'date',
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.ref_no'),
        name: 'refNo',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.ref_no_2'),
        name: 'refNo2',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.ref_no_3'),
        name: 'refNo3',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.status'),
        name: 'status',
        type: 'select',
        options: [
          { value: '' },
          ..._orderStatus.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.container'),
        name: 'container',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.own_transport'),
        name: 'ownTransport',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.cross_docking'),
        name: 'crossDocking',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      }
    ]

    this.config = {
      rows: { appendable: false, selectable: { multiple: true } },
      list: {
        fields: [
          'name',
          'bizplace',
          'refNo',
          'refNo2',
          'refNo3',
          'etaDate',
          'container',
          'importCargo',
          'ownTransport',
          'crossDocking',
          'status',
          'createdAt',
          'updatedAt',
          'acceptedBy'
        ]
      },
      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) => {
              const status = record.status
              if (status === ORDER_STATUS.PENDING_RECEIVE.value) {
                navigate(`receive_arrival_notice/${record.name}`) // 1. move to order receiving page
              } else if (status === ORDER_STATUS.INTRANSIT.value) {
                navigate(`check_arrived_notice/${record.name}`) // 2. move to order arriving check page
              } else if (status === ORDER_STATUS.ARRIVED.value) {
                navigate(`assign_buffer_location/${record.name}`) // 3. move to assign buffer location
              } else {
                navigate(`arrival_notice_detail/${record.name}`)
              }
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.gan'),
          label: true,
          sortable: true,
          width: 180
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          label: true,
          sortable: true,
          width: 250
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo2',
          header: i18next.t('field.ref_no_2'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo3',
          header: i18next.t('field.ref_no_3'),
          label: true,
          sortable: true,
          width: 150
        },
        {
          type: 'date',
          name: 'etaDate',
          header: i18next.t('field.eta'),
          label: true,
          sortable: true,
          width: 120
        },
        {
          type: 'boolean',
          name: 'container',
          header: i18next.t('field.container'),
          label: true,
          sortable: true,
          width: 60
        },
        {
          type: 'boolean',
          name: 'importCargo',
          header: i18next.t('field.import_cargo'),
          label: true,
          sortable: true,
          width: 60
        },
        {
          type: 'boolean',
          name: 'ownTransport',
          header: i18next.t('field.own_transport'),
          label: true,
          sortable: true,
          width: 60
        },
        {
          type: 'boolean',
          name: 'crossDocking',
          header: i18next.t('field.cross_docking'),
          label: true,
          width: 60
        },
        {
          type: 'object',
          name: 'releaseGood',
          header: i18next.t('field.ro'),
          label: true,
          width: 160
        },
        {
          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: 'updatedAt',
          header: i18next.t('field.updated_at'),
          label: true,
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'acceptedBy',
          header: i18next.t('field.accepted_by'),
          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: 'updatedAt', desc: true }] }) {
    const response = await client.query({
      query: gql`
        query arrivalNoticeRequests($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          arrivalNoticeRequests(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              bizplace {
                name
                description
              }
              name
              etaDate
              refNo
              refNo2
              refNo3
              status
              ownTransport
              container
              crossDocking
              releaseGood {
                name
              }
              importCargo
              createdAt
              updatedAt
              acceptedBy {
                id
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: { filters: await this.searchForm.getQueryFilters(), pagination: { page, limit }, sortings: sorters }
    })

    if (!response.errors) {
      return {
        total: response.data.arrivalNoticeRequests.total || 0,
        records: response.data.arrivalNoticeRequests.items || []
      }
    }
  }

  async _fetchBizplaces() {
    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: 'name', width: 25, type: 'string' },
        { header: i18next.t('field.company'), key: 'bizplaceName', width: 25, type: 'string' },
        { header: i18next.t('field.ref_no'), key: 'refNo', 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.eta_date'), key: 'etaDate', width: 30, type: 'string' },
        { header: i18next.t('field.container'), key: 'container', width: 30, type: 'string' },
        { header: i18next.t('field.import_cargo'), key: 'importCargo', width: 30, type: 'string' },
        { header: i18next.t('field.cross_docking'), key: 'crossDocking', width: 30, 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.updated_at'), key: 'updatedAt', width: 30, type: 'date' },
        { header: i18next.t('field.accepted_by'), key: 'acceptedByName', width: 25, type: 'string' }
      ]

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

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

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

window.customElements.define('arrival-notice-requests', ArrivalNoticeRequests)
