import '@things-factory/biz-ui'
import '@things-factory/barcode-ui'
import '@things-factory/grist-ui'
import '@things-factory/product-ui'
import '../../order/reverse-kitting-order/reverse-kitting-pallet-label-popup'

import gql from 'graphql-tag'
import { css, html } from 'lit-element'
import { connect } from 'pwa-helpers/connect-mixin.js'

import { MultiColumnFormStyles } from '@things-factory/form-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { openPopup } from '@things-factory/layout-base'
import { client, CustomAlert, navigate, PageView, store } from '@things-factory/shell'
import { CommonButtonStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'

import { fetchLocationSortingRule } from '../../../fetch-location-sorting-rule'
import { INVENTORY_STATUS, LOCATION_SORTING_RULE, ORDER_STATUS } from '../../constants'

class ReverseKittingOrderDetail extends connect(store)(localize(i18next)(PageView)) {
  static get styles() {
    return [
      MultiColumnFormStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow-x: auto;
        }
        .form-container {
          display: flex;
        }
        .form-container > form {
          flex: 1;
        }
        .container {
          flex: 1;
          display: flex;
          overflow-y: auto;
          min-height: 50vh;
        }
        .grist {
          background-color: var(--main-section-background-color);
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        h2 {
          padding: var(--subtitle-padding);
          font: var(--subtitle-font);
          color: var(--subtitle-text-color);
          border-bottom: var(--subtitle-border-bottom);
        }
        .grist h2 {
          margin: var(--grist-title-margin);
          border: var(--grist-title-border);
          font: var(--grist-title-font);
          color: var(--secondary-color);
        }

        .grist h2 mwc-icon {
          vertical-align: middle;
          margin: var(--grist-title-icon-margin);
          font-size: var(--grist-title-icon-size);
          color: var(--grist-title-icon-color);
        }

        h2 + data-grist {
          padding-top: var(--grist-title-with-grid-padding);
        }

        [hidden] {
          display: none;
        }
      `
    ]
  }

  static get properties() {
    return {
      _reverseKittingNo: String,
      inventoryGristConfig: Object,
      inventoryData: Object,
      _bizplaces: Object,
      _bizplace: Object,
      _bizplaceId: String,
      _bizplaceName: String,
      locationSortingRules: Object,
      _editable: Boolean,
      _newOrder: Boolean,
      _status: String
    }
  }

  get inventoryGrist() {
    return this.shadowRoot.querySelector('data-grist#inventory-grist')
  }

  get reverseKittingOrderForm() {
    return this.shadowRoot.querySelector('form[name=reverseKittingOrder]')
  }

  render() {
    return html`
      <div class="form-container">
        <form name="reverseKittingOrder" class="multi-column-form" autocomplete="off">
          <fieldset>
            <legend>${i18next.t('title.reverse_kitting_no')}: ${this._reverseKittingNo}</legend>
            <label>${i18next.t('label.company')}</label>
            <input type="hidden" name="bizplaceId" value="${this._bizplaceId}" />
            <input
              readonly
              type="text"
              name="bizplaceName"
              value="${this._bizplaceName}"
              @click="${this._openBizplacesSelector.bind(this)}"
            />

            ${!this._newOrder
              ? html`<label>${i18next.t('label.status')}</label><input readonly type="text" name="status" />`
              : ''}
          </fieldset>
        </form>

        ${!this._newOrder ? html`<barcode-tag bcid="qrcode" .value=${this._reverseKittingNo} showLogo="true"></barcode-tag>` : ''}
      </div>
      <div class="container">
        <div class="grist">
          <h2><mwc-icon>list_alt</mwc-icon>${i18next.t('title.target_products')}</h2>

          <data-grist
            id="inventory-grist"
            .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
            .config=${this.inventoryGristConfig}
            .data=${this.inventoryData}
            @record-change="${this._onProductChangeHandler.bind(this)}"
          ></data-grist>
        </div>
      </div>
    `
  }

  constructor() {
    super()
    this._reverseKittingNo = 'new'
    this._newOrder = this._reverseKittingNo == 'new' ? true : false
    this.inventoryData = { records: [] }
  }

  get context() {
    let actions = [
      {
        title: i18next.t('button.to_listing'),
        action: this._navigateToList.bind(this),
        ...CommonButtonStyles.back
      }
    ]

    if (this._newOrder) {
      actions = [
        ...actions,
        {
          title: i18next.t('button.create'),
          action: this._generateReverseKittingOrder.bind(this),
          ...CommonButtonStyles.add
        }
      ]
    } else {
      if (this._status === ORDER_STATUS.PENDING.value) {
        actions = [
          ...actions,
          {
            title: i18next.t('button.delete'),
            action: this._deleteReverseKittingOrder.bind(this),
            ...CommonButtonStyles.delete
          },
          {
            title: i18next.t('button.confirm'),
            action: this._confirmReverseKittingOrder.bind(this),
            ...CommonButtonStyles.confirm
          }
        ]
      } else if (this._status === ORDER_STATUS.READY_TO_EXECUTE.value) {
        actions = [
          ...actions,
          {
            title: i18next.t('button.cancel'),
            action: this._cancelReverseKittingOrder.bind(this),
            ...CommonButtonStyles.cancel
          },
          {
            title: i18next.t('button.activate'),
            action: this._activateReverseKittingOrder.bind(this),
            ...CommonButtonStyles.activate
          }
        ]
      } else if (this._status === ORDER_STATUS.EXECUTING.value) {
        actions.push({
          title: i18next.t('button.lot_label_print'),
          action: this._openLotLabelPrintPopup.bind(this),
          ...CommonButtonStyles.label
        })
      }
    }

    return {
      title: i18next.t('title.reverse_kitting_order_detail'),
      actions,
      printable: { accept: ['preview'], content: this },
      help: 'operato-wms/reverse-kitting-order/reverse-kitting-order-detail'
    }
  }

  async pageUpdated(changes) {
    this._clearView()
    if (this.active) {
      if (changes.resourceId) {
        this._reverseKittingNo = changes.resourceId
      } else if (!this._reverseKittingNo) {
        this._reverseKittingNo = 'new'
      }

      this._newOrder = this._reverseKittingNo == 'new' ? true : false

      if (!this._newOrder) {
        await this.fetchReverseKittingOrder()
      }
      this.updateContext()
    }
  }

  async pageInitialized() {
    this.locationSortingRules = await fetchLocationSortingRule(LOCATION_SORTING_RULE.INVENTORY_ASSIGNMENT.value)
    await this.fetchBizplaces()

    if (!this._newOrder) {
      await this.fetchReverseKittingOrder()
    }

    this._configureInventoryGrist()
  }

  _configureInventoryGrist() {
    let editable = this._bizplaceId ? (this._newOrder ? true : false) : false

    this.inventoryGristConfig = {
      pagination: { infinite: true },
      rows: { selectable: { multiple: true } },
      list: { fields: ['inventory', 'product', 'location', 'releaseQty'] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'close',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              if (this._newOrder) {
                const newData = data.records.filter((_, idx) => idx !== rowIndex)
                this.inventoryData = { ...this.inventoryData, records: newData }
                this.inventoryGrist.dirtyData.records = newData
                this._updateInventoryList()
              }
            }
          }
        },
        {
          type: 'object',
          name: 'inventory',
          header: i18next.t('field.inventory_list'),
          record: {
            editable: editable,
            options: {
              queryName: 'inventoriesByPallet',
              basicArgs: {
                filters: [
                  { name: 'status', operator: 'eq', value: INVENTORY_STATUS.STORED.value },
                  { name: 'bizplace', operator: 'in', value: [this._bizplaceId] }
                ],
                locationSortingRules: this.locationSortingRules
              },
              nameField: 'batchId',
              descriptionField: 'palletId',
              select: [
                { name: 'id', hidden: true },
                { name: 'name', hidden: true },
                { name: 'uom', hidden: true },
                { name: 'remainUomValue', hidden: true },
                { name: 'product', type: 'object', hidden: true },
                { name: 'palletId', header: i18next.t('field.lot_id') },
                { name: 'productSKU', header: i18next.t('field.sku') },
                { name: 'productName', header: i18next.t('field.product_info') },
                { name: 'batchId', header: i18next.t('field.batch_id') },
                {
                  name: 'location',
                  type: 'object',
                  queryName: 'locations',
                  field: 'name'
                },
                { name: 'packingType', header: i18next.t('field.packing_type') },
                { name: 'packingSize', header: i18next.t('field.packing_size') },
                { name: 'remainQty', type: 'float', header: i18next.t('field.remain_qty') },
                {
                  name: 'remainUomValueWithUom',
                  type: 'string',
                  header: i18next.t('field.total_uom_value')
                },
                { name: 'batchIdRef', header: i18next.t('field.batch_no_ref') },
                {
                  name: 'remark',
                  type: 'string',
                  header: i18next.t('field.remark')
                }
              ],
              list: {
                fields: ['palletId', 'productName', 'batchId', 'location', 'remainUomValue', 'batchIdRef']
              }
            }
          },
          width: 250
        },
        { name: 'batchId', hidden: true },
        {
          type: 'string',
          name: 'productSKU',
          header: i18next.t('field.sku'),
          width: 100
        },
        {
          type: 'string',
          name: 'productName',
          header: i18next.t('field.product_name'),
          width: 150
        },
        {
          type: 'code',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          record: { codeName: 'PACKING_TYPES' },
          width: 150
        },
        {
          type: 'integer',
          name: 'qty',
          header: i18next.t('field.qty'),
          record: { editable: editable, options: { min: 0 } },
          width: 100
        },
        {
          type: 'float',
          name: 'uomValue',
          header: i18next.t('field.uom_value'),
          record: { editable: editable, options: { min: 0 } },
          width: 100
        },
        {
          type: 'string',
          name: 'productCombination',
          header: i18next.t('field.combination'),
          handlers: {
            click: this._openProductCombinations.bind(this)
          },
          width: 300
        }
      ]
    }
  }

  _onProductChangeHandler(event) {
    const changeRecord = event.detail.after
    const changedColumn = event.detail.column.name

    try {
      if (changedColumn === 'qty') {
        this._validateQty(changeRecord.qty, changeRecord.remainQty)
      }
      this._updateQtyAndUomValue(event.detail.row, changedColumn, event.detail.before, changeRecord)
    } catch (e) {
      const beforeValue = event.detail.before && event.detail.before[event.detail.column.name]
      if (beforeValue) {
        event.detail.after[event.detail.column.name] = beforeValue
      } else {
        delete event.detail.after[event.detail.column.name]
      }
      this._showToast(e)
    }
  }

  _updateQtyAndUomValue(rowIndex, columnName, initialRecord, newRecord) {
    let roundedUomValue = 0
    let qty = 0

    if (columnName == 'qty' || columnName == 'uomValue') {
      if (initialRecord?.remainQty && initialRecord?.remainUomValue) {
        let packageUomValue = initialRecord.remainUomValue / initialRecord.remainQty

        if (columnName == 'qty') qty = newRecord.qty || 0
        else qty = Math.round(newRecord.uomValue / packageUomValue)

        roundedUomValue = Math.round(qty * packageUomValue * 100) / 100
      }
    }

    this.inventoryData = {
      ...this.inventoryData,
      ...this.inventoryGrist.dirtyData,
      records: this.inventoryGrist.dirtyData.records.map((record, idx) => {
        if (idx == rowIndex && (columnName == 'qty' || columnName == 'uomValue')) {
          if (columnName == 'uomValue') record.qty = qty
          record.uomValue = roundedUomValue
        }

        return {
          ...record,
          ...record.inventory,
          name: record.name ? record.name : idx
        }
      })
    }

    this._updateInventoryList()
  }

  async fetchBizplaces() {
    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) {
      const bizplaces = response.data.partnersBizplaces.items
      if (bizplaces.length == 1) {
        this._bizplace = bizplaces[0]
        this._bizplaceId = bizplaces[0].id
        this._bizplaceName = bizplaces[0].name
      } else {
        this._bizplace = null
        this._bizplaceId = ''
        this._bizplaceName = ''
      }

      return bizplaces
    }
  }

  async fetchReverseKittingOrder() {
    try {
      if (this._newOrder) return

      this.inventoryGrist.showSpinner()
      const response = await client.query({
        query: gql`
          query reverseKittingOrder($name: String!) {
            reverseKittingOrder(name: $name) {
              id
              name
              status
              bizplace {
                id
                name
                description
              }
              reverseKittingOrderInventories {
                id
                name
                set
                targetType
                targetBatchId
                targetProduct {
                  id
                  name
                  description
                }
                inventory {
                  id
                  name
                  batchId
                  batchIdRef
                  palletId
                  product {
                    id
                    sku
                    name
                    description
                  }
                  productName
                  packingType
                  packingSize
                  uom
                  location {
                    id
                    name
                  }
                  status
                }
                qty
                uomValue
                otherTarget
                operationGuide
                status
                description
                remark
              }
            }
          }
        `,
        variables: { name: this._reverseKittingNo }
      })

      if (!response.errors) {
        const reverseKittingOrder = response.data.reverseKittingOrder
        this._bizplaceId = reverseKittingOrder.bizplace.id
        this._bizplaceName = reverseKittingOrder.bizplace.name
        this._status = reverseKittingOrder.status
        this.inventoryData = {
          records: reverseKittingOrder.reverseKittingOrderInventories.map(reverseKittingOI => {
            return {
              ...reverseKittingOI,
              ...reverseKittingOI.inventory,
              orderReverseKittingId: reverseKittingOI.id,
              productSKU: reverseKittingOI.inventory.product.sku,
              productName: reverseKittingOI.inventory.product.name,
              productCombination: this.displayProductCombination(JSON.parse(reverseKittingOI.operationGuide))
            }
          })
        }

        this._fillupRKOForm(reverseKittingOrder)
        this.updateContext()
      }
    } catch (e) {
      this._showToast(e)
    } finally {
      this.inventoryGrist.hideSpinner()
    }
  }

  _updateInventoryList() {
    const _selectedInv = (this.inventoryGrist.dirtyData.records || []).map(record => record.inventory.id)

    this.inventoryGristConfig = {
      ...this.inventoryGristConfig,
      columns: this.inventoryGristConfig.columns.map(column => {
        if (column.name === 'inventory') {
          column.record.options.basicArgs = {
            ...column.record.options.basicArgs,
            filters: [...column.record.options.basicArgs.filters.filter(filter => filter.name !== 'id')]
          }

          if (_selectedInv.length)
            column.record.options.basicArgs.filters = [
              ...column.record.options.basicArgs.filters,
              {
                name: 'id',
                value: _selectedInv,
                operator: 'notin'
              }
            ]
        }

        return column
      })
    }

    this.inventoryData = {
      ...this.inventoryGrist.dirtyData,
      records: this.inventoryGrist.dirtyData.records.map(record => {
        return {
          ...record,
          ...record.inventory,
          product: {
            id: record.inventory.productId,
            name: record.inventory.productName
          }
        }
      })
    }
  }

  async _generateReverseKittingOrder() {
    try {
      this.checkInventoryValidity()
      const result = await CustomAlert({
        title: i18next.t('title.are_you_sure'),
        text: `${i18next.t('text.create')} ${i18next.t('text.reverse_kitting_order')}`,
        confirmButton: { text: i18next.t('button.confirm') },
        cancelButton: { text: i18next.t('button.cancel') }
      })

      if (!result.value) return

      const reverseKittingOrder = this._getReverseKittingOrder()

      const response = await client.mutate({
        mutation: gql`
          mutation generateReverseKittingOrder($reverseKittingOrder: NewReverseKittingOrder!) {
            generateReverseKittingOrder(reverseKittingOrder: $reverseKittingOrder) {
              id
              name
            }
          }
        `,
        variables: { reverseKittingOrder }
      })

      if (!response.errors) {
        this.inventoryData = { records: [] }
        this._showToast({ message: i18next.t('text.reverse_kitting_order_created') })
        this._reverseKittingNo = response.data.generateReverseKittingOrder.name
        this._newOrder = false
        await this.fetchReverseKittingOrder()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  async _activateReverseKittingOrder() {
    let result = await CustomAlert({
      title: i18next.t('title.are_you_sure'),
      text: `${i18next.t('text.activate')} ${i18next.t('text.reverse_kitting_order')}`,
      confirmButton: { text: i18next.t('button.confirm') },
      cancelButton: { text: i18next.t('button.cancel') }
    })

    if (!result.value) return

    try {
      const response = await client.mutate({
        mutation: gql`
          mutation activateReverseKittingOrder($name: String!) {
            activateReverseKittingOrder(name: $name) {
              name
            }
          }
        `,
        variables: { name: this._reverseKittingNo }
      })

      if (!response.errors) {
        this._showToast({ message: i18next.t('text.reverse_kitting_order_activated') })
        await this.fetchReverseKittingOrder()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  async _cancelReverseKittingOrder() {
    let result = await CustomAlert({
      title: i18next.t('title.are_you_sure'),
      text: `${i18next.t('text.cancel')} ${i18next.t('text.reverse_kitting_order')}`,
      confirmButton: { text: i18next.t('button.confirm') },
      cancelButton: { text: i18next.t('button.cancel') }
    })

    if (!result.value) return

    try {
      const response = await client.mutate({
        mutation: gql`
          mutation cancelReverseKittingOrder($name: String!) {
            cancelReverseKittingOrder(name: $name) {
              name
            }
          }
        `,
        variables: { name: this._reverseKittingNo }
      })

      if (!response.errors) {
        this._showToast({ message: i18next.t('text.reverse_kitting_order_cancelled') })
        await this.fetchReverseKittingOrder()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  async _confirmReverseKittingOrder() {
    let result = await CustomAlert({
      title: i18next.t('title.are_you_sure'),
      text: `${i18next.t('text.confirm')} ${i18next.t('text.reverse_kitting_order')}`,
      confirmButton: { text: i18next.t('button.confirm') },
      cancelButton: { text: i18next.t('button.cancel') }
    })

    if (!result.value) return

    try {
      const response = await client.mutate({
        mutation: gql`
          mutation confirmReverseKittingOrder($name: String!) {
            confirmReverseKittingOrder(name: $name) {
              name
            }
          }
        `,
        variables: { name: this._reverseKittingNo }
      })

      if (!response.errors) {
        this._showToast({ message: i18next.t('text.reverse_kitting_order_confirmed') })
        await this.fetchReverseKittingOrder()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  async _deleteReverseKittingOrder() {
    let result = await CustomAlert({
      title: i18next.t('title.are_you_sure'),
      text: `${i18next.t('text.delete')} ${i18next.t('text.reverse_kitting_order')}`,
      confirmButton: { text: i18next.t('button.confirm') },
      cancelButton: { text: i18next.t('button.cancel') }
    })

    if (!result.value) return

    try {
      const response = await client.mutate({
        mutation: gql`
          mutation deleteReverseKittingOrder($name: String!) {
            deleteReverseKittingOrder(name: $name)
          }
        `,
        variables: { name: this._reverseKittingNo }
      })

      if (!response.errors) {
        this._showToast({ message: i18next.t('text.reverse_kitting_order_deleted') })
        this._navigateToList()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  checkInventoryValidity() {
    let records = this.inventoryGrist.dirtyData?.records

    if (!records || !records.length) {
      throw new Error(i18next.t('text.there_is_no_inventory'))
    }

    if (records.some(record => !record.inventory && !record.inventory.id))
      throw new Error(i18next.t('text.invalid_inventory'))

    if (records.some(record => !record.productCombination))
      throw new Error(i18next.t('text.invalid_product_combination'))

    records.forEach(record => this._validateQty(record.qty, record.remainQty))

    return true
  }

  _validateQty(qty, remainQty) {
    if (!qty || qty <= 0 || qty > remainQty) {
      throw new Error(i18next.t('text.invalid_quantity_input'))
    }
  }

  _getReverseKittingOrder() {
    return {
      reverseKittingOrderInventories: this._getReverseKittingOrderInventories(),
      customerBizplaceId: this._bizplaceId
    }
  }

  _getReverseKittingOrderInventories() {
    if (
      !this.inventoryGrist.dirtyData ||
      !this.inventoryGrist.dirtyData.records ||
      !this.inventoryGrist.dirtyData.records.length
    ) {
      return []
    }

    const records = this.inventoryGrist.dirtyData.records

    return records
      .map((record, idx) => {
        let result = {
          set: idx + 1,
          batchId: record.batchId,
          name: record.productName,
          packingType: record.packingType,
          qty: record.qty,
          uomValue: record.uomValue
        }

        if (record.operationGuide && record.operationGuide.data) {
          result.operationGuide = JSON.stringify(record.operationGuide)
        }

        result.inventory = { id: record.id }

        return result
      })
      .flat()
  }

  _openBizplacesSelector() {
    openPopup(
      html`
        <popup-partner-bizplaces-selector
          @selected="${e => {
            this._bizplaceId = e.detail.id
            this._bizplaceName = e.detail.name
            const inventoryRecords = this.inventoryGrist.dirtyData.records
            if (inventoryRecords && inventoryRecords.length > 0) {
              // clear all data in grist
              this.inventoryGrist.dirtyData.records.length = 0
            }
            this._configureInventoryGrist()
          }}"
        ></popup-partner-bizplaces-selector>
      `,
      {
        backdrop: true,
        size: 'large',
        title: i18next.t('title.select_company')
      }
    )
  }

  _openLotLabelPrintPopup() {
    const _pallets = {
      records: this.inventoryData.records.map(record => {
        const operationGuide = JSON.parse(record.operationGuide)
        let qty = operationGuide.data.productCombinationSets?.length || 0

        return {
          id: record.orderReverseKittingId,
          palletId: record.palletId,
          batchId: record.batchId,
          product: record.product,
          qty,
          printQty: qty,
          packingType: record.packingType,
          bizplace: this._bizplace
        }
      })
    }
    openPopup(
      html` <reverse-kitting-pallet-label-popup .pallets="${_pallets}"></reverse-kitting-pallet-label-popup> `,
      {
        backdrop: true,
        size: 'large',
        title: i18next.t('title.lot_label')
      }
    )
  }

  _openProductCombinations(columns, data, column, record, rowIndex) {
    if (this._newOrder) {
      if (record.inventory.product.id) {
        openPopup(
          html`
            <product-combination-selection-popup
              .productId="${record.inventory.product.id}"
              .packingType="${record.packingType}"
              .packingSize="${record.packingSize}"
              .bizplaceId="${this._bizplaceId}"
              @selected="${e => {
                let operationGuide = { data: { ...e.detail } }
                let productCombinationSets = operationGuide.data.productCombinationSets.map(item => {
                  return {
                    ...item,
                    qty: item.qty * record.qty
                  }
                })
                operationGuide.data.productCombinationSets = productCombinationSets

                this.inventoryGrist.dirtyData.records = this.inventoryGrist.dirtyData.records.map(item => {
                  if (item.id == record.id) {
                    item.operationGuide = operationGuide
                    item.productCombination = this.displayProductCombination(operationGuide)
                  }

                  return item
                })

                this.inventoryData = {
                  ...this.inventoryData,
                  records: [...this.inventoryGrist.dirtyData.records]
                }
              }}"
            ></product-combination-selection-popup>
          `,
          {
            backdrop: true,
            size: 'large',
            title: `${record.productSKU}`
          }
        )
      }
    }
  }

  displayProductCombination(record) {
    const combinationName = record.data.productCombinationName
    let productCombinationSets = record.data.productCombinationSets
    return productCombinationSets
      .reduce((acc, curr, currentIndex, arr) => {
        let display = `COMBINATION SET ${currentIndex + 1}: ${combinationName} SKU: ${curr?.productSku} QTY: ${
          curr?.qty
        }`

        if (display.trim() != '') acc.push(display)

        return acc
      }, [])
      .join(' | ')
  }

  _fillupRKOForm(data) {
    this._fillupForm(this.reverseKittingOrderForm, data)
  }

  _fillupForm(form, data) {
    for (let key in data) {
      Array.from(form.querySelectorAll('input, textarea, select')).forEach(field => {
        if (field.name === key && field.type === 'checkbox') {
          field.checked = data[key]
        } else if (field.name === key) {
          field.value = data[key]
        }
      })
    }
  }

  _clearView() {
    this.reverseKittingOrderForm.reset()
    this._bizplaceId = ''
    this._bizplaceName = ''
    this.inventoryData = { records: [] }
  }

  _navigateToList() {
    navigate(`reverse_kitting_orders`)
  }

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

window.customElements.define('reverse-kitting-order-detail', ReverseKittingOrderDetail)
