import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import './route-label-popup'
import './select-operator-popup'

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 { ScrollbarStyles, CommonButtonStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import { openPopup } from '@things-factory/layout-base'
import { applyParamsToFields } from '../../util'
import { fetchSettingRule } from '../../fetch-setting-value'

import { WORKSHEET_TYPE } from '../constants'

class ZoneWorksheet extends localize(i18next)(PageView) {
  static get properties() {
    return {
      config: Object,
      data: Object,
      assignee: String,
      status: String,
      _searchFields: Array,
      _partnersList: Array,
      _routeLabelSetting: Boolean,
      _routeLabelSettingDomainId: String
    }
  }

  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;
        }
      `
    ]
  }

  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() {
    var actions = []

    if (this._routeLabelSetting) {
      actions.push({
        title: i18next.t('button.print_route_label'),
        action: this._openPrintLabelPopup.bind(this),
        ...CommonButtonStyles.label
      })
    }

    actions = actions.concat([
      {
        title: i18next.t('button.assign_picker'),
        action: this._assignPicker.bind(this),
        ...CommonButtonStyles.activate
      },
      {
        title: i18next.t('button.activate'),
        action: this._activateBulkWorksheet.bind(this),
        ...CommonButtonStyles.activate
      }
    ])

    return {
      title: i18next.t('title.zone_worksheet'),
      exportable: {
        name: i18next.t('title.zone_worksheet'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/outbound/zone-worksheet',
      actions
    }
  }

  pageUpdated(changes, lifecycle) {
    if (this.active) {
      this.assignedId = lifecycle.params.assignedId || null
      this.status = lifecycle.params.status || null

      let { params } = lifecycle
      if (params && this._searchFields) {
        applyParamsToFields(this._searchFields, params, this.searchForm)
      }

      this.dataGrist.fetch()
    }
  }

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

    this._searchFields = [
      {
        name: 'name',
        label: i18next.t('field.worksheet_no'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        name: 'releaseGoodNo',
        label: i18next.t('field.order_info'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        name: 'bizplaceId',
        label: i18next.t('field.company'),
        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' }
      },
      {
        name: 'assignee',
        label: i18next.t('field.picker'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        name: 'zone',
        label: i18next.t('field.zone'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        name: 'fromDate',
        label: i18next.t('field.from_date'),
        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) }
      },
      {
        name: 'toDate',
        label: i18next.t('field.to_date'),
        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]
      }
    ]

    this.config = {
      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

              if (type === WORKSHEET_TYPE.ZONE_PICKING.value) {
                navigate(`worksheet_zone_picking/${record.name}`)
              } else if (type === WORKSHEET_TYPE.LOADING.value) {
                navigate(`worksheet_loading/${record.name}`)
              }
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.worksheet_no'),
          width: 150
        },
        {
          type: 'number',
          name: 'roCounts',
          header: i18next.t('field.no_of_ro'),
          width: 100
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          width: 120
        },
        {
          type: 'string',
          name: 'refNo2',
          header: i18next.t('field.ref_no_2'),
          width: 120
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          width: 240
        },
        {
          type: 'number',
          name: 'skuCounts',
          header: i18next.t('field.no_of_sku'),
          width: 100
        },
        {
          type: 'string',
          name: 'type',
          header: i18next.t('field.type'),
          width: 120
        },
        {
          type: 'string',
          name: 'zone',
          header: i18next.t('field.zone'),
          width: 120
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          width: 120
        },
        {
          type: 'object',
          name: 'assignee',
          header: i18next.t('field.assigned_picker'),
          width: 120
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'startedAt',
          header: i18next.t('field.started_at'),
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'endedAt',
          header: i18next.t('field.ended_at'),
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          sortable: true,
          width: 150
        }
      ]
    }
  }

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

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

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

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

  async fetchHandler({ page, limit, sorters = [{ name: 'createdAt', desc: true }] }) {
    const filters = this.searchForm.queryFilters
    filters.push({
      name: 'type',
      operator: 'in',
      value: [WORKSHEET_TYPE.ZONE_PICKING.value]
    })

    // assigneeId filter is currently not in use
    // if (this.assigneeId) {
    //   filters.push({
    //     name: 'assigneeId',
    //     operator: 'in',
    //     value: [this.assigneeId]
    //   })
    // }

    if (this.status) {
      filters.push({ name: 'status', operator: 'eq', value: this.status })
    }

    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
              taskNo
              assignee {
                id
                name
              }
              bizplace {
                id
                name
                description
              }
              type
              zone
              status
              startedAt
              createdAt
              endedAt
              updater {
                name
                description
              }
              domain {
                id
                name
              }
              roCounts
              skuCounts
              refNo
              refNo2
            }
            total
          }
        }
      `,
      variables: { filters, pagination: { page, limit }, sortings: sorters }
    })

    if (!response.errors) {
      // Decide whether to show route label printing based on setting.
      const domain = response.data.worksheets.items[0]?.domain
      if (domain) {
        this._routeLabelSetting = await fetchSettingRule('enable-print-route-label', domain.id)
        this._routeLabelSettingDomainId = domain.id
      }
      this.updateContext()
      return {
        total: response.data.worksheets.total || 0,
        records: response.data.worksheets.items || []
      }
    }
  }

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

    if (!response.errors) {
      this._partnersList = response.data.partnersBizplaces
      return response.data.partnersBizplaces.items
    }
  }

  async _openPrintLabelPopup() {
    try {
      const bizplaceFilters = (await this.searchForm.getQueryFilters()).find(x => x.name === 'bizplaceId')
      if (!bizplaceFilters) {
        throw new Error(`Please select a customer to print route label.`)
      }

      const selectedPartner = this._partnersList.items.find(itm => itm.id == bizplaceFilters.value)
      const selectedDomainId = selectedPartner?.domain?.id

      // Reuse cached setting if same domain, otherwise fetch
      let routeLabelEnabled = this._routeLabelSetting
      if (selectedDomainId && selectedDomainId !== this._routeLabelSettingDomainId) {
        routeLabelEnabled = await fetchSettingRule('enable-print-route-label', selectedDomainId)
      }

      if (!routeLabelEnabled) {
        throw new Error(`Route label printing is not enabled for this partner.`)
      }

      openPopup(
        html`
          <route-label-popup
            .partnerId="${bizplaceFilters.value}"
            .worksheetType="${'single'}"
            .sourceWorksheetType="${'ZONE_PICKING'}"
          ></route-label-popup>
        `,
        {
          backdrop: true,
          size: 'large',
          title: i18next.t('title.print_route_label')
        }
      )
    } catch (e) {
      this._showToast(e)
    }
  }

  _assignPicker() {
    try {
      let selectedData = this.dataGrist.selected.filter(item => {
        return item.status == 'DEACTIVATED'
      })

      if (selectedData.length <= 0) throw new Error('No available worksheet selected')

      openPopup(
        html`
          <select-operator-popup
            @updateOperator="${async e => {
              let assignee = e.detail

              const response = await client.mutate({
                mutation: gql`
                  mutation assignPickingWorker($worksheetId: [String]!, $userId: String!) {
                    assignPickingWorker(worksheetId: $worksheetId, userId: $userId)
                  }
                `,
                variables: { worksheetId: selectedData.map(itm => itm.id), userId: assignee.id }
              })

              if (!response.errors) {
                this.dataGrist.fetch()
                return this._showToast({ message: i18next.t('text.updated_successfully') })
              }

              if (this.activatable) {
                if (this.orderNo) {
                  history.back()
                }
              }
            }}"
          ></select-operator-popup>
        `,
        {
          backdrop: true,
          size: 'medium',
          title: 'select operator'
        }
      )
    } catch (error) {
      return this._showToast(error)
    }
  }

  async _activateBulkWorksheet() {
    try {
      let selectedData = this.dataGrist.selected.filter(item => {
        if (item.status !== 'DEACTIVATED') {
          throw new Error(i18next.t('text.please_select_order_with_status_deactivated_only'))
        }
        return item.status == 'DEACTIVATED'
      })

      if (selectedData.length <= 0)
        throw new Error(i18next.t('text.please_select_at_least_one_order_with_status_deactivated_to_proceed'))

      if (selectedData.length > 50)
        throw new Error(i18next.t('text.please_select_maximum_50_worksheets_with_status_deactivated_to_proceed'))

      const result = await CustomAlert({
        title: i18next.t('title.are_you_sure'),
        text: i18next.t('text.activate_picking_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 activateBulkWorksheetZonePicking($names: [String!]!) {
            activateBulkWorksheetZonePicking(names: $names) {
              name
            }
          }
        `,
        variables: {
          names: selectedData.map(item => {
            return item.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 = [
      { header: i18next.t('field.worksheet_no'), key: 'name', width: 30, type: 'string' },
      { header: i18next.t('field.no_of_ro'), key: 'roCounts', width: 15, type: 'number' },
      { header: i18next.t('field.ref_no'), key: 'refNo', width: 25, type: 'string' },
      { header: i18next.t('field.company'), key: 'bizplaceName', width: 40, type: 'string' },
      { header: i18next.t('field.no_of_sku'), key: 'skuCounts', width: 15, type: 'number' },
      { header: i18next.t('field.type'), key: 'type', width: 20, type: 'string' },
      { header: i18next.t('field.zone'), key: 'zone', width: 20, type: 'string' },
      { header: i18next.t('field.status'), key: 'status', width: 20, type: 'string' },
      { header: i18next.t('field.assigned_picker'), key: 'assigneeName', width: 30, type: 'string' },
      { header: i18next.t('field.created_at'), key: 'createdAt', width: 25, type: 'datetime' },
      { header: i18next.t('field.started_at'), key: 'startedAt', width: 25, type: 'datetime' },
      { header: i18next.t('field.ended_at'), key: 'endedAt', width: 25, type: 'datetime' },
      { header: i18next.t('field.updater'), key: 'updaterName', width: 30, type: 'string' }
    ]

    var data = records.map(itm => {
      return {
        ...itm,
        bizplaceName: itm.bizplace ? itm.bizplace.name : '',
        assigneeName: itm.assignee ? itm.assignee.name : '',
        updaterName: itm.updater ? itm.updater.name : '',
        createdAt: itm.createdAt ? new Date(parseInt(itm.createdAt)).toLocaleString() : '',
        startedAt: itm.startedAt ? new Date(parseInt(itm.startedAt)).toLocaleString() : '',
        endedAt: itm.endedAt ? new Date(parseInt(itm.endedAt)).toLocaleString() : ''
      }
    })

    return { header: headerSetting, data: data }
  }

  _showToast({ type, message }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message
        }
      })
    )
  }
}
window.customElements.define('zone-worksheet', ZoneWorksheet)
