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

import { client, CustomAlert, PageView, store, gqlContext } from '@things-factory/shell'
import { connect } from 'pwa-helpers/connect-mixin'
import { css, html } from 'lit-element'
import { getCodeByName } from '@things-factory/code-base'
import { ScrollbarStyles, CommonButtonStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import { i18next, localize } from '@things-factory/i18n-base'
import { openPopup } from '@things-factory/layout-base'
import { TOTE_LABEL_SETTING_KEY } from '../constants'
import { DirectPrinter } from '@things-factory/barcode-base'
import gql from 'graphql-tag'

class ToteList extends connect(store)(localize(i18next)(PageView)) {
  static get properties() {
    return {
      config: Object,
      data: Object,
      importHandler: Object,
      _isDeletedRecord: Boolean,
      _toteStatus: Object,
      _toteLabel: Object
    }
  }

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

  constructor() {
    super()
    this._isDeletedRecord = false
  }

  get context() {
    let actions = []

    actions.push(
      {
        title: i18next.t('button.print_label'),
        action: this._printToteLabel.bind(this),
        ...CommonButtonStyles.label
      },
      {
        title: i18next.t('button.bulk_update_status'),
        action: this._bulkUpdateToteStatus.bind(this),
        ...CommonButtonStyles.label
      },
      {
        title: i18next.t('button.save'),
        action: this._saveTote.bind(this),
        ...CommonButtonStyles.save
      }
    )

    if (this._isDeletedRecord) {
      actions.push({
        title: i18next.t('button.restore'),
        action: this._undeleteTotes.bind(this),
        ...CommonButtonStyles.submit
      })
    }

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

    return {
      title: i18next.t('title.tote'),
      actions,
      exportable: {
        name: i18next.t('title.tote'),
        data: this._exportableData.bind(this)
      },
      importable: {
        handler: this._importableData.bind(this)
      },
      help: 'operato-wms/master-data/tote'
    }
  }

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

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

    this._searchFields = [
      {
        label: i18next.t('field.tote_no'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.company'),
        name: 'bizplace',
        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' }
      },
      {
        label: i18next.t('field.status'),
        name: 'status',
        type: 'select',
        options: [
          { value: '' },
          ...this._toteStatus.map(status => {
            return {
              name: status.name,
              value: status.name
            }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.deleted'),
        name: 'deleted_at',
        type: 'checkbox',
        props: { searchOper: 'eq' }
      }
    ]

    this.config = {
      list: {
        fields: ['toteNo', 'company', 'status']
      },
      rows: { selectable: { multiple: true } },
      pagination: { limit: 50, pages: [50, 100, 200, 500] },
      columns: [
        { type: 'gutter', gutterName: 'dirty' },
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.tote_no'),
          imex: { header: i18next.t('field.tote_no'), key: 'name', width: 50, type: 'string' },
          record: {
            editable: true
          },
          sortable: true,
          width: 100
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          imex: {
            header: i18next.t('field.company'),
            key: 'bizplace.name',
            width: 50,
            type: 'array',
            arrData: partners.map(partner => {
              return {
                name: partner.name,
                id: partner.id
              }
            })
          },
          record: {
            editable: true,
            options: {
              queryName: 'partnersBizplaces'
            }
          },
          sortable: true,
          width: 250
        },
        {
          type: 'code',
          name: 'status',
          header: i18next.t('field.status'),
          imex: {
            header: i18next.t('field.status'),
            key: 'status',
            width: 50,
            type: 'array',
            arrData: this._toteStatus.map(toteStatus => {
              return {
                name: toteStatus.name
              }
            })
          },
          record: {
            editable: true,
            codeName: 'TOTE_STATUS'
          },
          sortable: true,
          width: 130
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          sortable: true,
          width: 150
        },
        {
          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')
  }

  _importableData(records) {
    setTimeout(() => {
      openPopup(
        html`
          <import-pop-up
            .records=${records}
            .config=${{
              rows: this.config.rows,
              columns: [...this.config.columns.filter(column => column.imex !== undefined)]
            }}
            .importHandler="${this.importHandler.bind(this)}"
          ></import-pop-up>
        `,
        {
          backdrop: true,
          size: 'large',
          title: i18next.t('title.import')
        }
      )
    }, 500)
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    const response = await client.query({
      query: gql`
        query totes($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          totes(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              bizplace {
                id
                name
                description
              }
              domain {
                id
                name
              }
              status
              updatedAt
              updater {
                id
                name
                description
              }
              deletedAt
            }
            total
          }
        }
      `,
      variables: {
        filters: this.searchForm.queryFilters,
        pagination: { page, limit },
        sortings: sorters
      }
    })

    if (!response.error) {
      this._isDeletedRecord = response.data.totes.items[0]?.deletedAt ? true : false

      this.updateContext()

      return {
        total: response.data.totes.total || 0,
        records: response.data.totes.items || []
      }
    }
  }

  async importHandler(patches) {
    let existedToteStatus = this._toteStatus
    try {
      patches.map(itm => {
        if (itm.cuFlag == '+') {
          if (!itm.bizplace?.id || !itm.status || !itm.name) {
            throw new Error(i18next.t('text.empty_value_in_list'))
          }
          let foundToteStatus = existedToteStatus.find(exist => exist.name == itm.status)
          if (!foundToteStatus) {
            throw new Error(i18next.t('text.tote_status_does_not_exist'))
          }
        }
      })

      this.dataGrist.showSpinner()
      const response = await client.query({
        query: gql`
          mutation updateMultipleTote($patches: [TotePatch!]!) {
            updateMultipleTote(patches: $patches) {
              name
            }
          }
        `,
        variables: {
          patches
        }
      })
      if (!response.errors) {
        history.back()
        this.dataGrist.fetch()
        document.dispatchEvent(
          new CustomEvent('notify', {
            detail: {
              message: i18next.t('text.data_imported_successfully')
            }
          })
        )
      }
      this.dataGrist.hideSpinner()
    } catch (e) {
      this._showToast(e)
    }
  }

  async _saveTote() {
    try {
      let patches = this.dataGrist.exportPatchList({ flagName: 'cuFlag' })
      this._validateTote(patches)
      if (patches && patches.length) {
        this.dataGrist.showSpinner()
        const response = await client.mutate({
          mutation: gql`
            mutation updateMultipleTote($patches: [TotePatch!]!) {
              updateMultipleTote(patches: $patches) {
                name
              }
            }
          `,
          variables: {
            patches
          }
        })

        if (!response.errors) {
          this.dataGrist.fetch()
          document.dispatchEvent(
            new CustomEvent('notify', {
              detail: {
                message: i18next.t('text.data_updated_successfully')
              }
            })
          )
        }
        this.dataGrist.hideSpinner()
      }
    } catch (e) {}
  }

  _validateTote(patches) {
    for (const patch of patches) {
      if (patch.cuFlag == '+') {
        if (!patch.bizplace) {
          throw document.dispatchEvent(
            new CustomEvent('notify', {
              detail: {
                message: i18next.t('text.company_field_is_empty')
              }
            })
          )
        }

        if (!patch.name) {
          throw document.dispatchEvent(
            new CustomEvent('notify', {
              detail: {
                message: i18next.t('text.tote_field_is_empty')
              }
            })
          )
        }

        if (!patch.status) {
          throw document.dispatchEvent(
            new CustomEvent('notify', {
              detail: {
                message: i18next.t('text.status_field_is_empty')
              }
            })
          )
        }
      }
    }
  }

  async _deleteTote() {
    CustomAlert({
      title: i18next.t('text.are_you_sure'),
      text: i18next.t('text.you_can_still_restore_after_deleting'),
      type: 'warning',
      confirmButton: { text: i18next.t('button.delete'), color: '#22a6a7' },
      cancelButton: { text: 'cancel', color: '#cfcfcf' },
      callback: async result => {
        if (result.value) {
          this.dataGrist.showSpinner()
          const id = this.dataGrist.selected.map(record => record.id)
          if (id && id.length > 0) {
            const response = await client.query({
              query: gql`
                mutation deleteTotes($id: [String!]!) {
                  deleteTotes(ids: $id)
                }
              `,
              variables: { id }
            })

            if (!response.errors) {
              this.dataGrist.fetch()
              document.dispatchEvent(
                new CustomEvent('notify', {
                  detail: {
                    message: i18next.t('text.data_deleted_successfully')
                  }
                })
              )
            }
          } else {
            CustomAlert({
              title: i18next.t('text.nothing_selected'),
              text: i18next.t('text.there_is_nothing_to_delete')
            })
          }
          this.dataGrist.hideSpinner()
        }
      }
    })
  }

  async _undeleteTotes() {
    const ids = this.dataGrist.selected.map(record => record.id)

    if (!ids?.length) {
      return this.showToast(i18next.t('text.there_is_nothing_to_restore'))
    }

    const answer = await CustomAlert({
      type: 'warning',
      title: i18next.t('button.restore'),
      text: i18next.t('text.are_you_sure'),
      confirmButton: { text: i18next.t('button.restore') },
      cancelButton: { text: i18next.t('button.cancel') }
    })

    if (!answer.value) return

    const response = await client.mutate({
      mutation: gql`
        mutation undeleteTotes($ids: [String!]!) {
          undeleteTotes(ids: $ids)
        }
      `,
      variables: { ids },
      context: gqlContext()
    })

    if (!response.errors) {
      CustomAlert({
        type: 'success',
        title: i18next.t('text.completed'),
        text: i18next.t('text.data_restore_successfully'),
        confirmButton: { text: i18next.t('button.confirm') }
      })
      this.dataGrist.fetch()
    }
  }

  async _bulkUpdateToteStatus() {
    try {
      let selectedIds
      if (this.dataGrist.selected && this.dataGrist.selected.length > 0) {
        selectedIds = this.dataGrist.selected.map(record => record.id)
      } else {
        throw new Error('Please select at least 1 record to update status')
      }

      const statusFilter = (await this.searchForm.getQueryFilters()).find(x => x.name === 'status')

      if (!statusFilter) {
        throw new Error('Please choose a status to update')
      }

      const result = await CustomAlert({
        title: i18next.t('title.are_you_sure'),
        text: i18next.t('text.bulk_update_status'),
        confirmButton: { text: i18next.t('button.confirm') },
        cancelButton: { text: i18next.t('button.cancel') }
      })

      if (!result.value) return

      const response = await client.mutate({
        mutation: gql`
          mutation bulkUpdateToteStatus($ids: [String!]!, $status: String!) {
            bulkUpdateToteStatus(ids: $ids, status: $status)
          }
        `,
        variables: {
          ids: selectedIds,
          status: statusFilter.value
        }
      })

      if (!response.errors) {
        await CustomAlert({
          title: i18next.t('title.bulk_update_status'),
          text: i18next.t('text.status_update_completed'),
          confirmButton: { text: i18next.t('button.confirm') }
        })

        this.dataGrist.fetch()
      }
    } 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
              domain {
                id
                name
              }
            }
          }
        }
      `,
      variables: { filters }
    })
    this.targetBizplace = response.data.partnersBizplaces || {}
    if (!response.errors) {
      this._partnersList = response.data.partnersBizplaces
      return response.data.partnersBizplaces.items
    }
  }

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

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

  _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)
            return record
          }, {})
      }
    })

    return { header: headerSetting, data: data }
  }

  async _printToteLabel() {
    var labelId = this._toteLabel && this._toteLabel.id
    let items = []

    if (this.dataGrist.selected && this.dataGrist.selected.length > 0) {
      items = this.dataGrist.selected
    }

    if (!labelId) {
      document.dispatchEvent(
        new CustomEvent('notify', {
          detail: {
            level: 'error',
            message: `${i18next.t('text.no_label_setting_was_found')}. ${i18next.t('text.please_check_your_setting')}`
          }
        })
      )
    } else {
      if (items.length <= 0) {
        document.dispatchEvent(
          new CustomEvent('notify', {
            detail: {
              level: 'error',
              message: `${i18next.t('text.there_is_no_selected_items')}`
            }
          })
        )
      }

      for (var item of items) {
        var searchParams = new URLSearchParams()

        /* for tote record mapping */
        searchParams.append('name', item.name)
        searchParams.append('bizplace', item.bizplace.name)
        searchParams.append('warehouse', item.domain.name)

        try {
          const response = await fetch(`label-command/${labelId}?${searchParams.toString()}`, {
            method: 'GET'
          })

          if (response.status !== 200) {
            throw `Error: Can't get label command from server (response: ${response.status})`
          }

          var command = await response.text()

          if (!this.printer) {
            this.printer = new DirectPrinter()
          }

          await this.printer.print(command)
        } catch (ex) {
          document.dispatchEvent(
            new CustomEvent('notify', {
              detail: {
                level: 'error',
                message: ex,
                ex
              }
            })
          )

          delete this.printer
          break
        }
      }
    }
  }

  stateChanged(state) {
    var toteLabelSetting = state.dashboard[TOTE_LABEL_SETTING_KEY]
    this._toteLabel = (toteLabelSetting && toteLabelSetting.board) || {}
  }

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

window.customElements.define('tote-list', ToteList)
