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

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

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

class BulkPrintPackingList extends localize(i18next)(PageView) {
  static get properties() {
    return {
      pickingListConfig: Object,
      orderNos: Array,
      releaseOrders: Array
    }
  }

  static get styles() {
    return [
      MultiColumnFormStyles,
      css`
        :host {
          overflow-x: auto;
        }
        section {
          display: flex;
          flex-direction: column;
        }
        .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: row;
          flex: 1;
          overflow-y: auto;
        }
        .grist-column {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: 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);
        }

        @media print {
          section {
            break-before: page;
            break-after: page;

            margin: 0;
            padding: 0;
          }
        }
      `
    ]
  }

  get context() {
    var actions = [
      {
        title: i18next.t('button.back_to_list'),
        action: () => history.back(),
        ...CommonButtonStyles.back
      }
    ]

    return {
      title: i18next.t('title.bulk_print_packing_list'),
      actions,
      printable: {
        accept: ['preview'],
        content: this
      }
    }
  }

  render() {
    const releaseOrders = this.releaseOrders

    return html` ${releaseOrders.map(releaseOrder => {
      const orderInventories = {
        records: (releaseOrder.orderInventories || []).map(orderInventory => {
          return {
            ...orderInventory,
            productName: orderInventory.product.name,
            sku: orderInventory.product.sku,
            uom: orderInventory.inventory.uom
          }
        })
      }
      return html`
        <section>
          <div class="form-container">
            <form name="releaseOrder" class="multi-column-form">
              <fieldset>
                <legend>${releaseOrder.name}</legend>
                <label>${i18next.t('label.company')}</label>
                <input name="bizplaceName" value="${releaseOrder?.bizplace.name}" readonly />

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

                <label>${i18next.t('label.ref_no_2')}</label>
                <input name="refNo2" value="${releaseOrder?.refNo2 || ''}" readonly />

                <label>${i18next.t('label.ref_no_3')}</label>
                <input name="refNo3" value="${releaseOrder?.refNo3 || ''}" readonly />

                <label>${i18next.t('label.release_date')}</label>
                <input name="releaseDate" type="date" value="${releaseOrder.releaseDate}" readonly />

                <label ?hidden="${!!!releaseOrder?.attentionTo}">${i18next.t('label.attention_to')}</label>
                <input
                  name="attentionto"
                  .value="${releaseOrder?.attentionTo}"
                  ?hidden="${!!!releaseOrder?.attentionTo}"
                  readonly
                />

                <label ?hidden="${!!!releaseOrder?.phone1}">${i18next.t('label.phone_no')}</label>
                <input name="phone1" .value="${releaseOrder?.phone1}" ?hidden="${!!!releaseOrder?.phone1}" readonly />

                <label ?hidden="${!!!releaseOrder?.deliveryAddress1}">${i18next.t('label.delivery_address')}</label>
                <textarea
                  name="deliveryAddress1"
                  .value="${releaseOrder?.deliveryAddress1}"
                  ?hidden="${!!!releaseOrder?.deliveryAddress1}"
                  rows="5"
                  readonly
                ></textarea>

                <label>${i18next.t('label.order_remark')}</label>
                <textarea rows="5" readonly></textarea>
              </fieldset>
            </form>

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

          <div class="grist">
            <data-grist
              .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
              .config=${this.pickingListConfig}
              .data=${orderInventories}
            ></data-grist>
          </div>
        </section>
      `
    })}`
  }

  async pageUpdated(changes, lifecycle) {
    if (this.active) {
      this.orderNos = lifecycle.params.orderNo.split(',') || []
      await this.fetchReleaseOrders()
    }
  }

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

  pageInitialized() {
    this.pickingListConfig = {
      pagination: { infinite: true },
      rows: { appendable: false },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'string',
          name: 'sku',
          header: i18next.t('field.sku'),
          width: 120
        },
        {
          type: 'string',
          name: 'productName',
          header: i18next.t('field.name'),
          width: 180
        },
        {
          type: 'string',
          name: 'packingType',
          header: i18next.t('field.packing_type'),
          width: 180
        },
        {
          type: 'float',
          name: 'packingSize',
          header: i18next.t('field.packing_size'),
          width: 100
        },
        {
          type: 'number',
          name: 'releaseQty',
          header: i18next.t('field.qty'),
          width: 100
        },
        {
          type: 'number',
          name: 'releaseUomValue',
          header: i18next.t('field.uom_value'),
          width: 120
        },
        {
          type: 'string',
          name: 'uom',
          header: i18next.t('field.uom'),
          width: 120
        }
      ]
    }
  }

  async fetchReleaseOrders() {
    if (!this.orderNos?.length) return
    const response = await client.query({
      query: gql`
        query releaseGoods($filters: [Filter!], $sortings: [Sorting!]) {
          releaseGoods(filters: $filters, sortings: $sortings) {
            items {
              id
              name
              refNo
              refNo2
              refNo3
              releaseDate
              attentionTo
              phone1
              deliveryAddress1
              remark
              bizplace {
                id
                name
              }
              orderInventories {
                id
                releaseQty
                packingType
                packingSize
                releaseUomValue
                inventory {
                  uom
                }
                product {
                  sku
                  name
                }
              }
            }
          }
        }
      `,
      variables: {
        filters: [{ name: 'name', operator: 'in', value: this.orderNos }],
        sortings: [{ name: 'updatedAt', desc: true }]
      }
    })

    if (!response.errors) {
      this.releaseOrders = response.data.releaseGoods.items || []
    }
  }
}
window.customElements.define('bulk-print-packing-list', BulkPrintPackingList)
