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, 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 { fetchSettingRule } from '../../fetch-setting-value'

import { WORKSHEET_TYPE } from '../constants'

import { applyParamsToFields } from '../../util'

class MergedOutboundWorksheet 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 {
      _partnersList: Array,
      _searchFields: Array,
      _routeLabelSetting: Boolean,
      config: Object,
      data: Object,
      assignee: String,
      status: String
    }
  }

  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.push({
      title: i18next.t('button.assign_picker'),
      action: this._assignPicker.bind(this),
      ...CommonButtonStyles.activate
    })

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

  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.assigneeId = lifecycle.params.assigneeId || 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: 'taskNo',
        label: i18next.t('field.task_no'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        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' }
      },
      {
        name: 'assignee',
        label: i18next.t('field.picker'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.from_date'),
        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_date'),
        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]
      }
    ]

    this.config = {
      list: {
        fields: ['name', 'bizplace', 'type', '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

              if (type === WORKSHEET_TYPE.BATCH_PICKING.value) {
                navigate(`worksheet_batch_picking/${record.name}`)
              } else if (type === WORKSHEET_TYPE.SORTING.value) {
                navigate(`worksheet_sorting/${record.name}`)
              }
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.worksheet_no'),
          imex: { header: i18next.t('field.worksheet_no'), key: 'name', width: 30, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'taskNo',
          header: i18next.t('field.task_no'),
          imex: { header: i18next.t('field.task_no'), key: 'taskNo', width: 30, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          imex: { header: i18next.t('field.company'), key: 'bizplace.name', 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: 150
        },
        {
          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: 'object',
          name: 'assignee',
          header: i18next.t('field.assigned_picker'),
          imex: { header: i18next.t('field.assigned_picker'), key: 'assignee.name', width: 20, 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: 'string' },
          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: 'string' },
          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: 'string' },
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          imex: { header: i18next.t('field.updater'), key: 'updater.name', 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.BATCH_PICKING.value, WORKSHEET_TYPE.SORTING.value]
    })

    // Add extra condition if path variable has assigneeId
    // It's for navigate from picking UI to list up assigned tasks of user
    if (this.assigneeId) {
      filters.push({
        name: 'assigneeId',
        operator: 'in',
        value: [this.assigneeId]
      })
    }

    // Add extra condition if path variable has status
    // It's for navigate from picking UI to list up assigned tasks of user
    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
              status
              startedAt
              createdAt
              endedAt
              updater {
                name
                description
              }
              domain {
                id
                name
              }
            }
            total
          }
        }
      `,
      variables: { filters, pagination: { page, limit }, sortings: sorters }
    })

    if (!response.errors) {
      let domain = response.data.worksheets.items[0]?.domain
      this._routeLabelSetting = await fetchSettingRule('enable-print-route-label', domain?.id)
      this.updateContext()
      return {
        total: response.data.worksheets.total || 0,
        records: response.data.worksheets.items || []
      }
    }
  }

  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
              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.`)
      } else {
        let selectedPartnerDomain = this._partnersList.items.find(itm => itm.id == bizplaceFilters.value)
        let partnerRouteLabelSetting = await fetchSettingRule(
          'enable-print-route-label',
          selectedPartnerDomain.domain.id
        )
        if (partnerRouteLabelSetting == false) throw new Error(`Partner setting not found`)
      }

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

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

  navigatePickingRelatedPages(record) {
    if (this.assigneeId) {
      const searchParams = new URLSearchParams()
      searchParams.append('orderNo', record.releaseGood.name)
      if (this.status === WORKSHEET_STATUS.EXECUTING.value) {
        navigate(`picking?${searchParams.toString()}`)
      } else if (this.status === WORKSHEET_STATUS.DEACTIVATED.value) {
        navigate(`worksheet_batch_picking/${record.name}?${searchParams.toString()}`)
      }
    } else {
      navigate(`worksheet_batch_picking/${record.name}`)
    }
  }

  _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)
    }
  }
  _showToast({ type, message }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message
        }
      })
    )
  }

  _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.imex !== undefined)
      .map(column => {
        return column.imex
      })

    var data = records.map(item => {
      return {
        id: item.id,
        ...this._columns
          .filter(column => column.type !== 'gutter' && 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()
            }
            if (record[column.imex.key] === 'Invalid Date') {
              record[column.imex.key] = ''
            }
            return record
          }, {})
      }
    })

    return { header: headerSetting, data: data }
  }

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

window.customElements.define('merged-outbound-worksheet', MergedOutboundWorksheet)
