import '@things-factory/grist-ui'

import gql from 'graphql-tag'
import { css, html } from 'lit-element'

import { i18next, localize } from '@things-factory/i18n-base'
import { client, navigate, PageView } from '@things-factory/shell'
import { CommonButtonStyles, ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

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

class ReverseKittingOrderList extends localize(i18next)(PageView) {
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;

          overflow: hidden;
        }

        search-form {
          overflow: visible;
        }
        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
        }
        data-grist {
          overflow-y: hidden;
          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>

      <div class="grist">
        <data-grist
          .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
          .config=${this.config}
          .fetchHandler="${this.fetchHandler.bind(this)}"
        ></data-grist>
      </div>
    `
  }

  get context() {
    return {
      title: i18next.t('title.reverse_kitting_orders'),
      actions: [
        {
          title: i18next.t('button.create'),
          action: this._navigateToCreate.bind(this),
          ...CommonButtonStyles.submit
        }
      ],
      exportable: {
        name: i18next.t('title.reverse_kitting_orders'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/order/reverse-kitting-order/reverse-kitting-order-list'
    }
  }

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

  pageInitialized() {
    this._searchFields = [
      {
        label: i18next.t('field.order_no'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.status'),
        name: 'status',
        type: 'select',
        options: [
          { value: '' },
          { name: i18next.t(`label.${ORDER_STATUS.PENDING.name}`), value: ORDER_STATUS.PENDING.value },
          { name: i18next.t(`label.${ORDER_STATUS.PENDING_RECEIVE.name}`), value: ORDER_STATUS.PENDING_RECEIVE.value },
          {
            name: i18next.t(`label.${ORDER_STATUS.READY_TO_EXECUTE.name}`),
            value: ORDER_STATUS.READY_TO_EXECUTE.value
          },
          { name: i18next.t(`label.${ORDER_STATUS.EXECUTING.name}`), value: ORDER_STATUS.EXECUTING.value },
          { name: i18next.t(`label.${ORDER_STATUS.DONE.name}`), value: ORDER_STATUS.DONE.value }
        ],
        props: { searchOper: 'eq' }
      }
    ]

    this.config = {
      rows: { selectable: { multiple: true }, appendable: false },
      columns: [
        { type: 'gutter', gutterName: 'dirty' },
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              navigate(`reverse_kitting_order_detail/${record.name}`)
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.order_no'),
          sortable: true,
          width: 180
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          sortable: true,
          width: 150
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          sortable: true,
          width: 160
        }
      ]
    }
  }

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

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

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

  async fetchHandler({ page, limit, sorters = [{ name: 'createdAt', desc: true }] }) {
    const response = await client.query({
      query: gql`
        query reverseKittingOrders($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          reverseKittingOrders(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              status
              createdAt
              updatedAt
              creator {
                name
                description
              }
              updater {
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: {
        filters: this.searchForm.queryFilters,
        pagination: { page, limit },
        sortings: sorters
      }
    })

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

  _navigateToCreate() {
    navigate(`reverse_kitting_order_detail/new`)
  }

  _exportableData() {
    return {
      header: [
        { header: i18next.t('field.order_no'), key: 'name', width: 25, type: 'string' },
        { header: i18next.t('field.status'), key: 'status', width: 25, type: 'string' },
        { header: i18next.t('field.updated_at'), key: 'updatedAt', width: 30, type: 'date' },
        { header: i18next.t('field.updater'), key: 'updater', width: 25, type: 'string' }
      ],
      data: this.dataGrist?.data?.records?.map(record => {
        return { ...record, updater: record.updater.name }
      })
    }
  }
}

window.customElements.define('reverse-kitting-order-list', ReverseKittingOrderList)
