import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import { client, navigate, PageView } from '@things-factory/shell'
import { css, html } from 'lit-element'
import { getCodeByName } from '@things-factory/code-base'
import { isMobileDevice } from '@things-factory/utils'
import { i18next, localize } from '@things-factory/i18n-base'
import { ORDER_STATUS } from '../../constants'
import { ScrollbarStyles } from '@things-factory/styles'
import gql from 'graphql-tag'

class TransferOrderRequests 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.transfer_order_requests'),
      exportable: {
        name: i18next.t('title.transfer_order_requests'),
        data: this._exportableData.bind(this)
      }
    }
  }

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

  async pageInitialized() {
    const _orderStatus = await getCodeByName('TO_REQUESTS_STATUS')
    const _transferTypes = await getCodeByName('TO_TYPES')
    const _userBizplaces = await this.fetchBizplaces()

    this._searchFields = [
      {
        label: i18next.t('field.to_no'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.retail_outlet'),
        name: 'bizplaceId',
        type: 'select',
        options: [
          { value: '' },
          ..._userBizplaces
            .filter(userBizplaces => !userBizplaces.mainBizplace)
            .map(userBizplace => {
              return {
                name: userBizplace.name,
                value: userBizplace.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.issued_date'),
        name: 'issuedDate',
        type: 'date',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.ref_no'),
        name: 'refNo',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.type'),
        name: 'type',
        type: 'select',
        options: [
          { value: '' },
          ..._transferTypes.map(type => {
            return { name: i18next.t(`label.${type.description}`), value: type.name }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.own_transport'),
        name: 'ownTransport',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        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' }
      }
    ]

    this.config = {
      rows: { selectable: { multiple: true }, appendable: false },
      list: { fields: ['name', 'bizplace', 'issuedDate', 'status', 'updatedAt'] },
      columns: [
        { type: 'gutter', gutterName: 'dirty' },
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              const status = record.status
              if (status === ORDER_STATUS.PENDING_RECEIVE.value || status === ORDER_STATUS.PENDING_CANCEL.value) {
                navigate(`receive_transfer_order_request/${record.name}`)
              } else {
                navigate(`transfer_order_detail/${record.name}`)
              }
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.transfer_order_no'),
          record: { align: 'left' },
          sortable: true,
          width: 200
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.retail_outlet'),
          record: { align: 'left' },
          sortable: true,
          width: 300
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          record: { align: 'left' },
          sortable: true,
          width: 160
        },
        {
          type: 'string',
          name: 'type',
          header: i18next.t('field.type'),
          record: { align: 'left' },
          sortable: true,
          width: 130
        },
        {
          type: 'date',
          name: 'issuedDate',
          header: i18next.t('field.issued_date'),
          record: { align: 'center' },
          sortable: true,
          width: 120
        },
        {
          type: 'boolean',
          name: 'ownTransport',
          header: i18next.t('field.own_transport'),
          record: { align: 'center' },
          sortable: true,
          width: 60
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          record: { align: 'left' },
          sortable: true,
          width: 120
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          record: { align: 'center' },
          sortable: true,
          width: 160
        }
      ]
    }
  }

  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 transferOrders($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          transferOrders(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              bizplace {
                name
                description
              }
              name
              issuedDate
              status
              refNo
              type
              ownTransport
              orderInventories {
                batchId
                status
                product {
                  sku
                  name
                  description
                }
              }
              updatedAt
            }
            total
          }
        }
      `,
      variables: {
        filters: await this.searchForm.getQueryFilters(),
        pagination: { page, limit },
        sortings: sorters
      }
    })

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

  async fetchBizplaces(bizplace = []) {
    const response = await client.query({
      query: gql`
        query bizplaces($filters: [Filter!]) {
          bizplaces(filters: $filters) {
            items {
              id
              name
              description
            }
          }
        }
      `,
      variables: {
        filters: [...bizplace]
      }
    })
    return response.data.bizplaces.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
    }
  }

  _exportableData() {
    return this.dataGrist.exportRecords()
  }
}

window.customElements.define('transfer-order-requests', TransferOrderRequests)
