import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import '../inventory/inventory-by-product-detail'

import gql from 'graphql-tag'
import { css, html } from 'lit-element'
import { connect } from 'pwa-helpers/connect-mixin'

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

import { showToast } from '../../util'

function formatLocalDate(date = new Date()) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

class shortageReport extends connect(store)(localize(i18next)(PageView)) {
  static get styles() {
    return [
      // ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          width: 100%;
        }

        data-grist {
          overflow-y: auto;
          flex: 1;
        }

        .summary {
          background-color: var(--main-section-background-color);
          display: flex;
          flex-direction: column;
          overflow-y: auto;
          align-items: flex-end;
          padding: var(--data-list-item-padding);
          display: grid;
          font-size: 14px;
          color: #394e64;
          grid-template-columns: repeat(2, 1fr);
          grid-auto-rows: minmax(24px, auto);
        }
      `
    ]
  }

  static get properties() {
    return {
      _searchFields: Array,
      _config: Object,
      _gristData: Object,
      _partners: Object,
      items: Object
      // importHandler: Object
    }
  }

  get context() {
    return {
      title: i18next.t('Shortage Report'),
      exportable: {
        name: i18next.t('Shortage Report'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/report/shortage-report'
    }
  }

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

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

  get _bizplaceSelector() {
    return this.searchForm.shadowRoot.querySelector('select[name=bizplace]')
  }

  get _fromDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=fromDate]')
  }

  get _toDateInput() {
    return this.searchForm.shadowRoot.querySelector('input[name=toDate]')
  }

  render() {
    return html`
      <search-form
        id="search-form"
        .fields=${this._searchFields}
        initFocus="description"
        @submit=${e => this.dataGrist.fetch()}
      ></search-form>

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

  get searchFields() {
    return [
      {
        label: i18next.t('Company'),
        name: 'bizplace',
        type: 'select',
        options: [
          { value: '' },
          ...this._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.from_date'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          max: formatLocalDate(new Date())
        },
        value: (() => {
          let date = new Date()
          date.setMonth(date.getMonth() - 1)
          return formatLocalDate(date)
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to_date'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          min: (() => {
            let date = new Date()
            date.setMonth(date.getMonth() - 1)
            return formatLocalDate(date)
          })(),
          max: formatLocalDate(new Date())
        },
        value: formatLocalDate(new Date()),
        handlers: { change: this._submit.bind(this) }
      },
      {
        label: i18next.t('field.product_info'),
        name: 'product',
        type: 'string',
        props: { searchOper: 'in' }
      },
      {
        label: i18next.t('field.order_no'),
        name: 'orderNo',
        type: 'text',
        props: { searchOper: 'custom' }
      }
    ]
  }

  get reportConfig() {
    // let rows = {
    //   selectable: false,
    //   insertable: false,
    //   appendable: false
    // }
    let columns = [
      { type: 'gutter', gutterName: 'sequence' },
      {
        type: 'string',
        name: 'bizplaceName',
        header: i18next.t('field.company'),
        width: 200
      },
      {
        type: 'string',
        name: 'orderNo',
        header: i18next.t('field.order_no'),
        width: 200
      },
      {
        type: 'string',
        name: 'refNo',
        header: i18next.t('field.ref_no'),
        width: 150
      },
      {
        type: 'string',
        name: 'productSku',
        header: i18next.t('field.sku'),
        width: 200
      },
      {
        type: 'string',
        name: 'productName',
        header: i18next.t('field.product'),
        width: 200
      },
      {
        type: 'string',
        name: 'orderQty',
        header: i18next.t('field.order_quantity'),
        width: 170
      },
      {
        type: 'string',
        name: 'avQty',
        header: i18next.t('field.available_qty'),
        width: 150
      },
      {
        type: 'string',
        name: 'nettStock',
        header: i18next.t('field.nett_stock'),
        width: 150
      },
      {
        type: 'datetime',
        name: 'createdAt',
        header: i18next.t('field.created_at'),
        width: 170
      }
    ]
    let list = {
      fields: [
        'bizplaceName',
        'orderNo',
        'refNo',
        'productSku',
        'productName',
        'orderQty',
        'avQty',
        'nettStock',
        'createdAt'
      ]
    }

    return {
      // rows: rows,
      columns: columns,
      list,
      pagination: { limit: 50, pages: [50, 100, 200, 500, 1000] },
      rows: {
        selectable: false,
        insertable: false,
        appendable: false
      }
    }
  }

  async pageInitialized() {
    this._gristData = { total: 0, records: [] }
    this._products = []

    const [_partnersReq] = await Promise.allSettled([this._fetchPartners()])

    this._partners = _partnersReq.status == 'fulfilled' ? _partnersReq.value : []

    this._searchFields = this.searchFields
    this._config = this.reportConfig
  }

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

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      this._validate()
      let filters = this.searchForm.queryFilters.map(filter => {
        switch (filter.name) {
          case 'fromDate':
            let fromDt = new Date(filter.value)
            fromDt.setHours(0)
            filter.value = fromDt.toISOString()
            break
          case 'toDate':
            let toDt = new Date(filter.value)
            toDt.setHours(23, 59, 59)
            filter.value = toDt.toISOString()
            break
          default:
            break
        }
        return filter
      })

      const pagination = { page, limit }
      const sortings = sorters

      const response = await client.query({
        query: gql`
          query shortageReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            shortageReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                bizplaceName
                orderNo
                refNo
                productSku
                productName
                productDescription
                orderQty
                avQty
                nettStock
                deliveryAddress
                state
                city
                country
                createdAt
              }
              total
            }
          }
        `,
        variables: { filters, pagination, sortings },
        context: gqlContext()
      })

      return {
        total: response.data.shortageReport.total || 0,
        records: response.data.shortageReport.items || []
      }

      this._gristData = {
        ...items
      }

      return items
    } catch (e) {
      showToast(e)
    }
  }

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

  _validate() {
    if (!this.searchForm.shadowRoot.querySelector('form').checkValidity())
      throw new Error(i18next.t('text.invalid_form_value'))
    if (!this._bizplaceSelector.value) throw new Error(i18next.t('text.no_company_selected'))
    if (!this._fromDateInput.value) throw new Error(i18next.t('text.from_date_is_empty'))
    if (!this._toDateInput.value) throw new Error(i18next.t('text.to_date_is_empty'))
  }

  _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
    this._submit()
  }

  _submit(e) {
    this._config = { ...this.reportConfig }
    this.searchForm.submit()
  }

  async _exportableData() {
    try {
      var headerSetting = [
        { header: i18next.t('field.company'), key: 'bizplaceName', width: 60, type: 'string' },
        { header: i18next.t('field.order_no'), key: 'orderNo', width: 30, type: 'string' },
        { header: i18next.t('field.ref_no'), key: 'refNo', width: 60, type: 'string' },
        { header: i18next.t('field.sku'), key: 'productSku', width: 25, type: 'string' },
        { header: i18next.t('field.product'), key: 'productName', width: 25, type: 'string' },
        { header: i18next.t('field.product_description'), key: 'productDescription', width: 25, type: 'string' },
        { header: i18next.t('field.order_quantity'), key: 'orderQty', width: 15, type: 'string' },
        { header: i18next.t('field.available_qty'), key: 'avQty', width: 15, type: 'string' },
        { header: i18next.t('field.nett_stock'), key: 'nettStock', width: 15, type: 'string' },
        { header: i18next.t('field.delivery_address'), key: 'deliveryAddress', width: 15, type: 'string' },
        { header: i18next.t('field.state'), key: 'state', width: 15, type: 'string' },
        { header: i18next.t('field.city'), key: 'city', width: 15, type: 'string' },
        { header: i18next.t('field.country'), key: 'country', width: 15, type: 'string' },
        { header: i18next.t('field.created_at'), key: 'createdAt', width: 30, type: 'string' }
      ]

      var exportData = {
        header: [...headerSetting],
        data: (await this.fetchHandler({ page: 1, limit: 9999999 })).records.map(itm => {
          return {
            ...itm,
            createdAt: itm.createdAt ? new Date(parseInt(itm.createdAt)).toLocaleString() : ''
          }
        })
      }

      return exportData
    } catch (e) {
      this._showToast(e)
    }
  }

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

window.customElements.define('shortage-report', shortageReport)
