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'

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 OrderVasReport 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,
      _vasList: Object,
      _partnerId: String,
      _partnerName: String,
      _vassId: String,
      _vassName: String,
      data: Object
    }
  }

  get context() {
    return {
      title: i18next.t('title.vas_order_report'),
      printable: {
        accept: ['preview'],
        content: this
      },
      exportable: {
        name: i18next.t('title.date_vas_order_report', {
          state: {
            text: (() => {
              let date = new Date()
              return date.getFullYear().toString() + (date.getMonth() + 1).toString() + date.getDate().toString()
            })()
          }
        }),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/report/order-vas-report'
    }
  }

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

  get searchFields() {
    return [
      {
        label: i18next.t('field.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: 'gte',
          max: formatLocalDate(new Date())
        },
        value: (() => {
          const 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: 'lte',
          max: formatLocalDate(new Date())
        },
        value: formatLocalDate(new Date()),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.product_info'),
        name: 'productInfo',
        type: 'string',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.order_no'),
        name: 'orderNo',
        type: 'string',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.vas'),
        name: 'vass',
        type: 'select',
        options: [
          { value: '' },
          ...this._vasList
            .map(vass => {
              return {
                name: `${vass.name} ${vass.description ? `(${vass.description})` : ''}`,
                value: vass.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      }
    ]
  }

  get reportConfig() {
    return {
      rows: {
        selectable: false,
        groups: [
          { column: 'bizplaceName' },
          // { column: 'ro' },
          { column: 'ro', title: 'Sub Total' },
          { column: 'refNo' },
          { column: 'sku' },
          { column: 'batchId' },
          { column: 'packingType' },
          { column: 'uom' },
          { column: 'uomValue' },
          { column: 'releaseQty' },
          { column: 'orderVasName' },
          { column: 'qty' },
          { column: 'newBatchId' },
          { column: 'newSku' },
          { column: 'newPackingType' },
          { column: 'newUom' },
          { column: 'newUomValue' },
          { column: 'outputQty' }
        ],
        totals: ['vasQty']
      },
      columns: [
        {
          type: 'string',
          name: 'bizplaceName',
          header: i18next.t('field.company'),
          sortable: false,
          imex: { header: i18next.t('field.company'), key: 'bizplaceName', width: 30, type: 'string' },
          width: 150
        },
        {
          type: 'string',
          name: 'ro',
          header: i18next.t('field.order_no'),
          sortable: false,
          imex: { header: i18next.t('field.order_no'), key: 'ro', width: 25, type: 'string' },
          width: 160
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          sortable: false,
          imex: { header: i18next.t('field.ref_no'), key: 'refNo', width: 25, type: 'string' },
          width: 150
        },
        {
          type: 'string',
          name: 'sku',
          header: i18next.t('field.sku'),
          sortable: false,
          imex: { header: i18next.t('field.sku'), key: 'sku', width: 20, type: 'string' },
          width: 150
        },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_no'),
          sortable: false,
          imex: { header: i18next.t('field.batch_no'), key: 'batchId', width: 20, type: 'string' },
          width: 100
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          sortable: false,
          imex: { header: i18next.t('field.packing_type'), key: 'packingType', width: 20, type: 'string' },
          width: 130
        },
        {
          type: 'string',
          name: 'uom',
          header: i18next.t('field.uom'),
          sortable: false,
          imex: { header: i18next.t('field.uom'), key: 'uom', width: 5, type: 'string' },
          width: 70
        },
        {
          type: 'number',
          name: 'uomValue',
          header: i18next.t('field.unit_uom_value'),
          sortable: false,
          imex: { header: i18next.t('field.unit_uom_value'), key: 'uomValue', width: 10, type: 'string' },
          width: 100
        },
        {
          type: 'number',
          name: 'releaseQty',
          header: i18next.t('field.release_qty'),
          sortable: false,
          imex: { header: i18next.t('field.release_qty'), key: 'releaseQty', width: 10, type: 'number' },
          width: 90
        },
        {
          type: 'string',
          name: 'orderVasName',
          header: i18next.t('field.set'),
          sortable: false,
          imex: { header: i18next.t('field.set'), key: 'orderVasName', width: 10, type: 'string' },
          width: 150
        },
        {
          type: 'number',
          name: 'qty',
          header: i18next.t('field.qty'),
          sortable: false,
          imex: { header: i18next.t('field.qty'), key: 'qty', width: 10, type: 'number' },
          width: 80
        },
        {
          type: 'string',
          name: 'newBatchId',
          header: i18next.t('field.batch_no_sku', { sku: 'NEW SKU' }),
          sortable: false,
          imex: {
            header: i18next.t('field.batch_no_sku', { sku: 'NEW SKU' }),
            key: 'newBatchId',
            width: 20,
            type: 'string'
          },
          width: 150
        },
        {
          type: 'string',
          name: 'newSku',
          header: i18next.t('field.new_sku'),
          sortable: false,
          imex: { header: i18next.t('field.new_sku'), key: 'newSku', width: 20, type: 'string' },
          width: 150
        },
        {
          type: 'string',
          name: 'newPackingType',
          header: i18next.t('field.packing_type_sku', { sku: 'NEW SKU' }),
          sortable: false,
          imex: {
            header: i18next.t('field.packing_type_sku', { sku: 'NEW SKU' }),
            key: 'newPackingType',
            width: 10,
            type: 'string'
          },
          width: 130
        },
        {
          type: 'string',
          name: 'newUom',
          header: i18next.t('field.uom_sku', { sku: 'NEW SKU' }),
          sortable: false,
          imex: { header: i18next.t('field.uom_sku', { sku: 'NEW SKU' }), key: 'newUom', width: 5, type: 'string' },
          width: 130
        },
        {
          type: 'number',
          name: 'newUomValue',
          header: i18next.t('field.uom_value_sku', { sku: 'NEW SKU' }),
          sortable: false,
          imex: {
            header: i18next.t('field.uom_value_sku', { sku: 'NEW SKU' }),
            key: 'newUomValue',
            width: 10,
            type: 'string'
          },
          width: 130
        },
        {
          type: 'number',
          name: 'outputQty',
          header: i18next.t('field.output_qty'),
          sortable: false,
          imex: { header: i18next.t('field.output_qty'), key: 'outputQty', width: 10, type: 'string' },
          width: 80
        },
        {
          type: 'string',
          name: 'vas',
          header: i18next.t('field.vas'),
          sortable: false,
          imex: { header: i18next.t('field.vas'), key: 'vas', width: 15, type: 'string' },
          width: 130
        },
        {
          type: 'string',
          name: 'vasRemark',
          header: i18next.t('field.remark'),
          sortable: false,
          imex: { header: i18next.t('field.remark'), key: 'vasRemark', width: 15, type: 'string' },
          width: 100
        },
        {
          type: 'number',
          name: 'vasQty',
          header: i18next.t('field.vas_qty'),
          sortable: false,
          imex: { header: i18next.t('field.vas_qty'), key: 'vasQty', width: 10, type: 'string' },
          width: 70
        },
        {
          type: 'string',
          name: 'updaterName',
          header: i18next.t('field.updater'),
          sortable: false,
          imex: { header: i18next.t('field.updater'), key: 'updater', width: 15, type: 'string' },
          width: 100
        }
      ]
    }
  }

  async pageInitialized() {
    this._releaseOrders = []
    this._partners = [...(await this._fetchPartners())]
    this._vasList = [...(await this._fetchVas())]
    this._orderVass = []

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

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

  async fetchHandler({ page, limit, sorters = [] }) {
    try {
      this._validate()
      const response = await client.query({
        query: gql`
          query orderVasReport($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            orderVasReport(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                bizplace {
                  name
                  description
                }
                releaseGood {
                  name
                  refNo
                }
                orderVas {
                  id
                  name
                  batchId
                  packingType
                  uom
                  uomValue
                  newPackingType
                  newUom
                  newUomValue
                  outputQty
                  qty
                  product {
                    sku
                  }
                  newProduct {
                    sku
                  }
                  remark
                }
                orderVasItem {
                  id
                  vas {
                    name
                    description
                  }
                  vasQty
                  vasRemark
                }
                orderInventory {
                  releaseQty
                }
                worksheet {
                  endedAt
                }
                user {
                  id
                  name
                }
              }
            }
          }
        `,
        variables: {
          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
            })
          ],
          pagination: { page, limit },
          sortings: sorters
        }
      })
      return {
        total: 0,
        records: response.data.orderVasReport.items.map(item => {
          return {
            ...item,
            orderVasId: item.orderVas.id,
            orderVasName: item.orderVas.name,
            bizplaceName: item.bizplace.name,
            ro: item.releaseGood.name,
            refNo: item.releaseGood.refNo,
            sku: item.orderVas.product.sku,
            batchId: item.orderVas.batchId,
            qty: item.orderVas.qty,
            packingType: item.orderVas.packingType,
            uom: item.orderVas.uom,
            uomValue: item.orderVas.uomValue,
            releaseQty: item.orderInventory.releaseQty,
            vas: `${item.orderVasItem.vas.name}(${item.orderVasItem.vas.description})`,
            vasQty: item.orderVasItem.vasQty,
            vasRemark: item.orderVasItem.vasRemark,
            newSku: item.orderVas.newProduct.sku,
            newPackingType: item.orderVas.newPackingType,
            newUom: item.orderVas.newUom,
            outputQty: item.orderVas.outputQty,
            newUomValue: item.orderVas.newUomValue,
            completionDate: item.worksheet.endedAt,
            remark: item.orderVas.remark,
            updaterName: item.user?.name
          }
        })
      }
    } catch (e) {
      this._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) {
      const partners = response.data.partnersBizplaces.items
      if (partners.length == 1) {
        this._partnerId = partners[0].id
        this._partnerName = partners[0].name
      } else {
        this._partnerId = ''
        this._partnerName = ''
      }

      return partners
    }
  }

  async _fetchVas() {
    const filters = []
    const response = await client.query({
      query: gql`
        query vass($filters: [Filter!]) {
          vass(filters: $filters) {
            items {
              id
              name
              description
            }
          }
        }
      `,
      variables: { filters }
    })

    if (!response.errors) {
      const vass = response.data.vass.items
      if (vass.length == 1) {
        this._vassId = vass[0].id
        this._vassName = vass[0].name
      } else {
        this._vassId = ''
        this._vassName = ''
      }

      return vass
    }
  }

  _validate() {
    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'))
    }
    if (new Date(this._fromDateInput.value) > new Date(this._toDateInput.value)) {
      throw new Error(i18next.t('text.to_date_cannot_be_before_from_date'))
    }

    if (!this.searchForm.shadowRoot.querySelector('form').checkValidity())
      throw new Error(i18next.t('text.invalid_form_value'))
  }

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

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

    const minDate = new Date(fromDate)
    if (Number.isNaN(minDate.getTime())) return

    const min = formatLocalDate(minDate)
    this._toDateInput.min = min
  }

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

  _exportableData() {
    try {
      var headerSetting = [
        ...this.report._config.columns
          .filter(column => column.type !== 'gutter' && column.record !== undefined && column.imex !== undefined)
          .map(column => {
            return column.imex
          })
      ]

      return {
        header: headerSetting,
        data: this.report.data.records.map(record => {
          return flattenObject({
            ...record
          })
        }),
        groups: this.report._config.rows.groups,
        totals: this.report._config.rows.totals
      }
    } catch (e) {
      this._showToast(e)
    }
  }

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

window.customElements.define('order-vas-report', OrderVasReport)
