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

class ReturnOrderList 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,
      _ownTransport: Boolean
    }
  }

  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.return_orders'),
      exportable: {
        name: i18next.t('title.return_orders'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/return-order/return-order-list'
    }
  }

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

  async pageInitialized() {
    const _orderStatus = await getCodeByName('RETURN_LIST_STATUS')
    this._searchFields = [
      {
        label: i18next.t('field.return_order_no'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.eta'),
        name: 'etaDate',
        type: 'date',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.ref_no'),
        name: 'refNo',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.own_transport'),
        name: 'ownTransport',
        type: 'checkbox',
        props: { searchOper: 'eq' },
        attrs: ['indeterminate']
      },
      {
        label: i18next.t('field.status'),
        name: 'status',
        type: 'select',
        options: [
          { value: '' },
          ..._orderStatus.map(status => {
            return { name: i18next.t(`${status.description}`), value: status.name }
          })
        ],
        props: { searchOper: 'eq' }
      }
    ]

    this.config = {
      rows: { selectable: { multiple: true }, appendable: false },
      list: { fields: ['name', 'etaDate', 'status', 'updatedAt'] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              const status = record.status
              if (status === ORDER_STATUS.REJECTED.value) {
                navigate(`rejected_return_order/${record.name}`) // 1. move to rejected detail page
              } else {
                navigate(`return_order_detail/${record.name}`)
              }
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.ro'),
          imex: { header: i18next.t('field.ro'), key: 'name', width: 50, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          imex: { header: i18next.t('field.ref_no'), key: 'refNo', width: 50, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'date',
          name: 'etaDate',
          header: i18next.t('field.eta'),
          imex: { header: i18next.t('field.eta'), key: 'etaDate', width: 30, type: 'string' },
          sortable: true,
          width: 120
        },
        {
          type: 'boolean',
          name: 'ownTransport',
          header: i18next.t('field.own_transport'),
          imex: { header: i18next.t('field.own_transport'), key: 'ownTransport', width: 50, type: 'string' },
          sortable: true,
          width: 60
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.status'),
          imex: { header: i18next.t('field.status'), key: 'status', width: 50, type: 'string' },
          sortable: true,
          width: 120
        },
        {
          type: 'object',
          name: 'creator',
          header: i18next.t('field.created_by'),
          imex: { header: i18next.t('field.created_by'), key: 'creator.name', width: 50, type: 'string' },
          sortable: true,
          width: 200
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          imex: { header: i18next.t('field.created_at'), key: 'createdAt', width: 30, type: 'date' },
          sortable: true,
          width: 160
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          imex: { header: i18next.t('field.updated_at'), key: 'updatedAt', width: 30, type: 'date' },
          sortable: true,
          width: 160
        }
      ]
    }
  }

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

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

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

  async fetchHandler({ page, limit, sorters = [{ name: 'createdAt', desc: true }] }) {
    const response = await client.query({
      query: gql`
        query returnOrders($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          returnOrders(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              bizplace {
                id
                name
              }
              ownTransport
              refNo
              eta
              etaDate
              status
              createdAt
              updatedAt
              creator {
                id
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: {
        filters: this.searchForm.queryFilters,
        pagination: { page, limit },
        sortings: sorters
      }
    })

    if (!response.errors) {
      this._ownTransport = response.data.returnOrders.ownTransport

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

  _exportableData() {
    let records = []
    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.dataGrist._config.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('return-order-list', ReturnOrderList)
