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

import gql from 'graphql-tag'
import {
  css,
  html
} from 'lit-element'

import { getCodeByName } from '@things-factory/code-base'
import {
  i18next,
  localize
} from '@things-factory/i18n-base'
import {
  client,
  CustomAlert,
  navigate,
  PageView
} from '@things-factory/shell'
import {
  CommonButtonStyles,
  ScrollbarStyles
} from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

import { WORKSHEET_TYPE } from '../constants'

class PackingWorksheetList extends localize(i18next)(PageView) {
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
        }

        search-form {
          overflow: visible;
        }
        data-grist {
          overflow-y: auto;
          flex: 1;
        }
      `
    ]
  }

  static get properties() {
    return {
      _searchFields: Array,
      config: Object,
      data: Object
    }
  }

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

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

  get context() {
    return {
      title: i18next.t('title.packing_worksheet_list'),
      actions: [
        {
          title: i18next.t('button.activate'),
          action: this._activateWorksheet.bind(this),
          ...CommonButtonStyles.activate
        }
      ],
      exportable: {
        name: i18next.t('title.packing_worksheet_list'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/outbound/packing-worksheet-list'
    }
  }

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

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

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

  async pageInitialized() {
    const _worksheetStatus = await getCodeByName('WORKSHEET_STATUS')
    const partners = [...(await this._fetchPartners())]

    this._searchFields = [
      {
        name: 'outboundOrderInfo',
        label: i18next.t('field.order_info'),
        type: 'text',
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.company'),
        name: 'bizplaceId',
        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' }
      },
      {
        name: 'status',
        label: i18next.t('label.status'),
        type: 'select',
        options: [
          { value: '' },
          ..._worksheetStatus.map(status => {
            return { name: i18next.t(`label.${status.description}`), value: status.name }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.from'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq'
        },
        value: (() => {
          let date = new Date()
          date.setMonth(date.getMonth() - 6)
          return date.toISOString().split('T')[0]
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          min: (() => {
            let date = new Date()
            date.setMonth(date.getMonth() - 6)
            return date.toISOString().split('T')[0]
          })()
        },
        value: new Date().toISOString().split('T')[0]
      },
      {
        label: i18next.t('field.order_remark'),
        name: 'orderRemark',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.manifested'),
        name: 'manifest',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      }
    ]

    this.config = {
      list: {
        fields: ['releaseGood', 'bizplace', 'type', 'releaseRefNo', 'status', 'startedAt', 'endedAt']
      },
      rows: { appendable: false, selectable: { multiple: true } },
      pagination: { limit: 100, pages: [20, 50, 100, 200, 500] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              if (!record.id) return
              const type = record.type

              // Handle PICKING
              if (type === WORKSHEET_TYPE.PACKING.value) {
                navigate(`worksheet_packing/${record.name}`)
              }
            }
          }
        },
        {
          type: 'boolean',
          name: 'orderRemark',
          header: i18next.t('field.order_remark'),
          sortable: true,
          width: 100
        },
        {
          type: 'object',
          name: 'releaseGood',
          header: i18next.t('field.release_good_no'),
          imex: { header: i18next.t('field.release_good_no'), key: 'releaseGood', width: 30, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'releaseRefNo',
          header: i18next.t('field.ref_no'),
          imex: { header: i18next.t('field.ref_no'), key: 'releaseRefNo', width: 30, type: 'string' },
          sortable: true,
          width: 180
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          imex: { header: i18next.t('field.company'), key: 'bizplace', width: 30, type: 'string' },
          sortable: true,
          width: 240
        },
        {
          type: 'string',
          name: 'type',
          header: i18next.t('field.type'),
          imex: { header: i18next.t('field.type'), key: 'type', width: 30, type: 'string' },
          sortable: true,
          width: 100
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          imex: { header: i18next.t('field.status'), key: 'status', width: 30, type: 'string' },
          sortable: true,
          width: 100
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          imex: { header: i18next.t('field.created_at'), key: 'createdAt', width: 30, type: 'date' },
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'startedAt',
          header: i18next.t('field.started_at'),
          imex: { header: i18next.t('field.started_at'), key: 'startedAt', width: 30, type: 'date' },
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'endedAt',
          header: i18next.t('field.ended_at'),
          imex: { header: i18next.t('field.ended_at'), key: 'endedAt', width: 30, type: 'date' },
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          imex: { header: i18next.t('field.updater'), key: 'updater', width: 30, type: 'string' },
          sortable: true,
          width: 150
        }
      ]
    }
  }

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

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

  async fetchHandler({ page, limit, sorters = [{ name: 'createdAt', desc: true }] }) {
    const filters = this.searchForm.queryFilters
    filters.push({
      name: 'type',
      operator: 'in',
      value: [WORKSHEET_TYPE.PACKING.value]
    })
    const response = await client.query({
      query: gql`
        query worksheets($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          worksheets(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              releaseGood {
                id
                name
                description
                refNo
              }
              bizplace {
                id
                name
                description
              }
              orderRemark
              name
              type
              status
              startedAt
              createdAt
              endedAt
              updater {
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: { filters, pagination: { page, limit }, sortings: sorters }
    })

    if (!response.errors) {
      return {
        total: response.data.worksheets.total || 0,
        records:
          response.data.worksheets.items.map(item => {
            return { ...item, releaseRefNo: item.releaseGood.refNo }
          }) || {}
      }
    }
  }

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

  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 _activateWorksheet() {
    try {
      let selectedItem = this.dataGrist.selected.filter(i => i.status == 'DEACTIVATED')
      if (selectedItem.length <= 0) {
        this._showToast({ message: 'No orders have been selected' })
      } else {
        const result = await CustomAlert({
          title: i18next.t('title.are_you_sure'),
          text: i18next.t('text.activate_packing_worksheet'),
          confirmButton: { text: i18next.t('button.confirm') },
          cancelButton: { text: i18next.t('button.cancel') }
        })

        if (!result.value) {
          return
        }

        const response = await client.mutate({
          mutation: gql`
            mutation activatePacking($worksheetNo: [String!]!) {
              activatePacking(worksheetNo: $worksheetNo) {
                id
                name
              }
            }
          `,
          variables: {
            worksheetNo: selectedItem.map(itm => {
              return itm.name
            })
          }
        })

        if (!response.errors) {
          this._showToast({ message: i18next.t('text.worksheet_activated') })
        }
      }
    } catch (e) {
      this._showToast(e)
    } finally {
      this.dataGrist.fetch()
    }
  }

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

  _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() {
    let records = []
    if (this.dataGrist.selected && this.dataGrist.selected.length > 0) {
      records = this.dataGrist.selected
    } else {
      records = this.dataGrist.data.records
    }

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

    var data = records.map(item => {
      return {
        ...this._columns
          .filter(column => column.type !== 'gutter' && column.record !== undefined && column.imex !== undefined)
          .reduce((record, column) => {
            record[column.imex.key] = column.imex.key
              .split('.')
              .reduce((obj, key) => (obj && obj[key] !== 'undefined' ? obj[key] : undefined), item)
            if (column.type === 'datetime') {
              record[column.imex.key] = new Date(parseInt(record[column.imex.key])).toLocaleString()
            }
            return record
          }, {}),
          id: item.id,
          releaseGood: item.releaseGood.name,
          releaseRefNo: item.releaseRefNo,
          bizplace: item.bizplace.name,
          type: item.type,
          status:item.status,
          createdAt: item.createdAt,
          startedAt: item.startedAt,
          endedAt: item.endedAt,
          updater:item.updater.name,

      }
    })
    return { header: headerSetting, data: data }
  }

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

window.customElements.define('packing-worksheet-list', PackingWorksheetList)
