import '@things-factory/form-ui'
import '@things-factory/grist-ui'

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,
  PageView,
  store
} from '@things-factory/shell'
import { flattenObject } from '@things-factory/utils'

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

      data-report {
        flex: 1;
      }
    `
  }

  static get properties() {
    return {
      _searchFields: Object,
      _config: Object,
      _partners: Object,
      data: Object
    }
  }

  get context() {
    return {
      title: i18next.t('title.inventory_pallet_detail_report'),
      printable: {
        accept: ['preview'],
        content: this
      },
      exportable: {
        name: i18next.t('title.inventory_pallet_detail_report'),
        data: this._exportableData.bind(this)
      }
    }
  }

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

  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} @submit=${e => this.report.fetch()}></search-form>

      <data-report
        .config=${this._config}
        .fetchHandler="${this.fetchHandler.bind(this)}"
      ></data-grist>
    `
  }

  get searchFields() {
    return [
      {
        label: i18next.t('field.company'),
        name: 'bizplace',
        type: 'select',
        options: [
          { value: '' },
          ...this._partners
            .map(partner => {
              return {
                name: partner.name,
                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: new Date().toISOString().split('T')[0]
        },
        value: (() => {
          let date = new Date()
          date.setTime(date.getTime() - 86400000 * 7)
          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.setTime(date.getTime() - 86400000 * 7)
            return date.toISOString().split('T')[0]
          })(),
          max: new Date().toISOString().split('T')[0]
        },
        value: new Date().toISOString().split('T')[0]
      }
    ]
  }

  get reportConfig() {
    return {
      pagination: { infinite: true },
      rows: {
        selectable: false,
        groups: [{ column: 'bizplace|name' }],
        totals: ['openingBalance', 'inBalance', 'outBalance', 'closingBalance']
      },
      columns: [
        {
          type: 'string',
          name: 'bizplace|name',
          header: i18next.t('field.company'),
          width: 450
        },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_id'),
          width: 200
        },
        {
          type: 'string',
          name: 'jobSheet',
          header: i18next.t('field.job_sheet'),
          width: 200
        },
        {
          type: 'string',
          name: 'containerSize',
          header: i18next.t('field.container_size'),
          width: 100
        },
        {
          type: 'float',
          name: 'openingBalance',
          record: { align: 'center' },
          header: i18next.t('field.opening_balance'),
          width: 130
        },
        {
          type: 'float',
          name: 'inBalance',
          record: { align: 'center' },
          header: i18next.t('field.inbound'),
          width: 130
        },
        {
          type: 'float',
          name: 'outBalance',
          record: { align: 'center' },
          header: i18next.t('field.outbound'),
          width: 130
        },
        {
          type: 'float',
          name: 'closingBalance',
          record: { align: 'center' },
          header: i18next.t('field.closing_balance'),
          width: 130
        }
      ]
    }
  }

  async pageInitialized() {
    this._products = []
    this._partners = [...(await this._fetchPartners())]

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

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

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      if(!this._validateDateRange()) return
      let filters = this.searchForm.queryFilters.map(itm => {
        switch (itm.name) {
          case 'fromDate':
            let fromDt = new Date(itm.value)
            fromDt.setHours(0)

            itm = {
              ...itm,
              value: fromDt.toISOString()
            }
            break
          case 'toDate':
            let toDt = new Date(itm.value)
            toDt.setHours(23, 59, 59)

            itm = {
              ...itm,
              value: toDt.toISOString()
            }
            break
          default:
            break
        }

        return itm
      })

      this._validate()

      const response = await client.query({
        query: gql`
          query elcclInventoryHistoryPalletDetailReport(
            $filters: [Filter!]
            $pagination: Pagination
            $sortings: [Sorting!]
          ) {
            elcclInventoryHistoryPalletDetailReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              bizplace {
                name
                description
              }
              product {
                name
                description
              }
              openingBalance
              inBalance
              outBalance
              closingBalance
              batchId
              jobSheet
              jsonDateMovement
              containerSize
            }
          }
        `,
        variables: {
          filters,
          pagination: { page, limit },
          sortings: sorters
        }
      })

      this.data = {
        filter: [...this.searchForm.queryFilters],
        records: response.data.elcclInventoryHistoryPalletDetailReport.map(item => flattenObject(item)) || []
      }

      return {
        total: 0,
        records: this.data.records
      }
    } catch (e) {
      console.log(e)
    }
  }

  async _fetchPartners() {
    const filters = []
    const response = await client.query({
      query: gql`
        query partnersBizplaces($filters: [Filter!], $sortings: [Sorting!]) {
          partnersBizplaces(filters: $filters, sortings: $sortings) {
            items {
              id
              name
              description
            }
          }
        }
      `,
      variables: { filters, sortings: [{ name: 'name' }] }
    })

    if (!response.errors) {
      return response.data.partnersBizplaces.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
    }
  }

  _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 today = new Date()
    today.setHours(0, 0, 0, 0)

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

    this._toDateInput.min = min
  }

  _exportableData() {
    try {
      let headerSettingBegin = [
        { header: i18next.t('field.company'), key: 'bizplace|name', width: 50, type: 'string' },
        { header: i18next.t('field.batch_id'), key: 'batchId', width: 25, type: 'string' },
        { header: i18next.t('field.job_sheet'), key: 'jobSheet', width: 30, type: 'string' },
        { header: i18next.t('field.container_size'), key: 'containerSize', width: 10, type: 'string' },
        { header: i18next.t('field.opening_balance'), key: 'openingBalance', width: 25, type: 'string' }
      ]

      let headerSettingDate = []
      let fromDate = new Date(this.data.filter.find(x => x.name === 'fromDate').value)
      let toDate = new Date(this.data.filter.find(x => x.name === 'toDate').value)

      for (var d = fromDate; d <= toDate; d.setDate(d.getDate() + 1)) {
        headerSettingDate.push({
          header: d
            .toLocaleDateString('en-GB', {
              day: '2-digit',
              month: 'short'
            })
            .replace(/ /g, '-'),
          key: d.toISOString().slice(0, 10),
          width: 25,
          type: 'string'
        })
      }

      let headerSettingEnd = [
        { header: i18next.t('field.inbound'), key: 'inBalance', width: 20, type: 'string' },
        { header: i18next.t('field.outbound'), key: 'outBalance', width: 20, type: 'string' },
        { header: i18next.t('field.closing_balance'), key: 'closingBalance', width: 20, type: 'string' }
      ]

      let fullData = this.data.records.map(record => {
        if (record.jsonDateMovement) {
          let bal = parseInt(record.openingBalance || 0)
          JSON.parse(record.jsonDateMovement).forEach(data => {
            bal = bal + parseInt(data.in_balance) - parseInt(data.out_balance)
            record = {
              ...record,
              [data.created_at]: 'In: ' + data.in_balance + ' | Out: ' + data.out_balance + ' | Bal: ' + bal
            }
          })
        }
        return { ...record }
      })

      let exportData = {
        header: [...headerSettingBegin, ...headerSettingDate, ...headerSettingEnd],
        data: fullData,
        groups: this.report._config.rows.groups,
        totals: this.report._config.rows.totals
      }
      return exportData
    } catch (e) {
      this._showToast(e)
    }
  }

  _validateDateRange(){
    if(this._fromDateInput.value==='' && this._toDateInput.value===''){
      this._showToast({ message: i18next.t('text.both_date_cannot_be_empty')})
      return false
    }else if (this._fromDateInput.value===''){
      this._showToast({ message: i18next.t('text.from_date_cannot_be_empty')})
      return false
    }else if (this._toDateInput.value===''){
      this._showToast({ message: i18next.t('text.to_date_cannot_be_empty')})
      return false
    }else if(this._fromDateInput.value > this._toDateInput.value){
      this._showToast({ message: i18next.t('text.to_date_cannot_be_before_from_date') })
      return false
    }
      return true
    }
    _showToast({ type, message }) {
      document.dispatchEvent(
        new CustomEvent('notify', {
          detail: {
            type,
            message
          }
        })
      )
    }
  }

window.customElements.define('elccl-inventory-pallet-detail-report', ElcclInventoryPalletDetailReport)
