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 { openPopup } from '@things-factory/layout-base'
import { client, CustomAlert, navigate, PageView } from '@things-factory/shell'
import { CommonButtonStyles, ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

import { fetchSettingRule } from '../../fetch-setting-value'
import { RTM_OPTIONS, WORKSHEET_STATUS, WORKSHEET_TYPE } from '../constants'

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

class SingleOutboundWorksheet 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,
      assignee: String,
      config: Object,
      data: Object,
      targetBizplace: 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
    })

    actions.push({
      title: i18next.t('button.activate'),
      action: this._activateBulkWorksheet.bind(this),
      ...CommonButtonStyles.activate
    })

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

  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) {
        if (params.range) {
          params.toDate = new Date().toISOString().split('T')[0]
          switch (params.range) {
            case '1d':
              params.fromDate = new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().split('T')[0]
              break
            case '1w':
              params.fromDate = new Date(new Date().setDate(new Date().getDate() - 7)).toISOString().split('T')[0]
              break
            case '1m':
              params.fromDate = new Date(new Date().setMonth(new Date().getMonth() - 1)).toISOString().split('T')[0]
              break
            default:
              break
          }
        }
        const updatedFields = applyParamsToFields(this._searchFields, params)
        this._searchFields = updatedFields
        const searchForm = this.searchForm
        if (searchForm) {
          searchForm.fields = updatedFields
        }
      }
      this.dataGrist.fetch()
    }
  }

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

    this._searchFields = [
      {
        name: 'releaseGoodNo',
        label: i18next.t('field.order_info'),
        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: 'type',
        label: i18next.t('field.type'),
        type: 'select',
        options: [
          { value: '' },
          {
            name: WORKSHEET_TYPE.PICKING.name,
            value: WORKSHEET_TYPE.PICKING.value
          },
          {
            name: WORKSHEET_TYPE.LOADING.name,
            value: WORKSHEET_TYPE.LOADING.value
          },
          {
            name: WORKSHEET_TYPE.WAREHOUSE_RETURN.name,
            value: WORKSHEET_TYPE.WAREHOUSE_RETURN.value
          }
        ],
        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]
      },
      {
        label: i18next.t('field.rtm'),
        name: 'releaseGoodRtm',
        type: 'select',
        options: [{ value: '' }, ...RTM_OPTIONS.map(option => ({ name: option.label, value: option.value }))],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.cross_docking'),
        name: 'releaseGoodCrossDocking',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.transporter'),
        name: 'releaseGoodCourierOption',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.packing'),
        name: 'releaseGoodPackingOption',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.priority_delivery'),
        name: 'releaseGoodPriorityDelivery',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      }
    ]

    this.config = {
      list: {
        fields: ['releaseGood', 'bizplace', 'type', 'releaseRefNo', 'status', 'startedAt', 'endedAt']
      },
      rows: { selectable: { multiple: true }, appendable: false },
      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.PICKING.value) {
                this.navigatePickingRelatedPages(record)
              } else if (type === WORKSHEET_TYPE.LOADING.value) {
                navigate(`worksheet_loading/${record.name}`)
              } else if (type === WORKSHEET_TYPE.WAREHOUSE_RETURN.value) {
                navigate(`worksheet_return/${record.name}`)
              }
            }
          }
        },
        {
          type: 'object',
          name: 'releaseGood',
          header: i18next.t('field.release_good_no'),
          imex: {
            header: i18next.t('field.release_good_no'),
            key: 'releaseGood.name',
            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: 'array' },
          sortable: true,
          width: 180
        },
        {
          type: 'string',
          name: 'releaseGoodRtm',
          header: i18next.t('field.rtm'),
          imex: { header: i18next.t('field.rtm'), key: 'releaseGoodRtm', width: 40, type: 'string' },
          sortable: true,
          width: 120
        },
        {
          type: 'boolean',
          name: 'releaseGoodCrossDocking',
          header: i18next.t('field.cross_docking'),
          imex: { header: i18next.t('field.cross_docking'), key: 'releaseGoodCrossDocking', width: 20, type: 'string' },
          width: 100
        },
        {
          type: 'boolean',
          name: 'releaseGoodCourierOption',
          header: i18next.t('field.transporter'),
          imex: { header: i18next.t('field.transporter'), key: 'releaseGoodCourierOption', width: 20, type: 'string' },
          width: 60
        },
        {
          type: 'boolean',
          name: 'releaseGoodPackingOption',
          header: i18next.t('field.packing'),
          imex: { header: i18next.t('field.packing'), key: 'releaseGoodPackingOption', width: 20, type: 'string' },
          width: 60
        },
        {
          type: 'boolean',
          name: 'releaseGoodPriorityDelivery',
          header: i18next.t('field.priority_delivery'),
          imex: {
            header: i18next.t('field.priority_delivery'),
            key: 'releaseGoodPriorityDelivery',
            width: 20,
            type: 'string'
          },
          width: 120
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          imex: { header: i18next.t('field.company'), key: 'bizplace.name', width: 20, type: 'string' },
          sortable: true,
          width: 240
        },
        {
          type: 'string',
          name: 'type',
          header: i18next.t('field.type'),
          imex: { header: i18next.t('field.type'), key: 'type', width: 20, type: 'string' },
          sortable: true,
          width: 100
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          imex: { header: i18next.t('field.status'), key: 'status', width: 20, 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: 20, type: 'string' },
          sortable: true,
          width: 200
        },
        {
          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

    // Handle type filter: convert 'eq' to 'in' format if user selected a type, or add default filter
    const typeFilterIndex = filters.findIndex(filter => filter.name === 'type')
    if (typeFilterIndex >= 0) {
      const typeFilter = filters[typeFilterIndex]
      // Convert 'eq' operator to 'in' format for consistency with backend
      if (typeFilter.operator === 'eq' && typeFilter.value) {
        filters[typeFilterIndex] = {
          name: 'type',
          operator: 'in',
          value: [typeFilter.value]
        }
      } else if (!typeFilter.value || typeFilter.value === '') {
        // Remove empty type filter and use default instead
        filters.splice(typeFilterIndex, 1)
        filters.push({
          name: 'type',
          operator: 'in',
          value: [WORKSHEET_TYPE.PICKING.value, WORKSHEET_TYPE.LOADING.value, WORKSHEET_TYPE.WAREHOUSE_RETURN.value]
        })
      }
    } else {
      // Only add default type filter if user hasn't selected a type filter
      filters.push({
        name: 'type',
        operator: 'in',
        value: [WORKSHEET_TYPE.PICKING.value, WORKSHEET_TYPE.LOADING.value, WORKSHEET_TYPE.WAREHOUSE_RETURN.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]
      })
    }

    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
              assignee {
                id
                name
              }
              releaseGood {
                id
                name
                description
                refNo
                rtm
                crossDocking
                courierOption
                packingOption
                priorityDelivery
              }
              bizplace {
                id
                name
                description
              }
              name
              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

      if (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.map(item => {
            return {
              ...item,
              releaseRefNo: item.releaseGood.refNo || '',
              releaseGoodRtm: item.releaseGood.rtm || '',
              releaseGoodCrossDocking: item.releaseGood.crossDocking,
              releaseGoodCourierOption: item.releaseGood.courierOption,
              releaseGoodPackingOption: item.releaseGood.packingOption,
              releaseGoodPriorityDelivery: item.releaseGood.priorityDelivery
            }
          }) || {}
      }
    }
  }

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

  _assignPicker() {
    try {
      let selectedData = this.dataGrist.selected
      if (selectedData.length <= 0) throw new Error(i18next.t('text.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 activateBulkPicking($worksheetNo: [String!]!) {
            activateBulkPicking(worksheetNo: $worksheetNo) {
              id
              name
            }
          }
        `,
        variables: {
          worksheetNo: 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
    }
  }

  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="${'single'}"
            .sourceWorksheetType="${'PICKING'}"
          ></route-label-popup>
        `,
        {
          backdrop: true,
          size: 'large',
          title: i18next.t('title.print_route_label')
        }
      )
    } catch (e) {
      this._showToast(e)
    }
  }

  _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 {
        id: item.id,
        ...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 (record[column.imex.key] === 'Invalid Date') {
              record[column.imex.key] = ''
            }
            return record
          }, {})
      }
    })
    return { header: headerSetting, data: data }
  }

  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_picking/${record.name}?${searchParams.toString()}`)
      }
    } else {
      navigate(`worksheet_picking/${record.name}`)
    }
  }

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

window.customElements.define('single-outbound-worksheet', SingleOutboundWorksheet)
