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'

class ExternalReturnWorksheet 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.external_return_worksheet'),
      exportable: {
        name: i18next.t('title.external_return_worksheet'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/inbound/external-return-worksheet'
    }
  }

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

  async pageInitialized() {
    const _worksheetStatus = await getCodeByName('WORKSHEET_STATUS')
    const partners = await this._fetchPartners()

    this._searchFields = [
      {
        name: 'returnOrderNo',
        label: i18next.t('field.return_order_no'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        name: 'returnOrderRefNo',
        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: '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' }
      }
    ]

    this.config = {
      list: {
        fields: ['returnOrder', 'bizplace', 'type', 'returnOrderRefNo', 'status', 'startedAt', 'endedAt']
      },
      rows: { appendable: false },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              if (!record.id) return
              const type = record.type

              if (type === WORKSHEET_TYPE.UNLOADING_RETURN.value) {
                navigate(`worksheet_unloading_return/${record.name}`)
              } else if (type === WORKSHEET_TYPE.PUTAWAY_RETURN.value) {
                navigate(`worksheet_putaway_return/${record.name}`)
              }
            }
          }
        },
        {
          type: 'object',
          name: 'returnOrder',
          header: i18next.t('field.return_order_no'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'returnOrderRefNo',
          header: i18next.t('field.ref_no'),
          sortable: true,
          width: 180
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          sortable: true,
          width: 240
        },
        {
          type: 'string',
          name: 'type',
          header: i18next.t('field.type'),
          sortable: true,
          width: 100
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          sortable: true,
          width: 100
        },
        {
          type: 'datetime',
          name: 'startedAt',
          header: i18next.t('field.started_at'),
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'endedAt',
          header: i18next.t('field.ended_at'),
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          sortable: true,
          width: 150
        }
      ]
    }
  }

  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
    filters.push({
      name: 'type',
      operator: 'in',
      value: [WORKSHEET_TYPE.UNLOADING_RETURN.value, WORKSHEET_TYPE.PUTAWAY_RETURN.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
              returnOrder {
                id
                name
                description
                refNo
              }
              bizplace {
                id
                name
                description
              }
              name
              type
              status
              startedAt
              createdAt
              endedAt
              updater {
                name
                description
              }
            }
            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, returnOrderRefNo: item.returnOrder.refNo || '' }
          }) || {}
      }
    }
  }

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

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

  _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.return_order_no'), key: 'returnOrderName', width: 25, type: 'string' },
        { header: i18next.t('field.ref_no'), key: 'returnOrderRefNo', width: 25, type: 'string' },
        { header: i18next.t('field.company'), key: 'bizplaceName', width: 25, type: 'string' },
        { header: i18next.t('field.type'), key: 'type', width: 30, type: 'string' },
        { header: i18next.t('field.status'), key: 'status', width: 25, type: 'string' },
        { header: i18next.t('field.started_at'), key: 'startedAt', width: 30, type: 'date' },
        { header: i18next.t('field.ended_at'), key: 'endedAt', width: 25, type: 'date' },
        { header: i18next.t('field.updated_by'), key: 'updaterName', width: 25, type: 'string' }
      ]

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

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

window.customElements.define('external-return-worksheet', ExternalReturnWorksheet)
