import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import './draft-release-good-popup'

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

import { GhostPrint } from '@operato/ghost-print'
import { openPopup } from '@operato/layout'
import { i18next, localize } from '@things-factory/i18n-base'
import { client, CustomAlert, navigate, PageView } from '@things-factory/shell'
import { CommonButtonStyles, ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import { applyParamsToFields } from '../../../util'

import { DRAFT_RELEASE_ORDER_STATUS } from '../../../constants'

// const HEADER_JSON = {
//   'Content-Type': 'application/json',
//   Accept: 'application/json'
// }

class DraftReleaseGoodList extends localize(i18next)(PageView) {
  connectedCallback() {
    super.connectedCallback()
    this.addEventListener('reload-page', this.pageUpdated, true)
  }
  static get styles() {
    return [
      ScrollbarStyles,
      css`
        :host {
          display: flex;
          flex-direction: column;
          overflow: hidden;
        }

        search-form {
          overflow: visible;
        }

        data-grist {
          overflow-y: auto;
          flex: 1;
        }
      `
    ]
  }

  static get properties() {
    return {
      _searchFields: Array,
      config: Object,
      data: Object,
      _source: String,
      _settingValue: String
    }
  }

  constructor() {
    super()
    this._isExecuting = false
  }

  render() {
    return html`
      <search-form id="search-form" .fields=${this._searchFields} @submit=${e => this.dataGrist.fetch()}></search-form>

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

  get context() {
    return {
      title: i18next.t('title.draft_release_order'),
      exportable: {
        name: i18next.t('title.draft_release_order'),
        data: this.exportableData.bind(this)
      },

      actions: [
        {
          title: i18next.t('button.create_release_order'),
          action: () => {
            if (this._settingValue == 'true') {
              this._generatePopupReleaseGood(this)
            } else {
              this._generateReleaseGoods(this)
            }
          },
          ...CommonButtonStyles.activate
        },
        {
          title: i18next.t('button.create_draft_release_order'),
          action: this._navigateToCreate.bind(this),
          ...CommonButtonStyles.add
        }
      ],
      help: 'operato-wms/release-order/draft-release-good-list'
    }
  }

  pageUpdated(changes, lifecycle) {
    if (this.active) {
      let { params } = lifecycle
      if (params && this._searchFields) {
        if (params.range) {
          params.toDate = new Date().toISOString().split('T')[0]
          switch (params.range) {
            case '1d':
              params.fromDate = new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().split('T')[0]
              break
            case '1w':
              params.fromDate = new Date(new Date().setDate(new Date().getDate() - 7)).toISOString().split('T')[0]
              break
            case '1m':
              params.fromDate = new Date(new Date().setMonth(new Date().getMonth() - 1)).toISOString().split('T')[0]
              break
            default:
              break
          }
        }
        const updatedFields = applyParamsToFields(this._searchFields, params)
        this._searchFields = updatedFields
        const searchForm = this.searchForm
        if (searchForm) {
          searchForm.fields = updatedFields
        }
      }
      this.dataGrist.fetch()
    }
  }

  async pageInitialized() {
    this.isUserBelongsDomain = await this._checkUserBelongsDomain()
    const [_bizplacesReq] = await Promise.allSettled([this._fetchBizplaces()])

    const _bizplaces = _bizplacesReq.status == 'fulfilled' ? _bizplacesReq.value : []

    this._searchFields = [
      {
        label: i18next.t('field.order_info'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.product_info'),
        name: 'sku',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.company'),
        name: 'bizplaceId',
        type: 'select',
        options: [
          { value: '' },
          ..._bizplaces
            .map(bizplace => {
              return {
                name: `${bizplace.name} ${bizplace.description ? `(${bizplace.description})` : ''}`,
                value: bizplace.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.status'),
        name: 'status',
        type: 'select',
        options: [
          { value: '' },
          ...Object.keys(DRAFT_RELEASE_ORDER_STATUS).map(key => {
            return { name: key, value: DRAFT_RELEASE_ORDER_STATUS[key] }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.from'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq'
        },
        value: (() => {
          let date = new Date()
          date.setMonth(date.getMonth() - 3)
          return date.toISOString().split('T')[0]
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          min: (() => {
            let date = new Date()
            date.setMonth(date.getMonth() - 6)
            return date.toISOString().split('T')[0]
          })()
        },
        value: new Date().toISOString().split('T')[0]
      },
      {
        label: i18next.t('field.no_of_items'),
        name: 'noOfItems',
        type: 'select',
        props: {
          searchOper: 'gte'
        },
        options: [{ value: '' }, { name: 'Single Item', value: 1 }, { name: 'Multiple Item', value: 2 }]
      },
      {
        label: i18next.t('field.priority_delivery'),
        name: 'priorityDelivery',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.platform'),
        name: 'platformCode',
        type: 'select',
        props: {
          searchOper: 'eq'
        },
        options: [
          { value: '' },
          { name: 'Lazada', value: 'LZD' },
          { name: 'Shopee', value: 'SHP' },
          { name: 'Shopify', value: 'SPF' },
          { name: 'Tiktok', value: 'TTK' },
          { name: 'Magento', value: 'MGT' },
          { name: 'Generic', value: 'GENERIC' }
        ]
      }
    ]

    this.config = {
      rows: { selectable: { multiple: true }, appendable: false },
      list: { fields: ['name', 'releaseDate', 'status', 'updatedAt'] },
      pagination: { limit: 50, pages: [50, 100, 200, 500, 1000] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              navigate(`draft_release_good_detail/${record.name}`)
            }
          }
        },
        {
          type: 'boolean',
          name: 'priorityDelivery',
          header: i18next.t('field.priority_delivery'),
          imex: { header: i18next.t('field.priority_delivery'), key: 'priorityDelivery', width: 20, type: 'string' },
          sortable: false,
          width: 120
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.order_no'),
          imex: { header: i18next.t('field.order_no'), key: 'name', width: 30, type: 'string' },
          sortable: false,
          width: 150
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          imex: { header: i18next.t('field.company'), key: 'bizplace.name', width: 30, type: 'string' },
          sortable: false,
          width: 250
        },
        {
          type: 'string',
          name: 'type',
          header: i18next.t('field.type'),
          imex: { header: i18next.t('field.type'), key: 'type', width: 30, type: 'string' },
          sortable: false,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          imex: { header: i18next.t('field.ref_no'), key: 'refNo', width: 20, type: 'string' },
          sortable: false,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo2',
          header: i18next.t('field.ref_no_2'),
          imex: { header: i18next.t('field.ref_no_2'), key: 'refNo2', width: 20, type: 'string' },
          sortable: false,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo3',
          header: i18next.t('field.ref_no_3'),
          imex: { header: i18next.t('field.ref_no_3'), key: 'refNo3', width: 20, type: 'string' },
          sortable: false,
          width: 150
        },
        {
          type: 'date',
          name: 'releaseDate',
          header: i18next.t('field.release_date'),
          imex: { header: i18next.t('field.release_date'), key: 'releaseDate', width: 20, type: 'string' },
          sortable: false,
          width: 120
        },
        {
          type: 'boolean',
          name: 'exportOption',
          header: i18next.t('field.export_option'),
          imex: { header: i18next.t('field.export_option'), key: 'exportOption', width: 20, type: 'string' },
          sortable: false,
          width: 60
        },
        {
          type: 'boolean',
          name: 'ownTransport',
          header: i18next.t('field.own_transport'),
          imex: { header: i18next.t('field.own_transport'), key: 'ownTransport', width: 20, type: 'string' },
          sortable: false,
          width: 60
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          imex: { header: i18next.t('field.status'), key: 'status', width: 30, type: 'string' },
          sortable: false,
          width: 120
        },
        {
          type: 'string',
          name: 'platformCode',
          header: i18next.t('field.platform'),
          imex: { header: i18next.t('field.platform'), key: 'platformCode', width: 25, type: 'string' },
          sortable: true,
          width: 120
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          imex: { header: i18next.t('field.created_at'), key: 'createdAt', width: 30, type: 'datetime' },
          sortable: false,
          width: 160
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          imex: { header: i18next.t('field.updated_at'), key: 'updatedAt', width: 30, type: 'datetime' },
          sortable: false,
          width: 160
        },
        {
          type: 'object',
          name: 'creator',
          header: i18next.t('field.created_by'),
          imex: { header: i18next.t('field.created_by'), key: 'creator.name', width: 30, type: 'string' },
          sortable: false,
          width: 200
        }
      ]
    }
  }

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

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

  async fetchHandler({ page, limit, sorters = [{ name: 'created_at', desc: true }] }) {
    const response = await client.query({
      query: gql`
        query draftReleaseGoods($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          draftReleaseGoods(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              bizplace {
                id
                name
                description
              }
              ownTransport
              releaseGood {
                id
                name
                description
              }
              refNo
              refNo2
              refNo3
              type
              priorityDelivery
              exportOption
              releaseDate
              status
              source
              platformCode
              createdAt
              updatedAt
              creator {
                id
                name
                description
              }
            }
            settingValue
            total
          }
        }
      `,
      variables: {
        filters: [...(await this.searchForm.getQueryFilters())],
        pagination: { page, limit },
        sortings: sorters
      }
    })

    if (!response.errors) {
      this._ownTransport = response.data.draftReleaseGoods.ownTransport
      this._exportOption = response.data.draftReleaseGoods.exportOption
      this._settingValue = response.data.draftReleaseGoods.settingValue
      return {
        total: response.data.draftReleaseGoods.total || 0,
        records: response.data.draftReleaseGoods.items || []
      }
    }
  }

  get _columns() {
    return this.config.columns
  }

  async _generateReleaseGoods() {
    try {
      if (this._isExecuting) {
        this._showToast({ message: i18next.t('text.generate_release_order_is_still_executing_please_wait') })
        return
      }

      this._isExecuting = true
      let orderIds = []
      let selectedGristData = this.dataGrist.selected

      if (
        selectedGristData.filter(itm => itm.status == DRAFT_RELEASE_ORDER_STATUS.DRAFT).length <= 0 &&
        selectedGristData.filter(itm => itm.status == DRAFT_RELEASE_ORDER_STATUS.INSUFFICIENT).length <= 0
      )
        throw new Error(i18next.t('text.please_select_a_valid_draft_order_to_generate_release_order'))

      // Sort by createdAt ASC to ensure orders that came in first get converted first
      let selectedOrders = selectedGristData.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
      orderIds = selectedOrders.map(record => ({ id: record.id, releaseType: 'release' }))

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

      if (!result.value) return

      CustomAlert({
        title: i18next.t('text.please_wait'),
        text: i18next.t('text.generating_release_order(s)'),
        allowOutsideClick: true,
        allowEscapeKey: false
      })

      let response = await client.mutate({
        mutation: gql`
          mutation generateReleaseGoodsfromDraft($releaseInfo: [DraftReleaseGoodInfos!]!) {
            generateReleaseGoodsfromDraft(releaseInfo: $releaseInfo) {
              draftName
              successCount
              insufficientCount
              deletedCount
            }
          }
        `,
        variables: {
          releaseInfo: orderIds
        }
      })

      if (!response.errors) {
        let successCount = response.data.generateReleaseGoodsfromDraft[0].successCount
        let insufficientCount = response.data.generateReleaseGoodsfromDraft[0].insufficientCount
        let deletedCount = response.data.generateReleaseGoodsfromDraft[0].deletedCount

        if (insufficientCount > 0 && deletedCount == 0) {
          CustomAlert({
            title: i18next.t('title.completed'),
            text: 'Notice: ' + insufficientCount + ' ' + i18next.t('text.draft_order_insufficient'),
            confirmButton: { text: i18next.t('button.confirm') }
          })
        } else if (deletedCount > 0 && insufficientCount == 0) {
          CustomAlert({
            title: i18next.t('title.completed'),
            text: 'Notice: ' + deletedCount + ' ' + i18next.t('text.draft_order_deleted_detail'),
            confirmButton: { text: i18next.t('button.confirm') }
          })
        } else if (deletedCount > 0 && insufficientCount > 0) {
          CustomAlert({
            title: i18next.t('title.completed'),
            text:
              'Notice: ' +
              insufficientCount +
              ' ' +
              i18next.t('text.draft_order_insufficient') +
              ', ' +
              deletedCount +
              ' ' +
              i18next.t('text.draft_order_deleted_detail'),
            confirmButton: { text: i18next.t('button.confirm') }
          })
        } else {
          CustomAlert({
            title: i18next.t('title.completed'),
            text: successCount + ' ' + i18next.t('text.draft_order_success'),
            confirmButton: { text: i18next.t('button.confirm') }
          })
        }

        this.dataGrist.fetch()
        this._isExecuting = false
      }
    } catch (e) {
      this._showToast(e)
      this._isExecuting = false
    }
  }

  async _generatePopupReleaseGood() {
    let selectedGristData = this.dataGrist.selected
    const selectedStatuses = [
      DRAFT_RELEASE_ORDER_STATUS.DRAFT,
      DRAFT_RELEASE_ORDER_STATUS.INSUFFICIENT,
      DRAFT_RELEASE_ORDER_STATUS.PARTIAL_RELEASED
    ]
    let selectedOrders

    try {
      if (selectedGristData.length > 10) {
        throw new Error(i18next.t('text.only_ten_draft_orders_are_allowed_to_generate_release_order_at_a_time'))
      }

      if (selectedGristData.length < 1) {
        throw new Error(i18next.t('text.please_select_a_valid_draft_order_to_generate_release_order'))
      }

      let submittedOrders = selectedGristData.some(itm => itm.status === DRAFT_RELEASE_ORDER_STATUS.SUBMITTED)

      selectedOrders = selectedGristData.filter(itm => selectedStatuses.includes(itm.status))

      if (submittedOrders) {
        this._showToast({ message: i18next.t('text.submitted_draft_orders_will_not_be_displayed') })
      }

      if (selectedOrders.length < 1) {
        throw new Error('No draft orders to display')
      }

      openPopup(
        html`
          <draft-release-good-popup
            .draftOrder="${selectedOrders}"
            @reload-page="${this.pageUpdated.bind(this)}"
          ></draft-release-good-popup>
        `,
        {
          backdrop: true,
          size: 'large',
          title: i18next.t('title.create_release_order')
        }
      )
    } catch (e) {
      this._showToast(e)
    }
  }

  _navigateToCreate() {
    navigate(`draft_release_good_detail/new`)
  }

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

  async _fetchBizplaces() {
    const filters = []
    const response = await client.query({
      query: gql`
        query partnersBizplaces($filters: [Filter!]) {
          partnersBizplaces(filters: $filters) {
            items {
              id
              name
              description
            }
          }
        }
      `,
      variables: { filters }
    })

    if (!response.errors) {
      return response.data.partnersBizplaces.items
    }
  }

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

  _modifyDateRange(e) {
    const fromDate = e.currentTarget.value

    if (this._toDateInput.value < fromDate) this._toDateInput.value = fromDate

    let min = new Date(fromDate)
    let today = new Date()
    today.setHours(0, 0, 0, 0)

    min = min.toISOString().split('T')[0]

    this._toDateInput.min = min
  }

  async _checkUserBelongsDomain() {
    try {
      const response = await client.query({
        query: gql`
          query {
            checkUserBelongsDomain
          }
        `
      })

      if (!response.errors) {
        return response.data.checkUserBelongsDomain
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  async _callPrintDialog(contentSource) {
    GhostPrint.print({
      srcdoc: contentSource,
      onfinish: () => {
        this._showToast({ message: i18next.t('text.document_has_been_generated') })
      }
    })
  }

  async _fetchContactPoints() {
    const response = await client.query({
      query: gql`
        query contactPoints($filters: [Filter!]!, $pagination: Pagination, $sortings: [Sorting!]!) {
          contactPoints(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              companyName
            }
          }
        }
      `,
      variables: {
        filters: [{ name: 'type', operator: 'eq', value: 'SUPPLIER' }],
        pagination: { page: 0, limit: 999999 },
        sortings: [{ name: 'name' }]
      }
    })

    return response.data.contactPoints.items || []
  }

  async exportableData() {
    try {
      let records = []

      const bizplaceFilters = (await this.searchForm.getQueryFilters()).filter(x => x.name === 'bizplaceId')

      if (bizplaceFilters.length == 0) {
        throw new Error(`Please select a customer for export.`)
      }

      if (this.dataGrist.selected && this.dataGrist.selected.length > 0) {
        records = this.dataGrist.selected
      } else {
        records = this.dataGrist.data.records
      }

      var headerSetting = this.dataGrist._config.columns
        .filter(column => column.type !== 'gutter' /* && column.record !== undefined */ && column.imex !== undefined)
        .map(column => {
          return column.imex
        })

      var data = records.map(item => {
        return {
          id: item.id,
          ...this._columns
            .filter(
              column => column.type !== 'gutter' /* && column.record !== undefined */ && column.imex !== undefined
            )
            .reduce((record, column) => {
              record[column.imex.key] = column.imex.key
                .split('.')
                .reduce((obj, key) => (obj && obj[key] !== 'undefined' ? obj[key] : undefined), item)
              if (column.type === 'datetime') {
                record[column.imex.key] = new Date(parseInt(record[column.imex.key])).toLocaleString()
              }
              return record
            }, {})
        }
      })
      return { header: headerSetting, data: data }
    } catch (e) {
      this._showToast(e)
    }
  }
}

window.customElements.define('draft-release-good-list', DraftReleaseGoodList)
