import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import '../batch-picking-popup'
import '../batch-generate-single-picking-worksheet-popup'

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 { openPopup } from '@things-factory/layout-base'
import { client, navigate, PageView } from '@things-factory/shell'
import { CommonButtonStyles, ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

import { applyParamsToFields } from '../../../../util'
import { ORDER_STATUS } from '../../../constants'

class B2bOrderRequests 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.release_order_requests'),
      actions: [
        {
          title: i18next.t('button.batch_picking'),
          action: this._openBatchPickingPopup.bind(this),
          ...CommonButtonStyles.activate
        },
        {
          title: i18next.t('button.generate_worksheet'),
          action: this._openBatchGenerateSinglePickingWorksheetPopup.bind(this),
          ...CommonButtonStyles.activate
        }
      ],
      exportable: {
        name: i18next.t('title.release_order_requests'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/release-order/ro-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 (this.active) {
      let { params } = lifecycle
      if (params && this._searchFields) {
        if (params.range) {
          params.toDate = new Date().toISOString().split('T')[0]
          switch (params.range) {
            case '1d':
              params.fromDate = new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().split('T')[0]
              break
            case '1w':
              params.fromDate = new Date(new Date().setDate(new Date().getDate() - 7)).toISOString().split('T')[0]
              break
            case '1m':
              params.fromDate = new Date(new Date().setMonth(new Date().getMonth() - 1)).toISOString().split('T')[0]
              break
            default:
              break
          }
        }
        const updatedFields = applyParamsToFields(this._searchFields, params)
        this._searchFields = updatedFields
        const searchForm = this.searchForm
        if (searchForm) {
          searchForm.fields = updatedFields
        }
      }
      this.dataGrist.fetch()
    }
  }

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

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

    this._searchFields = [
      {
        label: i18next.t('field.ro'),
        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.release_date'),
        name: 'releaseDate',
        type: 'date',
        props: { searchOper: 'i_like' }
      },
      {
        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.export_option'),
        name: 'exportOption',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.own_transport'),
        name: 'ownTransport',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      }
    ]

    this.config = {
      rows: { selectable: { multiple: true }, appendable: false },
      list: { fields: ['name', 'bizplace', 'releaseDate', 'status', 'updatedAt'] },
      pagination: { limit: 100, pages: [20, 50, 100, 200, 500] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              const status = record.status
              navigate(`release_order_detail/${record.name}`)
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.ro'),
          imex: { header: i18next.t('field.ro'), key: 'name', width: 30, 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: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          imex: { header: i18next.t('field.ref_no'), key: 'refNo', width: 20, type: 'string' },
          sortable: true,
          width: 160
        },
        {
          type: 'string',
          name: 'refNo2',
          header: i18next.t('field.ref_no_2'),
          imex: { header: i18next.t('field.ref_no_2'), key: 'refNo2', width: 20, type: 'string' },
          sortable: true,
          width: 160
        },
        {
          type: 'string',
          name: 'refNo3',
          header: i18next.t('field.ref_no_3'),
          imex: { header: i18next.t('field.ref_no_3'), key: 'refNo3', width: 20, type: 'string' },
          sortable: true,
          width: 160
        },
        {
          type: 'date',
          name: 'releaseDate',
          header: i18next.t('field.release_date'),
          imex: { header: i18next.t('field.release_date'), key: 'releaseDate', width: 20, type: 'string' },
          sortable: true,
          width: 120
        },
        {
          type: 'boolean',
          name: 'exportOption',
          header: i18next.t('field.export_option'),
          imex: { header: i18next.t('field.export_option'), key: 'exportOption', width: 20, type: 'string' },
          sortable: true,
          width: 60
        },
        {
          type: 'boolean',
          name: 'ownTransport',
          header: i18next.t('field.own_transport'),
          imex: { header: i18next.t('field.own_transport'), key: 'ownTransport', width: 20, type: 'string' },
          sortable: true,
          width: 60
        },
        {
          type: 'boolean',
          name: 'crossDocking',
          header: i18next.t('field.cross_docking'),
          imex: { header: i18next.t('field.cross_docking'), key: 'crossDocking', width: 20, type: 'string' },
          width: 60
        },
        {
          type: 'object',
          name: 'arrivalNotice',
          header: i18next.t('field.gan'),
          imex: { header: i18next.t('field.gan'), key: 'arrivalNotice.name', width: 30, type: 'string' },
          width: 160
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          imex: { header: i18next.t('field.status'), key: 'status', width: 30, type: 'string' },
          sortable: true,
          width: 120
        },
        {
          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: 200
        },
        {
          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: 'acceptedBy',
          header: i18next.t('field.accepted_by'),
          imex: { header: i18next.t('field.accepted_by'), key: 'acceptedBy.name', width: 30, type: 'string' },
          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 = [] }) {
    const response = await client.query({
      query: gql`
        query releaseGoodRequests($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          releaseGoodRequests(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              bizplace {
                id
                name
                description
              }
              name
              releaseDate
              status
              refNo
              refNo2
              refNo3
              ownTransport
              crossDocking
              arrivalNotice {
                id
                name
                description
              }
              exportOption
              createdAt
              updatedAt
              acceptedBy {
                id
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: {
        filters: [...(await this.searchForm.getQueryFilters()), { name: 'type', operator: 'eq', value: 'b2b' }],
        pagination: { page, limit },
        sortings: sorters
      }
    })

    if (!response.errors) {
      return {
        total: response.data.releaseGoodRequests.total || 0,
        records: response.data.releaseGoodRequests.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
    }
  }

  _openBatchPickingPopup() {
    openPopup(
      html`
        <batch-picking-popup
          @generated="${() => {
            navigate('merged_outbound_worksheets')
            this._showToast({ message: i18next.t('text.worksheet_has_been_generated') })
          }}"
        ></batch-picking-popup>
      `,
      {
        backdrop: true,
        size: 'large',
        title: i18next.t('title.generate_batch_picking')
      }
    )
  }

  _openBatchGenerateSinglePickingWorksheetPopup() {
    openPopup(
      html`
        <batch-generate-single-picking-worksheet-popup
          @generated="${() => {
            this._showToast({ message: i18next.t('text.orders_has_been_activated') })
            this.dataGrist.fetch()
          }}"
        ></batch-generate-single-picking-worksheet-popup>
      `,
      {
        backdrop: true,
        size: 'large',
        title: i18next.t('title.generate_picking_worksheet')
      }
    )
  }

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

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

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

  _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.record !== undefined */ && 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()
            }
            return record
          }, {})
      }
    })
    return { header: headerSetting, data: data }
  }
}

window.customElements.define('b2b-order-requests', B2bOrderRequests)
