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

import { i18next, localize } from '@things-factory/i18n-base'
import { client, navigate, PageView } from '@things-factory/shell'
import { CommonButtonStyles, ScrollbarStyles } from '@things-factory/styles'
import { getPathInfo } from '@things-factory/utils'

class ReceivedNoteDetail extends localize(i18next)(PageView) {
  static get properties() {
    return {
      _grnNo: String,
      _status: String,
      _domainName: String,
      _data: Object
    }
  }

  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          padding: 0;
        }

        #container {
          flex: 1;
          padding: 0;
          margin: 0;
          border: 0;
        }
      `
    ]
  }

  get context() {
    var actions = [
      {
        title: i18next.t('button.print'),
        action: () => {
          this.renderRoot.querySelector('iframe').contentWindow.print()
        },
        ...CommonButtonStyles.print
      },
      {
        title: i18next.t('button.back'),
        action: () => navigate(`received_note_list`),
        ...CommonButtonStyles.back
      }
    ]

    return {
      title: i18next.t('title.goods_received_note_details'),
      actions,
      exportable: {
        name: i18next.t('title.goods_received_note_details'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/goods-received-note/received-note-detail'
    }
  }

  render() {
    return html` <iframe id="container"></iframe> `
  }

  async pageUpdated(changes) {
    if (this.active) {
      if (changes.resourceId) {
        this._grnNo = changes.resourceId
      }

      if (this._grnNo) {
        this._fetchGRNTemplate()
      }

      this.updateContext()
    }
  }

  _fetchGRNTemplate() {
    var { domain } = getPathInfo(location.pathname) // find out better way later.
    var timezoneOffSet = new Date().getTimezoneOffset().toString()

    switch (domain) {
      case 'el-ccl-selayang':
      case 'el-cold-chain-warehouse':
        this.shadowRoot.querySelector('#container').src = `/view_elccl_grn/${this._grnNo}`
        break
      case 'orientage-warehouse':
      case 'shah-alam-warehouse':
        this.shadowRoot.querySelector('#container').src = `/view_orientage_grn/${this._grnNo}`
        break
      case 'seebuu-warehouse':
        this.shadowRoot.querySelector('#container').src = `/view_seebuu_grn/${this._grnNo}`
        break
      case 'fmn01s-default':
        this.shadowRoot.querySelector('#container').src = `/view_fm_grn/${this._grnNo}/${timezoneOffSet}`
        break
      case 'kimeda-warehouse':
        this.shadowRoot.querySelector('#container').src = `/view_kimeda_grn/${this._grnNo}/${timezoneOffSet}`
        break
      default:
        this.shadowRoot.querySelector('#container').src = `/view_grn/${this._grnNo}/${timezoneOffSet}`
        break
    }
  }

  async _fetchGRN() {
    var timezoneOffSet = new Date().getTimezoneOffset().toString()

    if (!this._grnNo) return
    const response = await client.query({
      query: gql`
        query goodsReceivalNote($name: String!, $timezoneOffSet: String!) {
          goodsReceivalNote(name: $name, timezoneOffSet: $timezoneOffSet) {
            grnNo
            ganNo
            refGANNo
            refGANNo2
            refGANNo3
            companyDomain
            supplier
            date
            productLists {
              po
              productSKU
              productName
              productType
              productBatch
              expectedQty
              actualQty
              actualUomValue
              productUom
              expiryDate
              manufactureDate
              remark
              batchNo
              unitPrice
            }
          }
        }
      `,
      variables: {
        name: this._grnNo,
        timezoneOffSet: timezoneOffSet
      }
    })

    if (!response.errors) {
      return response.data.goodsReceivalNote
    }
  }

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

  //     if (!result.value) {
  //       return
  //     }

  //     const response = await client.query({
  //       query: gql`
  //       mutation {
  //         sendGoodsReceivalNote(${gqlBuilder.buildArgs({
  //           name: this._grnNo
  //         })}) {
  //           name
  //         }
  //       }
  //     `
  //     })

  //     if (!response.errors) {
  //       navigate('received_note_list')
  //       this._showToast({ message: i18next.t('text.goods_received_note_has_been_sent_successfully') })
  //     }
  //   } catch (e) {
  //     this._showToast(e)
  //   }
  // }

  async _exportableData() {
    const { grnNo, ganNo, refGANNo, refGANNo2, refGANNo3, companyDomain, supplier, date, productLists } =
      await this._fetchGRN()

    const exportData = productLists.map(res => {
      return {
        grnNo,
        ganNo,
        refGANNo,
        refGANNo2,
        refGANNo3,
        companyDomain,
        supplier,
        date,
        ...res
      }
    })

    const headerSetting = [
      {
        header: i18next.t('field.grn'),
        key: 'grnNo',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.gan'),
        key: 'ganNo',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.po'),
        key: 'po',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.ref_no'),
        key: 'refGANNo',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.ref_no_2'),
        key: 'refGANNo2',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.ref_no_3'),
        key: 'refGANNo3',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.company'),
        key: 'companyDomain',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.supplier'),
        key: 'supplier',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.date'),
        key: 'date',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.batch_no'),
        key: 'batchNo',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.sku'),
        key: 'productSKU',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.product_name'),
        key: 'productName',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.packing_type'),
        key: 'productType',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.expected_qty'),
        key: 'expectedQty',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.actual_qty'),
        key: 'actualQty',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.actual_uom_value'),
        key: 'actualUomValue',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.uom'),
        key: 'productUom',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.expiry_date'),
        key: 'expiryDate',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.manufacture_date'),
        key: 'manufactureDate',
        width: 25,
        type: 'string'
      },
      {
        header: i18next.t('field.unit_price'),
        key: 'unitPrice',
        width: 25,
        type: 'number'
      },
      {
        header: i18next.t('field.remark_issues'),
        key: 'remark',
        width: 25,
        type: 'string'
      }
    ]

    return { header: headerSetting, data: exportData }
  }

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

window.customElements.define('received-note-detail', ReceivedNoteDetail)
