import '@things-factory/barcode-ui'
import { MultiColumnFormStyles } from '@things-factory/form-ui'
import '@things-factory/grist-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { getRenderer } from '@things-factory/grist-ui'
import { client, CustomAlert, navigate, PageView } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'
import { CommonButtonStyles } from '@things-factory/styles'
import gql from 'graphql-tag'
import { css, html } from 'lit-element'
import {
  WORKSHEET_STATUS,
  VAS_BATCH_NO_TYPE,
  VAS_PRODUCT_TYPE,
  VAS_BATCH_AND_PRODUCT_TYPE,
  VAS_ETC_TYPE
} from '../constants'

class WorksheetLoading extends localize(i18next)(PageView) {
  static get properties() {
    return {
      _worksheetNo: String,
      _worksheetStatus: String,
      _statusList: Array,
      vasData: Object,
      vasGristConfig: Object,
      _roNo: String,
      config: Object,
      data: Object
    }
  }

  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);
        }
      `
    ]
  }

  get context() {
    var actions = [
      {
        title: i18next.t('button.back'),
        action: () => history.back(),
        ...CommonButtonStyles.back
      }
    ]
    if (this._worksheetStatus === WORKSHEET_STATUS.DEACTIVATED.value) {
      actions.push({
        title: i18next.t('button.activate'),
        action: this._activateWorksheet.bind(this),
        ...CommonButtonStyles.activate
      })
    }

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

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

            <label>${i18next.t('label.options')}</label>
            <div options-wrap>
              <input id="ownCollection" type="checkbox" name="ownCollection" disabled />
              <label for="ownCollection">${i18next.t('label.own_collection')}</label>

              <input name="vas" type="checkbox" .checked="${this.vasData?.records}" disabled />
              <label>${i18next.t('field.vas')}</label>
            </div>

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

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

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

            <label>${i18next.t('label.status')}</label>
            <input
              name="status"
              value="${this._statusList.find(x => x.value == this._worksheetStatus)?.display || ''}"
              readonly
              disabled
            />
          </fieldset>
        </form>

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

      <div class="grist">
        <h2><mwc-icon>list_alt</mwc-icon>${i18next.t('title.inventory')}</h2>

        <data-grist
          id="grist"
          .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
          .config=${this.config}
          .data="${this.data}"
        ></data-grist>
        <!-- hides vas Grist -->
        <!-- 
        ${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._statusList = Object.keys(WORKSHEET_STATUS).map(key => {
      return { value: WORKSHEET_STATUS[key].value, display: WORKSHEET_STATUS[key].name }
    })
  }

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

  pageInitialized() {
    this.preConfig = {
      rows: { appendable: false },
      list: {
        fields: ['batchId', 'palletId', 'product', 'packingType', 'releaseQty', 'pickedQty', 'batchIdRef', 'status']
      },
      pagination: { infinite: true },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_id'),
          width: 100
        },
        {
          type: 'string',
          name: 'palletId',
          header: i18next.t('field.lot_id'),
          width: 150
        },
        {
          type: 'string',
          name: 'productSku',
          header: i18next.t('field.sku'),
          width: 150
        },
        {
          type: 'object',
          name: 'product',
          header: i18next.t('field.product'),
          width: 350
        },
        {
          type: 'string',
          name: 'productBrand',
          header: i18next.t('field.brand'),
          width: 150
        },
        {
          type: 'string',
          name: 'zone',
          header: i18next.t('field.zone'),
          width: 80
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          width: 100
        },
        {
          type: 'string',
          name: 'packingSize',
          header: i18next.t('field.packing_size'),
          width: 100
        },
        {
          type: 'float',
          name: 'releaseQty',
          header: i18next.t('field.release_qty'),
          width: 60
        },
        {
          type: 'float',
          name: 'pickedQty',
          header: i18next.t('field.picked_qty'),
          width: 60
        },
        {
          type: 'string',
          name: 'batchIdRef',
          header: i18next.t('field.batch_no_ref'),
          width: 100
        }
      ]
    }
    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
        }
      ]
    }
  }

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

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

  async fetchWorksheet() {
    if (!this._worksheetNo) return
    const response = await client.query({
      query: gql`
        query worksheet($name: String!) {
          worksheet(name: $name) {
            status
            releaseGood {
              name
              description
              refNo
              ownTransport
            }
            orderVass {
              vas {
                name
                operationGuide
                operationGuideType
              }
              set
              targetType
              targetBatchId
              targetProduct {
                id
                name
                description
              }
              packingType
              qty
              uomValue
              otherTarget
              description
              remark
              status
              operationGuide
            }
            bizplace {
              name
              description
            }
            worksheetDetails {
              name
              status
              description
              targetInventory {
                releaseQty
                pickedQty
                product {
                  sku
                  brand
                  name
                  description
                }
                inventory {
                  palletId
                  batchId
                  batchIdRef
                  packingType
                  packingSize
                  warehouse {
                    name
                    description
                  }
                  zone
                  qty
                }
              }
            }
          }
        }
      `,
      variables: {
        name: this._worksheetNo
      }
    })

    if (!response.errors) {
      const worksheet = response.data.worksheet
      const worksheetDetails = worksheet.worksheetDetails
      this._worksheetStatus = worksheet.status
      this._roNo = (worksheet.releaseGood && worksheet.releaseGood.name) || ''

      this._fillupForm({
        ...worksheet,
        releaseGood: worksheet.releaseGood.name,
        bizplace: worksheet.bizplace.name,
        refNo: worksheet.releaseGood.refNo,
        ownCollection: worksheet.releaseGood.ownTransport
      })
      this.data = {
        records: worksheetDetails.map(worksheetDetail => {
          return {
            ...worksheetDetail.targetInventory.inventory,
            name: worksheetDetail.name,
            description: worksheetDetail.description,
            status: worksheetDetail.status,
            product: worksheetDetail.targetInventory.product,
            productSku: worksheetDetail.targetInventory.product.sku,
            productBrand: worksheetDetail.targetInventory.product.brand,
            releaseQty: worksheetDetail.targetInventory.releaseQty,
            pickedQty: worksheetDetail.targetInventory.pickedQty,
            packingType: worksheetDetail.targetInventory.inventory.packingType
          }
        })
      }

      //vas
      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}` : ''
              }
            })
        }
      }
    }
  }

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

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

    if (
      !this.preConfig.columns.some(e => e.name === 'status') &&
      this._worksheetStatus !== WORKSHEET_STATUS.DEACTIVATED.value
    ) {
      this.preConfig.columns = [...this.preConfig.columns, statusColumnConfig]
    } else if (
      this.preConfig.columns.some(e => e.name === 'status') &&
      this._worksheetStatus === WORKSHEET_STATUS.DEACTIVATED.value
    ) {
      this.preConfig.columns.splice(this.preConfig.columns.map(e => e.name).indexOf('status'))
    }

    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) {
          if (data[key] instanceof Object) {
            const objectData = data[key]
            field.value = `${objectData.name} ${objectData.description ? `(${objectData.description})` : ''}`
          } else {
            field.value = data[key]
          }
        }
      })
    }
  }

  async _activateWorksheet() {
    try {
      const result = await CustomAlert({
        title: i18next.t('title.are_you_sure'),
        text: i18next.t('text.activate_loading_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 activateLoading($worksheetNo: String!, $loadingWorksheetDetails: [WorksheetDetailPatch]) {
            activateLoading(worksheetNo: $worksheetNo, loadingWorksheetDetails: $loadingWorksheetDetails) {
              name
            }
          }
        `,
        variables: {
          worksheetNo: this._worksheetNo,
          loadingWorksheetDetails: this._getLoadingWorksheetDetails()
        }
      })
      if (!response.errors) {
        this._showToast({ message: i18next.t('text.worksheet_activated') })
        await this.fetchWorksheet()
        this.updateContext()
        navigate(`single_outbound_worksheets`)
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  _getLoadingWorksheetDetails() {
    return this.grist.dirtyData.records.map(worksheetDetail => {
      return {
        name: worksheetDetail.name,
        description: worksheetDetail.description
      }
    })
  }

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

window.customElements.define('worksheet-loading', WorksheetLoading)
