import '@things-factory/form-ui'
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, PageView } from '@things-factory/shell'
import { ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

import { CONDITION_OF_GOODS } from '../constants/order'

class InventoryHistory 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;
          overflow-y: auto;
        }

        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
      `
    ]
  }

  static get properties() {
    return {
      _searchFields: Array,
      config: Object,
      data: Object,
      exportItems: 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.inventory_histories'),
      actions: [],
      exportable: {
        name: i18next.t('title.inventory_histories'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/inventory/inventory-history'
    }
  }

  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]')
  }

  async pageInitialized() {
    const [partners, filterOptions] = await Promise.all([
      this._fetchPartners(),
      this._fetchInventoryHistoryFilterOptions()
    ])

    const { transactionTypes = [], statuses = [] } = filterOptions || {}

    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' },
        attrs: ['custom']
      },
      {
        label: i18next.t('field.from_date'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          max: new Date().toISOString().split('T')[0]
        },
        attrs: ['custom'],
        value: (() => {
          let date = new Date()
          date.setMonth(date.getMonth() - 1)
          return date.toISOString().split('T')[0]
        })(),
        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 date.toISOString().split('T')[0]
          })(),
          max: new Date().toISOString().split('T')[0]
        },
        attrs: ['custom'],
        value: new Date().toISOString().split('T')[0]
      },
      {
        label: i18next.t('field.product_info'),
        name: 'product_info',
        type: 'text',
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.zone'),
        name: 'zone',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.location'),
        name: 'locationName',
        type: 'text',
        props: { searchOper: 'i_like' },
        attrs: ['custom']
      },
      {
        label: i18next.t('field.lot_id'),
        name: 'palletId',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.carton_id'),
        name: 'cartonId',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.batch_id'),
        name: 'batchId',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.status'),
        name: 'status',
        type: 'select',
        options: [{ value: '' }, ...statuses.map(s => ({ name: s, value: s }))],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.transaction_type'),
        name: 'transactionType',
        type: 'select',
        options: [{ value: '' }, ...transactionTypes.map(t => ({ name: t, value: t }))],
        props: { searchOper: 'eq' }
      }
    ]

    this.config = {
      rows: { appendable: false },
      list: {
        fields: [
          'productSku',
          'product',
          'productBrand',
          'seq',
          'palletId',
          'cartonId',
          'batchId',
          'openingQty',
          'qty',
          'openingUomValue',
          'uomValue',
          'uom',
          'location',
          'updatedAt'
        ]
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'productSku',
          header: i18next.t('field.sku'),
          sortable: true,
          width: 200
        },
        {
          type: 'object',
          name: 'product',
          header: i18next.t('field.product'),
          sortable: true,
          width: 200
        },
        {
          type: 'string',
          name: 'productBrand',
          header: i18next.t('field.brand'),
          sortable: true,
          width: 200
        },
        {
          type: 'number',
          name: 'seq',
          header: i18next.t('field.seq'),
          sortable: true,
          width: 80
        },
        {
          type: 'string',
          name: 'palletId',
          header: i18next.t('field.lot_id'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'cartonId',
          header: i18next.t('field.carton_id'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_id'),
          sortable: true,
          width: 150
        },
        {
          type: 'number',
          name: 'openingQty',
          header: i18next.t('field.opening_qty'),
          sortable: true,
          width: 80
        },
        {
          type: 'number',
          name: 'qty',
          header: i18next.t('field.qty'),
          sortable: true,
          width: 80
        },
        {
          type: 'number',
          name: 'openingUomValue',
          header: i18next.t('field.opening_uom_value'),
          sortable: true,
          width: 100
        },
        {
          type: 'number',
          name: 'uomValue',
          header: i18next.t('field.uom_value'),
          sortable: true,
          width: 100
        },
        {
          type: 'string',
          name: 'uom',
          header: i18next.t('field.uom'),
          sortable: true,
          width: 80
        },
        {
          type: 'string',
          name: 'zone',
          header: i18next.t('field.zone'),
          sortable: true,
          width: 80
        },
        {
          type: 'object',
          name: 'location',
          header: i18next.t('field.location'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'conditionOfGoods',
          header: i18next.t('field.inventory_quality'),
          sortable: true,
          width: 150,
          record: {
            renderer: (value, column, record, rowIndex, field) => {
              const condition = Object.values(CONDITION_OF_GOODS).find(c => c.value === value)
              return condition ? i18next.t(`label.${condition.name}`) : value || ''
            }
          }
        },
        {
          type: 'string',
          name: 'batchIdRef',
          header: i18next.t('field.batch_no_ref'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'orderNo',
          header: i18next.t('field.order_no'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'orderRefNo',
          header: i18next.t('field.ref_no'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'transactionType',
          header: i18next.t('field.transaction_type'),
          sortable: true,
          width: 150
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          sortable: true,
          width: 150
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          sortable: true,
          width: 150
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          sortable: true,
          width: 150
        }
      ]
    }
  }

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

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

  async _fetchInventoryHistoryFilterOptions() {
    try {
      const response = await client.query({
        query: gql`
          query {
            inventoryHistoryFilterOptions {
              transactionTypes
              statuses
            }
          }
        `
      })

      if (!response.errors) return response.data.inventoryHistoryFilterOptions
    } catch (e) {
      console.error('Failed to fetch inventory history filter options', e)
    }

    return {}
  }

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

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      this._validate()
      let inventoryHistory = {}
      let filters = []
      const _customFields = this.searchForm.formFields
        .filter(field => field.hasAttribute('custom'))
        .map(field => field.name)

      var queryFilter = await this.searchForm.getQueryFilters()

      queryFilter.forEach(filter => {
        if (_customFields.includes(filter.name)) {
          switch (filter.name) {
            case 'bizplace':
              inventoryHistory[filter.name] = { id: filter.value }
              break
            case 'fromDate':
              let fromDt = new Date(filter.value)
              fromDt.setHours(0)
              inventoryHistory[filter.name] = fromDt.toISOString()
              break
            case 'toDate':
              let toDt = new Date(filter.value)
              toDt.setHours(23, 59, 59)
              inventoryHistory[filter.name] = toDt.toISOString()
              break
            default:
              if (filter.operator == 'i_like') {
                filter.value = `%${filter.value.replaceAll('%', '').trim()}%`
              } else {
                filter.value = filter.value.trim()
              }
              inventoryHistory[filter.name] = filter.value
              break
          }
        } else {
          if (filter.operator == 'i_like') {
            filter.value = `%${filter.value.replaceAll('%', '').trim()}%`
          } else {
            filter.value = filter.value.trim()
          }
          filters.push(filter)
        }
      })

      const response = await client.query({
        query: gql`
          query bizplaceInventoryHistories(
            $inventoryHistory: InventoryHistoryPatch
            $filters: [Filter!]
            $pagination: Pagination
            $sortings: [Sorting!]
          ) {
            bizplaceInventoryHistories(
              inventoryHistory: $inventoryHistory
              filters: $filters
              pagination: $pagination
              sortings: $sortings
            ) {
              items {
                seq
                palletId
                cartonId
                batchId
                batchIdRef
                orderRefNo
                orderNo
                bizplace {
                  id
                  name
                  description
                }
                product {
                  id
                  sku
                  brand
                  name
                  description
                }
                openingQty
                openingUomValue
                qty
                uom
                uomValue
                warehouse {
                  id
                  name
                  description
                }
                zone
                location {
                  id
                  name
                  description
                }
                conditionOfGoods
                status
                transactionType
                createdAt
                updatedAt
                updater {
                  id
                  name
                  description
                }
              }
              total
            }
          }
        `,
        variables: { inventoryHistory, filters: [...filters], pagination: { page, limit }, sortings: sorters }
      })

      return {
        total: response.data.bizplaceInventoryHistories.total || 0,
        records: (response.data.bizplaceInventoryHistories.items || []).map(item => {
          return {
            ...item,
            productSku: item.product.sku,
            productBrand: item.product.brand,
            productName: item.product.name,
            locationName: item.location.name,
            updaterName: item?.updater?.name ? item.updater.name : ''
          }
        })
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  async _fetchInventoryHistoriesForExport() {
    try {
      this._validate()

      let inventoryHistory = {}
      let filters = []
      const _customFields = this.searchForm.formFields
        .filter(field => field.hasAttribute('custom'))
        .map(field => field.name)

      var queryFilter = await this.searchForm.getQueryFilters()

      queryFilter.forEach(filter => {
        if (_customFields.includes(filter.name)) {
          switch (filter.name) {
            case 'bizplace':
              inventoryHistory[filter.name] = { id: filter.value }
              break
            case 'fromDate':
              let fromDt = new Date(filter.value)
              fromDt.setHours(0)
              inventoryHistory[filter.name] = fromDt.toISOString()
              break
            case 'toDate':
              let toDt = new Date(filter.value)
              toDt.setHours(23, 59, 59)
              inventoryHistory[filter.name] = toDt.toISOString()
              break
            default:
              inventoryHistory[filter.name] = filter.value
              break
          }
        } else {
          filters.push(filter)
        }
      })

      const response = await client.query({
        query: gql`
          query bizplaceInventoryHistoriesForExport($inventoryHistory: InventoryHistoryPatch, $filters: [Filter!]) {
            bizplaceInventoryHistoriesForExport(inventoryHistory: $inventoryHistory, filters: $filters) {
              items {
                sku
                productName
                productDescription
                brand
                seq
                palletId
                cartonId
                batchId
                batchIdRef
                openingQty
                qty
                openingUomValue
                uomValue
                uom
                zone
                orderNo
                refNo
                conditionOfGoods
                status
                transactionType
                bizplace
                warehouse
                location
                createdAt
                updatedAt
                updater
              }
              total
            }
          }
        `,
        variables: { inventoryHistory, filters }
      })

      if (!response.errors) return response.data.bizplaceInventoryHistoriesForExport.items
    } catch (error) {}
  }

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

  _modifyDateRange(e) {
    const fromDate = e.currentTarget.value

    if (this._toDateInput.value < fromDate) this._toDateInput.value = fromDate

    let min = new Date(fromDate)
    let max = new Date(fromDate)
    max.setMonth(max.getMonth() + 1)
    max.setDate(max.getDate() - 1)

    min = min.toISOString().split('T')[0]
    max = max.toISOString().split('T')[0]

    this._toDateInput.value = max
    this._toDateInput.max = max
    this._toDateInput.min = min
  }

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

  _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.sku'), key: 'sku', width: 75, type: 'string' },
        { header: i18next.t('field.product_name'), key: 'productName', width: 75, type: 'string' },
        { header: i18next.t('field.product_description'), key: 'productDescription', width: 75, type: 'string' },
        { header: i18next.t('field.brand'), key: 'brand', width: 75, type: 'string' },
        { header: i18next.t('field.seq'), key: 'seq', width: 75, type: 'number' },
        { header: i18next.t('field.lot_id'), key: 'palletId', width: 75, type: 'string' },
        { header: i18next.t('field.carton_id'), key: 'cartonId', width: 75, type: 'string' },
        { header: i18next.t('field.opening_qty'), key: 'openingQty', width: 75, type: 'number' },
        { header: i18next.t('field.qty'), key: 'qty', width: 75, type: 'number' },
        { header: i18next.t('field.opening_uom_value'), key: 'openingUomValue', width: 75, type: 'number' },
        { header: i18next.t('field.uom_value'), key: 'uomValue', width: 75, type: 'number' },
        { header: i18next.t('field.uom'), key: 'uom', width: 75, type: 'string' },
        { header: i18next.t('field.location'), key: 'location', width: 75, type: 'string' },
        { header: i18next.t('field.inventory_quality'), key: 'conditionOfGoods', width: 75, type: 'string' },
        { header: i18next.t('field.batch_id'), key: 'batchId', width: 75, type: 'string' },
        { header: i18next.t('field.batch_no_ref'), key: 'batchIdRef', width: 75, type: 'string' },
        { header: i18next.t('field.order_no'), key: 'orderNo', width: 75, type: 'string' },
        { header: i18next.t('field.ref_no'), key: 'refNo', width: 75, type: 'string' },
        { header: i18next.t('field.status'), key: 'status', width: 75, type: 'string' },
        { header: i18next.t('field.transaction_type'), key: 'transactionType', width: 75, type: 'string' },
        { header: i18next.t('field.created_at'), key: 'createdAt', width: 75, type: 'date' },
        { header: i18next.t('field.updated_at'), key: 'updatedAt', width: 75, type: 'date' },
        { header: i18next.t('field.updater'), key: 'updater', width: 75, type: 'string' }
      ]

      const bizplaceFilters = (await this.searchForm.getQueryFilters()).filter(x => x.name === 'bizplace')
      if (bizplaceFilters.length == 0) {
        throw new Error(`Please select a customer for export.`)
      }
      data = await this._fetchInventoryHistoriesForExport()

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

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

window.customElements.define('inventory-history', InventoryHistory)
