import '@things-factory/barcode-ui'
import '@things-factory/grist-ui'
import '../components/popup-note'
import '../vas/related-vas-list'
import './adjust-pallet-qty'
import './carton-label-popup'
import './pallet-label-popup'
import './putaway/putaway-worksheet-generate-popup'

import gql from 'graphql-tag'
import { css, html } from 'lit-element'

import { getCodeByName } from '@things-factory/code-base'
import { MultiColumnFormStyles } from '@things-factory/form-ui'
import { getRenderer } from '@things-factory/grist-ui'
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 } from '@things-factory/styles'
import { isMobileDevice, sleep } from '@things-factory/utils'

import { fetchSettingRule } from '../../fetch-setting-value'
import {
  ARRIVAL_NOTICE,
  ORDER_VAS_STATUS,
  VAS_BATCH_AND_PRODUCT_TYPE,
  VAS_BATCH_NO_TYPE,
  VAS_ETC_TYPE,
  VAS_PRODUCT_TYPE,
  WORKSHEET_STATUS
} from '../constants'

//vas --inbound
class WorksheetUnloading extends localize(i18next)(PageView) {
  static get properties() {
    return {
      _statusOptions: Array,
      _worksheetNo: String,
      _worksheetStatus: String,
      _ganNo: String,
      _enableCartonLabel: Boolean,
      config: Object,
      data: Object,
      vasData: Object,
      vasGristConfig: Object,
      vasWorksheetNo: String,
      vasWorksheetDetails: Object,
      crossDocking: Boolean,
      looseItem: Boolean,
      unpacking: Boolean
    }
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow-x: auto;
        }
        .form-container {
          display: flex;
        }
        .form-container > form {
          flex: 1;
        }
        barcode-tag {
          width: 100px;
          height: 100px;
          margin: 10px;
        }
        .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);
        }
        related-vas-list {
          flex: 1;
        }
      `
    ]
  }

  get context() {
    let actions = [
      {
        title: i18next.t('button.back'),
        action: () => navigate('inbound_worksheets'),
        ...CommonButtonStyles.back
      }
    ]

    if (this._worksheetStatus === WORKSHEET_STATUS.DEACTIVATED.value) {
      actions.push({
        title: i18next.t('button.activate'),
        action: this._activateWorksheet.bind(this),
        ...CommonButtonStyles.activate
      })
    }

    if (this._worksheetStatus === WORKSHEET_STATUS.EXECUTING.value) {
      if (this._enableCartonLabel) {
        actions.push({
          title: i18next.t('button.carton_label_print'),
          action: this._openCartonLabelPrintPopup.bind(this),
          ...CommonButtonStyles.label
        })
      } else {
        actions.push({
          title: i18next.t('button.lot_label_print'),
          action: this._openLotLabelPrintPopup.bind(this),
          ...CommonButtonStyles.label
        })
      }
      /* Remove button, process automated */
      // if (this.data?.records?.some(wsd => wsd.status === WORKSHEET_STATUS.PARTIALLY_UNLOADED.value)) {
      //   actions.push({
      //     title: i18next.t('button.create_putaway_worksheet'),
      //     action: this._showPutawayWorksheetPopup.bind(this),
      //     ...CommonButtonStyles.add
      //   })
      // }
    }

    return {
      title: i18next.t('title.worksheet_unloading'),
      actions,
      printable: { accept: ['preview'], content: this },
      help: 'operato-wms/inbound/worksheet-unloading'
    }
  }

  render() {
    return html`
      <div class="form-container">
        <form class="multi-column-form">
          <fieldset>
            <legend>${i18next.t('title.unloading')}</legend>

            <label>${i18next.t('label.options')}</label>
            <div options-wrap>
              <input name="crossDocking" type="checkbox" .checked="${this.crossDocking}" disabled />
              <label>${i18next.t('label.cross_docking')}</label>

              <input name="looseItem" type="checkbox" .checked="${this.looseItem}" disabled />
              <label>${i18next.t('label.loose_item')}</label>
            </div>

            <label>${i18next.t('label.arrival_notice')}</label>
            <input name="arrivalNotice" readonly />

            <label>${i18next.t('label.company')}</label>
            <input name="bizplace" readonly />

            <label>${i18next.t('label.warehouse')}</label>
            <input name="warehouse" readonly />

            <label>${i18next.t('label.staging_area')}</label>
            <input name="bufferLocation" readonly />

            <label>${i18next.t('label.ref_no')}${`1`}</label>
            <input name="refNo" readonly />

            <label>${i18next.t('label.ref_no')}${`2`}</label>
            <input name="refNo2" readonly />

            <label>${i18next.t('label.ref_no')}${`3`}</label>
            <input name="refNo3" readonly />

            <label>${i18next.t('label.status')}</label>
            <select name="status" disabled>
              ${this._statusOptions.map(
                status => html`
                  <option value="${status.name}" ?selected="${this._worksheetStatus === status.name}">
                    ${i18next.t(`label.${status.description}`)}
                  </option>
                `
              )}
            </select>
          </fieldset>
        </form>

        <barcode-tag bcid="qrcode" .value=${this._ganNo} showLogo="true"></barcode-tag>
      </div>

      <div class="grist">
        <h2><mwc-icon>list_alt</mwc-icon>${i18next.t('title.product')}</h2>
        <data-grist
          id="grist"
          .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
          .config=${this.config}
          .data="${this.data}"
        ></data-grist>

        <!-- temporarily hidden by SAM(SUM) -->
        <!-- ${this.vasData?.records
          ? html`
              <h2><mwc-icon>list_alt</mwc-icon>${i18next.t('title.vas')}</h2>
              <data-grist
                id="vas-grist"
                .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
                .config=${this.vasGristConfig}
                .data="${this.vasData}"
              ></data-grist>
            `
          : ''} -->
      </div>
    `
  }

  constructor() {
    super()
    this._statusOptions = []
    this._ganNo = ''
    this.unpacking = false
    this.vasData = { records: [] }
  }

  async pageUpdated(changes) {
    if (this.active && (changes.resourceId || this._worksheetNo)) {
      if (changes.resourceId) {
        this._worksheetNo = changes.resourceId
      }
      await this.fetchWorksheet()
      // await this.fetchVas()
      // await this.fetchOrderVas()
      this.updateContext()
      await this._updateGristConfig()
    }
  }

  async pageInitialized() {
    this._statusOptions = await getCodeByName('WORKSHEET_STATUS')
    this.preConfig = {
      rows: {
        appendable: false,
        handlers: {
          click: (columns, data, column, record, rowIndex) => {
            if (column.name === 'palletQty' && !record.isPalletized) {
              this._showPalletQtyAdjustPopup(record)
            } else if (column.name === 'issue' && record.issue) {
              this._showIssueNotePopup(record)
            }
          }
        }
      },
      list: { fields: ['remark', 'batchId', 'product', 'palletQty', 'packQty', 'totalUomValue', 'status'] },
      pagination: { infinite: true },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_id'),
          width: 150
        },
        {
          type: 'string',
          name: 'productSku',
          header: i18next.t('field.sku'),
          width: 150
        },
        {
          type: 'object',
          name: 'product',
          header: i18next.t('field.product'),
          width: 300
        },
        {
          type: 'string',
          name: 'productBrand',
          header: i18next.t('field.brand'),
          width: 150
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          width: 120
        },
        {
          type: 'integer',
          name: 'palletQty',
          header: i18next.t('field.pallet_qty'),
          width: 80
        },
        {
          type: 'float',
          name: 'packQty',
          header: i18next.t('field.pack_qty'),
          width: 80
        },
        {
          type: 'float',
          name: 'totalUomValue',
          header: i18next.t('field.total_uom'),
          width: 120
        },
        {
          type: 'string',
          name: 'batchIdRef',
          header: i18next.t('field.batch_no_ref'),
          width: 150
        },
        {
          type: 'string',
          name: 'remark',
          header: i18next.t('field.remark'),
          width: 300
        },
        {
          type: 'string',
          name: 'description',
          header: i18next.t('field.comment'),
          width: 200
        }
      ]
    }
    this.vasGristConfig = {
      list: { fields: ['targetType', 'targetDisplay', 'packingType'] },
      pagination: { infinite: true },
      rows: {
        appendable: false
      },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'set',
          header: i18next.t('field.set'),
          width: 80
        },
        {
          type: 'string',
          name: 'targetType',
          header: i18next.t('field.target_type'),
          width: 190
        },
        {
          type: 'string',
          name: 'target',
          header: i18next.t('field.target'),
          record: {
            renderer: (value, column, record, rowIndex, field) => {
              if (record.targetType === VAS_BATCH_NO_TYPE) {
                return getRenderer()(record.targetBatchId, column, record, rowIndex, field)
              } else if (record.targetType === VAS_PRODUCT_TYPE) {
                return getRenderer('object')(record.targetProduct, column, record, rowIndex, field)
              } else if (record.targetType === VAS_BATCH_AND_PRODUCT_TYPE) {
                return getRenderer()(
                  `${record.targetBatchId} / ${record.targetProduct.name}`,
                  column,
                  record,
                  rowIndex,
                  field
                )
              } else if (record.targetType === VAS_ETC_TYPE) {
                return getRenderer()(record.otherTarget, column, record, rowIndex, field)
              }
            }
          },

          width: 250
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          width: 120
        },
        {
          type: 'integer',
          name: 'qty',
          header: i18next.t('field.qty'),
          width: 80
        },
        {
          type: 'integer',
          name: 'uomValue',
          header: i18next.t('field.uom_value'),
          width: 80
        },
        {
          type: 'object',
          name: 'vas',
          header: i18next.t('field.vas'),
          record: { options: { queryName: 'vass' } },
          width: 200
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          width: 150
        },
        {
          type: 'string',
          name: 'remark',
          header: i18next.t('field.remark'),
          width: 350
        },
        {
          type: 'string',
          name: 'description',
          header: i18next.t('field.comment'),
          width: 350
        }
      ]
    }
    this.config = this.preConfig
  }

  updated(changedProps) {
    if (changedProps.has('_ganNo') && this._ganNo) {
      this.checkHavingVas(this._ganNo)
    }
  }

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

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

  get _ganNoInput() {
    return this.shadowRoot.querySelector('input[name=arrivalNotice]')
  }

  async fetchWorksheet() {
    if (!this._worksheetNo) return
    const response = await client.query({
      query: gql`
        query inboundWorksheetDetails($name: String!) {
          inboundWorksheetDetails(name: $name) {
            id
            name
            status
            arrivalNotice {
              id
              name
              description
              refNo
              refNo2
              refNo3
              crossDocking
              looseItem
            }
            orderVass {
              vas {
                name
                operationGuide
                operationGuideType
              }
              set
              targetType
              targetBatchId
              targetProduct {
                id
                name
                description
              }
              packingType
              qty
              uomValue
              otherTarget
              description
              remark
              status
              operationGuide
            }
            bizplace {
              id
              name
              description
              domain {
                id
                name
              }
            }
            bufferLocation {
              name
              warehouse {
                name
              }
            }
            worksheetDetails {
              id
              name
              description
              targetProduct {
                product {
                  id
                  sku
                  brand
                  name
                  type
                  description
                }
                manufactureDate
                batchId
                adjustedBatchId
                batchIdRef
                name
                description
                packingType
                packQty
                remark
                totalUomValue
                palletQty
                palletId
              }
              status
              issue
            }
          }
        }
      `,
      variables: { name: this._worksheetNo }
    })

    if (!response.errors) {
      const worksheet = response.data.inboundWorksheetDetails
      const worksheetDetails = worksheet.worksheetDetails
      const partnerDomainId = worksheet.bizplace.domain.id
      this._worksheetStatus = worksheet.status
      this._gan = worksheet && worksheet.arrivalNotice
      this._ganNo = (this._gan && this._gan.name) || ''
      this._bizplace = worksheet.bizplace.name
      this.crossDocking = worksheet?.arrivalNotice?.crossDocking
      this.looseItem = worksheet?.arrivalNotice?.looseItem

      this._fillupForm({
        ...worksheet,
        arrivalNotice: worksheet.arrivalNotice.name,
        bizplace: worksheet.bizplace.name,
        bufferLocation: worksheet.bufferLocation.name,
        warehouse: worksheet.bufferLocation.warehouse.name,
        refNo: worksheet.arrivalNotice.refNo,
        refNo2: worksheet.arrivalNotice.refNo2,
        refNo3: worksheet.arrivalNotice.refNo3
      })

      this.data = {
        records: worksheetDetails
          .map(worksheetDetail => {
            const targetProduct = worksheetDetail.targetProduct
            return {
              ...worksheetDetail,
              ...worksheetDetail.targetProduct,
              initialBatchId: targetProduct.batchId,
              productSku: targetProduct.product.sku,
              productBrand: targetProduct.product.brand,
              hasBatchChanges: targetProduct && targetProduct.batchId !== targetProduct.initialBatchId ? false : true,
              isPalletized:
                targetProduct && targetProduct.palletQty && Number(targetProduct.palletQty) > 0 ? true : false,
              isLooseItem: worksheet.arrivalNotice.looseItem ? true : false,
              refNo: worksheet.arrivalNotice.refNo,
              refNo2: worksheet.arrivalNotice.refNo2,
              refNo3: worksheet.arrivalNotice.refNo3
            }
          })
          .sort((a, b) => {
            const skuComparison = a.product.sku.localeCompare(b.product.sku)
            if (skuComparison !== 0) {
              return skuComparison
            }
            return a.targetProduct.batchId.localeCompare(b.targetProduct.batchId)
          })
      }

      const orderVass = worksheet.orderVass
      if (orderVass?.length > 0) {
        this.vasData = {
          records: orderVass
            .sort((a, b) => a.set - b.set)
            .map(orderVas => {
              return {
                ...orderVas,
                set: orderVas.set ? `Set ${orderVas.set}` : ''
              }
            })
        }
      }

      this._enableCartonLabel = await fetchSettingRule('enable-carton-label', partnerDomainId)
    }
  }

  async fetchVas() {
    const response = await client.query({
      query: gql`
        query vas($name: String!) {
          vas(name: $name) {
            id
            name
            description
          }
        }
      `,
      variables: { name: 'Unpacking' }
    })

    if (!response.errors) {
      this.vasData = response.data.vas
    }
  }

  async fetchOrderVas() {
    if (!this._worksheetNo) return

    let filters = [
      { name: 'vas', operator: 'eq', value: this.vasData.id },
      { name: 'arrivalNotice', operator: 'eq', value: this._gan.id },
      { name: 'status', operator: 'noteq', value: ORDER_VAS_STATUS.TERMINATED.value }
    ]

    const response = await client.query({
      query: gql`
        query orderVass($filters: [Filter!]) {
          orderVass(filters: $filters) {
            items {
              id
            }
            total
          }
        }
      `,
      variables: { filters }
    })

    if (!response.errors) {
      const total = response.data.orderVass.total
      if (total > 0) {
        this.unpacking = true
      }
    }
  }

  async checkHavingVas(orderNo) {
    const response = await client.query({
      query: gql`
        query havingVas($orderType: String!, $orderNo: String!) {
          havingVas(orderType: $orderType, orderNo: $orderNo) {
            name
            worksheetDetails {
              name
              description
              targetVas {
                id
                name
                status
                vas {
                  id
                  name
                }
              }
            }
          }
        }
      `,
      variables: { orderType: ARRIVAL_NOTICE.value, orderNo }
    })

    if (!response.errors) {
      this.vasWorksheetNo = response.data.havingVas?.name

      this.vasWorksheetDetails = response.data.havingVas?.worksheetDetails
      if (this.vasWorksheetDetails) {
        this.vasWorksheetDetails.forEach(wsd => {
          let vas = wsd.targetVas.vas

          if (String(vas.name).toLowerCase() === i18next.t('text.unpacking')) {
            if (wsd.targetVas.status !== ORDER_VAS_STATUS.TERMINATED.value) {
              this.unpacking = true
            }
          }
        })
      }
    }
  }

  _getVasWorksheetDetails() {
    return this.vasWorksheetDetails.map(worksheetDetail => {
      return {
        name: worksheetDetail.name,
        description: worksheetDetail.description
      }
    })
  }

  async _updateGristConfig() {
    const statusColumnConfig = {
      type: 'string',
      name: 'status',
      header: i18next.t('field.status'),
      width: 100
    }

    const issueColumnConfig = {
      type: 'string',
      name: 'issue',
      header: i18next.t('field.issue'),
      width: 200
    }

    const initialBatchColumnConfig = {
      type: 'string',
      name: 'adjustedBatchId',
      header: i18next.t('field.adjusted_batch_id'),
      width: 200
    }

    this.preConfig.columns.map(column => {
      if (column.name === 'description') {
        column.record = { ...column.record, editable: this._worksheetStatus === WORKSHEET_STATUS.DEACTIVATED.value }
      }
    })

    const statusColumnIdx = this.preConfig?.columns?.findIndex(col => col.name === 'status')
    const issueColumnIdx = this.preConfig?.columns?.findIndex(col => col.name === 'issue')
    const hasStatusColumn = statusColumnIdx >= 0

    if (!hasStatusColumn && this._worksheetStatus !== WORKSHEET_STATUS.DEACTIVATED.value) {
      this.preConfig.columns = [...this.preConfig.columns, statusColumnConfig, issueColumnConfig]
    } else if (hasStatusColumn && this._worksheetStatus === WORKSHEET_STATUS.DEACTIVATED.value) {
      this.preConfig.columns.splice(statusColumnIdx)
      this.preConfig.columns.splice(issueColumnIdx)
    } else if (
      this._worksheetStatus === WORKSHEET_STATUS.PENDING_APPROVAL.value ||
      this._worksheetStatus === WORKSHEET_STATUS.PENDING_ADJUSTMENT.value
    ) {
      if (!this.preConfig.columns.some(e => e.name === 'adjustedBatchId')) {
        const batchIdColumnIdx = this.preConfig.columns.map(c => c.name).indexOf('batchId')
        this.preConfig.columns.splice(batchIdColumnIdx, 0, initialBatchColumnConfig)
      }
    }

    this.config = { ...this.preConfig }
    this.data = { ...this.data }
  }

  _fillupForm(data) {
    for (let key in data) {
      Array.from(this.form.querySelectorAll('input, select')).forEach(field => {
        if (field.name === key && field.type === 'checkbox') {
          field.checked = data[key]
        } else if (field.name === key && field.type === 'datetime-local') {
          const datetime = Number(data[key])
          const timezoneOffset = new Date(datetime).getTimezoneOffset() * 60000
          field.value = new Date(datetime - timezoneOffset).toISOString().slice(0, -1)
        } else if (field.name === key) {
          if (data[key] instanceof Object) {
            const objectData = data[key]
            field.value = `${objectData.name} ${objectData.description ? `(${objectData.description})` : ''}`
          } else {
            field.value = data[key]
          }
        }
      })
    }
  }

  _showPalletQtyAdjustPopup(record) {
    openPopup(
      html`
        <adjust-pallet-qty
          .record="${record}"
          @pallet-adjusted="${e => {
            this.data = {
              ...this.data,
              records: this.data.records.map(item => {
                if (item.name === record.name) {
                  item.palletQty = e.detail.palletQty
                }

                return item
              })
            }
          }}"
        ></adjust-pallet-qty>
      `,
      {
        backdrop: true,
        size: 'medium',
        title: i18next.t('title.adjust_pallet_qty')
      }
    )
  }

  _showIssueNotePopup(record) {
    openPopup(html` <popup-note title="${record.batchId}" value="${record.issue}" .readonly="${true}"></popup-note> `, {
      backdrop: true,
      size: 'medium',
      title: i18next.t('title.issue_note')
    })
  }

  async _activateWorksheet() {
    try {
      //this._checkPalletQty()

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

      if (!result.value) return

      if (this.crossDocking) {
        result = await CustomAlert({
          title: i18next.t('title.cross_docking'),
          text: i18next.t('text.picking_worksheet_will_be_activated'),
          confirmButton: { text: i18next.t('button.confirm') },
          cancelButton: { text: i18next.t('button.cancel') }
        })

        if (!result.value) return
      }

      if (this.unpacking) {
        result = await CustomAlert({
          title: i18next.t('title.unpacking'),
          text: i18next.t('text.proceed_to_unpacking'),
          confirmButton: { text: i18next.t('button.confirm') },
          cancelButton: { text: i18next.t('button.cancel') }
        })

        if (!result.value) {
          return
        } else {
          await this._activateVasWorksheet()
          return
        }
      }

      const response = await client.mutate({
        mutation: gql`
          mutation activateUnloading($worksheetNo: String!, $unloadingWorksheetDetails: [WorksheetDetailPatch]) {
            activateUnloading(worksheetNo: $worksheetNo, unloadingWorksheetDetails: $unloadingWorksheetDetails) {
              name
            }
          }
        `,
        variables: { worksheetNo: this._worksheetNo, unloadingWorksheetDetails: this._getUnloadingWorksheetDetails() }
      })

      if (!response.errors) {
        this._showToast({ message: i18next.t('text.worksheet_activated') })

        await this.fetchWorksheet()
        this.updateContext()
        await this._updateGristConfig()
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  async _activateVasWorksheet() {
    try {
      const response = await client.mutate({
        mutation: gql`
          mutation activateVas($worksheetNo: String!, $vasWorksheetDetails: [WorksheetDetailPatch]) {
            activateVas(worksheetNo: $worksheetNo, vasWorksheetDetails: $vasWorksheetDetails) {
              name
            }
          }
        `,
        variables: { worksheetNo: this.vasWorksheetNo, vasWorksheetDetails: this._getVasWorksheetDetails() }
      })
      if (!response.errors) {
        this._showToast({ message: i18next.t('text.worksheet_activated') })
        navigate(`vas_worksheets`)
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  // _checkPalletQty() { //remove check pallet qty restriction
  //   if (!this.grist.dirtyData.records.every(record => record.palletQty && Number(record.palletQty) > 0))
  //     throw new Error(i18next.t('text.there_is_no_pallet_qty'))
  // }

  _getUnloadingWorksheetDetails() {
    return (this.grist.dirtyData.records || []).map(worksheetDetail => {
      let _tempObj = {
        name: worksheetDetail.name,
        batchId: worksheetDetail.batchId,
        description: worksheetDetail.description
      }

      if (worksheetDetail?.initialBatchId) {
        _tempObj.initialBatchId = worksheetDetail.initialBatchId
      }

      return _tempObj
    })
  }

  async _openLotLabelPrintPopup() {
    await sleep(1010)
    const _pallets = {
      records: this.data.records.map(record => {
        return {
          id: record.id,
          palletId: record.palletId,
          batchId: record.batchId,
          product: record.product,
          palletQty: record.palletQty,
          printQty: record.palletQty,
          packingType: record.packingType,
          bizplace: this._bizplace
        }
      })
    }
    openPopup(html` <pallet-label-popup .pallets="${_pallets}"></pallet-label-popup> `, {
      backdrop: true,
      size: 'large',
      title: i18next.t('title.lot_label')
    })
  }

  async _openCartonLabelPrintPopup() {
    await sleep(1010)
    openPopup(
      html` <carton-label-popup .bizplaceName="${this._bizplace}" .data="${this.data}"></carton-label-popup> `,
      {
        backdrop: true,
        size: 'medium',
        title: i18next.t('title.carton_label')
      }
    )
  }

  async _showPutawayWorksheetPopup() {
    await sleep(1010)
    openPopup(
      html`
        <putaway-worksheet-generate-popup
          .crossDocking="${this.crossDocking}"
          .arrivalNotice="${this._gan}"
          @completed="${async () => {
            await this.fetchWorksheet()
            this.updateContext()
          }}"
        ></putaway-worksheet-generate-popup>
      `,
      {
        backdrop: true,
        size: 'large',
        title: i18next.t('title.generate_putaway_worksheet')
      }
    )
  }

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

  //sort values
  _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
    }
  }
}

window.customElements.define('worksheet-unloading', WorksheetUnloading)
