import { getCodeByName } from '@things-factory/code-base'
import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import '@things-factory/import-ui'
import { openPopup } from '@things-factory/layout-base'
import { client, CustomAlert, navigate, PageView } from '@things-factory/shell'
import { ScrollbarStyles, CommonButtonStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import gql from 'graphql-tag'
import { css, html } from 'lit-element'
import { showToast } from '../../util'

class WarehouseList extends localize(i18next)(PageView) {
  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,
      importHandler: Object
    }
  }

  render() {
    return html`
      <search-form
        id="search-form"
        .fields=${this._searchFields}
        initFocus="description"
        @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.warehouse'),
      actions: [
        {
          title: i18next.t('button.save'),
          action: this._saveWarehouse.bind(this),
          ...CommonButtonStyles.save
        },
        {
          title: i18next.t('button.delete'),
          action: this._deleteWarehouse.bind(this),
          ...CommonButtonStyles.delete
        }
      ],
      exportable: {
        name: i18next.t('title.warehouse'),
        data: this._exportableData.bind(this)
      },
      importable: {
        handler: this._importableData.bind(this)
      },
      help: 'operato-wms/master-data/warehouse'
    }
  }

  async pageInitialized() {
    this._warehouseTypes = await getCodeByName('WAREHOUSE_TYPES')

    this._searchFields = [
      {
        label: i18next.t('field.name'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.description'),
        name: 'description',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.type'),
        name: 'type',
        type: 'select',
        options: [
          { value: '' },
          ...this._warehouseTypes.map(_warehouseType => {
            return {
              name: _warehouseType.name,
              value: _warehouseType.name
            }
          })
        ],
        props: { searchOper: 'eq' }
      }
    ]

    this.config = {
      rows: { selectable: { multiple: true } },
      columns: [
        { type: 'gutter', gutterName: 'dirty' },
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              if (record.id) navigate(`locations/${record.id}?name=${record.name}`)
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.name'),
          record: { editable: true },
          imex: { header: i18next.t('field.name'), key: 'name', width: 50, type: 'string' },
          sortable: true,
          width: 100
        },
        {
          type: 'string',
          name: 'description',
          header: i18next.t('field.description'),
          record: { editable: true },
          imex: { header: i18next.t('field.description'), key: 'description', width: 100, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'code',
          name: 'type',
          header: i18next.t('field.type'),
          record: {
            editable: true,
            codeName: 'WAREHOUSE_TYPES'
          },
          imex: {
            header: i18next.t('field.type'),
            key: 'type',
            width: 50,
            type: 'array',
            arrData: this._warehouseTypes.map(_warehouseType => {
              return {
                name: _warehouseType.name,
                id: _warehouseType.name
              }
            })
          },
          sortable: true,
          width: 100
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          sortable: true,
          width: 180
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          sortable: true,
          width: 180
        }
      ]
    }
  }

  pageUpdated(changes, lifecycle) {
    if (this.active) {
      this.dataGrist.fetch()
    }
  }

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

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

  _importableData(records) {
    setTimeout(() => {
      openPopup(
        html`
          <import-pop-up
            .records=${records}
            .config=${{
              rows: this.config.rows,
              columns: [...this.config.columns.filter(column => column.imex !== undefined)]
            }}
            .importHandler="${this.importHandler.bind(this)}"
          ></import-pop-up>
        `,
        {
          backdrop: true,
          size: 'large',
          title: i18next.t('title.import')
        }
      )
    }, 500)
  }

  async fetchHandler({ page, limit, sorters = [] }) {
    const response = await client.query({
      query: gql`
        query warehouses($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          warehouses(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              type
              description
              updatedAt
              updater {
                id
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: {
        filters: this.searchForm.queryFilters,
        pagination: { page, limit },
        sortings: sorters
      }
    })

    return {
      total: response.data.warehouses.total || 0,
      records: response.data.warehouses.items || []
    }
  }

  async importHandler(patches) {
    try {
      if (patches.some(p => (!p.name || !p.type) && p.cuFlag == '+')) {
        throw new Error(i18next.t('text.empty_value_in_list'))
      }
      const response = await client.query({
        query: gql`
          mutation updateMultipleWarehouse($patches: [WarehousePatch!]!) {
            updateMultipleWarehouse(patches: $patches)
          }
        `,
        variables: {
          patches
        }
      })

      if (!response.errors) {
        history.back()
        this.dataGrist.fetch()
        document.dispatchEvent(
          new CustomEvent('notify', {
            detail: {
              message: i18next.t('text.data_imported_successfully')
            }
          })
        )
      }
    } catch (e) {
      showToast(e)
    }
  }

  async _saveWarehouse() {
    try { 
      let patches = this.dataGrist.exportPatchList({ flagName: 'cuFlag' })
      if (patches.some(p => (!p.name || !p.type) && p.cuFlag == '+' )) {
        throw new Error(i18next.t('text.empty_value_in_list'))
      }

      if (!patches?.length) {
        CustomAlert({
          title: i18next.t('text.nothing_changed'),
          text: i18next.t('text.there_is_nothing_to_save')
        })
      } else {
        const response = await client.mutate({
          mutation: gql`
            mutation updateMultipleWarehouse($patches: [WarehousePatch!]!) {
              updateMultipleWarehouse(patches: $patches)
            }
          `,
          variables: {
            patches
          }
        })

        if (!response.errors) {
          this.dataGrist.fetch()
          document.dispatchEvent(
            new CustomEvent('notify', {
              detail: {
                message: i18next.t('text.data_updated_successfully')
              }
            })
          )
        }
      }
    } catch (e) {
      showToast(e)
    }
  }

  async _deleteWarehouse() {
    CustomAlert({
      title: i18next.t('text.are_you_sure'),
      text: i18next.t('text.you_wont_be_able_to_revert_this'),
      type: 'warning',
      confirmButton: { text: i18next.t('button.delete'), color: '#22a6a7' },
      cancelButton: { text: 'cancel', color: '#cfcfcf' },
      callback: async result => {
        if (result.value) {
          const ids = this.dataGrist.selected.map(record => record.id)
          if (ids && ids.length > 0) {
            const response = await client.query({
              query: gql`
                mutation deleteWarehouses($ids: [String!]!) {
                  deleteWarehouses(ids: $ids)
                }
              `,
              variables: { ids }
            })

            if (!response.errors) {
              this.dataGrist.fetch()
              document.dispatchEvent(
                new CustomEvent('notify', {
                  detail: {
                    message: i18next.t('text.data_deleted_successfully')
                  }
                })
              )
            }
          } else {
            CustomAlert({
              title: i18next.t('text.nothing_selected'),
              text: i18next.t('text.there_is_nothing_to_delete')
            })
          }
        }
      }
    })
  }

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

  _exportableData() {
    let records = []
    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)
            return record
          }, {})
      }
    })

    return { header: headerSetting, data: data }
  }
}

window.customElements.define('warehouse-list', WarehouseList)
