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, CustomAlert, navigate, PageView } from '@things-factory/shell'
import { CommonButtonStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import { REPLENISHMENT_CONFIG, ORDER_TYPES, ORDER_STATUS } from '../constants'
import { showToast } from '../../util/index'
import { getCodeByName } from '@things-factory/code-base'

class ReplenishmentDetail extends 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;
        }
        barcode-tag {
          width: 100px;
          height: 100px;
          margin: 10px;
        }
        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);
        }

        search-form {
          overflow: visible;
        }
      `
    ]
  }

  static get properties() {
    return {
      searchFields: Array,
      config: Object,
      _pageType: String,
      _status: String,
      _orderNo: String
    }
  }

  get context() {
    let actions = [
      {
        title: i18next.t('button.back'),
        action: () => history.back(),
        ...CommonButtonStyles.back
      }
    ]
    if (this._status == ORDER_STATUS.PENDING.value) {
      actions.push({
        title: i18next.t('button.confirm'),
        action: this._confirmReplenishment.bind(this),
        ...CommonButtonStyles.add
      })
    }
    if (this._status == ORDER_STATUS.PENDING_WORKSHEET.value) {
      actions.push({
        title: i18next.t('button.generate_worksheet'),
        action: this._generateWorksheets.bind(this),
        ...CommonButtonStyles.add
      })
    }

    let cancelOrderStatus = [ORDER_STATUS.PICKING.value, ORDER_STATUS.PUTTING_AWAY.value]

    if (cancelOrderStatus.indexOf(this._status) < 0) {
      actions.push({
        title: i18next.t('button.cancel_order'),
        action: this._cancelReplenishment.bind(this),
        ...CommonButtonStyles.cancel
      })
    }

    return {
      title: i18next.t('title.replenishment_detail'),
      actions
    }
  }

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

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

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

            <label>${i18next.t('label.status')}</label>
            <input name="status" readonly disabled />
          </fieldset>
        </form>

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

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

  constructor() {
    super()
  }

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

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

  async pageUpdated(changes, lifecycle, before) {
    if (this.active) {
      this._pageType = lifecycle.resourceId
    }

    this.config = REPLENISHMENT_CONFIG.DETAIL

    this.dataGrist.fetch()
  }

  async pageInitialized() {}

  fetchHandler({ page, limit, sorters = [] }) {
    this._clearView()

    return this._fetchReplenimentDetails(this._pageType)
  }

  async _fetchReplenimentDetails(name) {
    const response = await client.query({
      query: gql`
        query replenishmentDetail($name: String!) {
          replenishmentDetail(name: $name) {
            id
            name
            status
            domain {
              id
              name
            }
            orderInventories {
              packingType
              packingSize
              transferQty
              productSKU
              bizplace {
                id
                name
              }
            }
          }
        }
      `,
      variables: {
        name
      }
    })

    if (!response.errors) {
      let record = response.data.replenishmentDetail
      this._status = record.status
      this.updateContext()

      this._fillupForm(this.replenishmentForm, record)
      this._orderNo = record.name
      return {
        records: record.orderInventories || []
      }
    }
  }

  async _generateWorksheets() {
    try {
      let replenishmentNos = []
      if (this.dataGrist.selected.length <= 0 && this._pageType == 'list')
        throw new Error(i18next.t('text.please_select_one_or_more_order_to_generate_worksheet'))

      let availableReplenishments = this.dataGrist.selected.filter(
        itm => itm.status === ORDER_STATUS.PENDING_WORKSHEET.value
      )

      if (availableReplenishments.length > 0) {
        replenishmentNos = availableReplenishments.map(record => record.name)
      } else {
        if (this._status == ORDER_STATUS.PENDING_WORKSHEET.value) {
          replenishmentNos.push(this._orderNo)
        }
      }

      if (replenishmentNos.length <= 0)
        throw new Error(i18next.t('text.selected_replenishment(s)_is_not_in_pending_worksheet_status'))

      const response = await client.mutate({
        mutation: gql`
          mutation ($replenishmentNos: [String!]) {
            generateReplenishmentWorksheets(replenishmentNos: $replenishmentNos)
          }
        `,
        variables: {
          replenishmentNos
        }
      })

      if (!response.errors) {
        navigate(`replenishment_worksheet_list`)
        showToast({ message: i18next.t('text.worksheet(s)_has_been_generated') })
      }
      this._processing = false
    } catch (e) {
      showToast(e)
    }
  }

  async _confirmReplenishment() {
    try {
      const response = await client.mutate({
        mutation: gql`
          mutation ($name: String!) {
            confirmReplenishment(name: $name) {
              id
              name
            }
          }
        `,
        variables: {
          name: this._orderNo
        }
      })
      if (!response.errors) {
        this.dataGrist.fetch()
        this.updateContext()
        showToast({ message: i18next.t('text.replenishment_worksheet_created') })
      }
    } catch (e) {
      showToast(e)
    }
  }

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

      if (!result.value) return

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

      if (!response.errors) {
        this.dataGrist.fetch()
        this.updateContext()
        showToast({ message: i18next.t('text.replenishment_is_cancelled') })
        navigate(`replenishment/list`)
      }
    } catch (e) {
      throw 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 }
    })
    if (!response.errors) {
      return response.data.partnersBizplaces.items
    }
  }

  async _getOrderInventories() {
    const orderInventories = this.dataGrist.selected.map(record => {
      let newRecord = {
        bizplaceId: record.bizplace.id,
        releaseQty: record.transferQty,
        packingType: record.packingType,
        packingSize: record.packingSize,
        type: ORDER_TYPES.REPLENISHMENT.value,
        productDetailId: record.productDetailId
      }

      return newRecord
    })

    return orderInventories
  }

  _fillupForm(form, data) {
    if (form) {
      form.reset()
      for (let key in data) {
        Array.from(form.querySelectorAll('input, textarea')).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]
            }
          }
        })
      }
    }
  }

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

  _clearView() {
    this._orderNo = ''
    this._status = ''
  }
}

window.customElements.define('replenishment-detail-page', ReplenishmentDetail)
