import '@things-factory/grist-ui'
import { MultiColumnFormStyles } from '@things-factory/form-ui'
import { openPopup } from '@things-factory/layout-base'
import { client, CustomAlert } from '@things-factory/shell'
import { i18next, localize } from '@things-factory/i18n-base'
import { isMobileDevice } from '@things-factory/utils'
import { css, html, LitElement } from 'lit-element'
import gql from 'graphql-tag'
import { ScrollbarStyles } from '@things-factory/styles'
import { ORDER_STATUS } from '../../constants'
import '@things-factory/biz-ui'

class BatchGenerateSinglePickingWorksheetPopup extends localize(i18next)(LitElement) {
  static get properties() {
    return {
      _searchFields: Array,
      config: Object,
      data: Object
    }
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background-color: white;
          padding: var(--padding-default);
        }
        search-form {
          overflow: visible;
        }
        .grist {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        .grist-container {
          overflow-y: hidden;
          display: flex;
          flex: 1;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        h2 {
          padding: var(--subtitle-padding);
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
          border-bottom: var(--subtitle-border-bottom);
        }
        .grist h2 {
          font: var(--grist-title-font);
        }
        .button-container {
          padding: var(--button-container-padding);
          margin: var(--button-container-margin);
          text-align: var(--button-container-align);
          background-color: var(--button-container-background);
          height: var(--button-container-height);
        }
      `
    ]
  }

  submit() {
    this.dispatchEvent(new CustomEvent('submit'))
  }

  render() {
    return html`
      <search-form .fields=${this._searchFields} @submit=${() => this.releaseOrderGrist.fetch()}></search-form>

      <div class="grist-container">
        <div class="grist">
          <h2>${i18next.t('title.release_order')}</h2>
          <data-grist
            id="releaseOrder"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.roConfig}
            .fetchHandler="${this.fetchReadyToPickOrders.bind(this)}"
          ></data-grist>
        </div>
      </div>

      <div class="button-container">
        <mwc-button
          @click="${this.generatePickingWorksheet.bind(this)}"
          raised
          label="${i18next.t('button.generate_worksheet')}"
        ></mwc-button>
      </div>
    `
  }

  async firstUpdated() {
    const partners = await this._fetchPartners()
    this._searchFields = [
      {
        label: i18next.t('field.company'),
        name: 'bizplace',
        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' }
      },
      {
        label: i18next.t('field.release_date'),
        name: 'releaseDate',
        type: 'date',
        props: { searchOper: 'lte' }
      }
    ]

    this.roConfig = {
      pagination: { pages: [100, 200, 300, 500], limit: 200 },
      rows: {
        selectable: { multiple: true },
        appendable: false
      },
      list: { fields: ['name', 'refNo', 'bizplace', 'releaseDate'] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.release_good_no'),
          width: 150
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          width: 130
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          width: 200
        },
        {
          type: 'date',
          name: 'releaseDate',
          header: i18next.t('field.release_date'),
          sortable: true,
          width: 150
        }
      ]
    }
  }

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

  get releaseOrderGrist() {
    return this.shadowRoot.querySelector('data-grist#releaseOrder')
  }

  get orderInventoryGrist() {
    return this.shadowRoot.querySelector('data-grist#orderInventory')
  }

  async _fetchPartners() {
    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
    }
  }

  async fetchReadyToPickOrders({ page, limit, sorters = [{ name: 'releaseDate' }] }) {
    // if (!this.partnerBizplace) return { total: 0, records: [] }

    const filters = [
      ...(await this.searchForm.getQueryFilters()).filter(x => x.name != 'partnerBizplace'),
      { name: 'status', operator: 'eq', value: ORDER_STATUS.PENDING_WORKSHEET.value },
      { name: 'crossDocking', operator: 'eq', value: false }
    ]

    if (this.partnerBizplace) {
      filters.push({ name: 'bizplaceId', operator: 'eq', value: this.partnerBizplace.id })
    }

    const pagination = { page, limit }
    const sortings = 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
              name
              refNo
              releaseDate
              type
              bizplace {
                id
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: { filters, pagination, sortings }
    })
    if (!response.errors) {
      return {
        total: response.data.releaseGoodRequests.total || 0,
        records: response.data.releaseGoodRequests.items || []
      }
    }
  }

  async generatePickingWorksheet() {
    try {
      let releaseGoodNos = []
      releaseGoodNos = this.releaseOrderGrist.selected.map(record => record.name)

      if (releaseGoodNos.length <= 0) throw new Error('Please select one or more order to generate worksheet')

      let result = await CustomAlert({
        title: i18next.t('title.are_you_sure'),
        text: i18next.t('text.generate_worksheet'),
        confirmButton: { text: i18next.t('button.submit') },
        cancelButton: { text: i18next.t('button.cancel') }
      })

      if (!result.value) return

      const response = await client.mutate({
        mutation: gql`
          mutation generateMultipleReleaseGoodWorksheet($releaseGoodNos: [String!]) {
            generateMultipleReleaseGoodWorksheet(releaseGoodNos: $releaseGoodNos)
          }
        `,
        variables: {
          releaseGoodNos
        }
      })

      if (!response.errors) {
        this.dispatchEvent(new CustomEvent('generated'))
        history.back()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

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

  _showToast({ type, message }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message
        }
      })
    )
  }
}
window.customElements.define('batch-generate-single-picking-worksheet-popup', BatchGenerateSinglePickingWorksheetPopup)
