import '@things-factory/form-ui'
import '@things-factory/grist-ui'
import { i18next, localize } from '@things-factory/i18n-base'
import { openPopup } from '@things-factory/layout-base'
import { client, navigate, PageView } from '@things-factory/shell'
import { ScrollbarStyles } from '@things-factory/styles'
import { isMobileDevice } from '@things-factory/utils'
import gql from 'graphql-tag'
import { css, html } from 'lit-element'
import { getOrderStatusCandidates, ORDER_TYPES } from '../constants'
import './search-popup'
class InventoryCheckList 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
    }
  }

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

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

  async pageInitialized() {
    const _orderStatus = getOrderStatusCandidates(ORDER_TYPES.CYCLE_COUNT)

    this._bizplaces = [...(await this._fetchBizplaceList())]

    this._searchFields = [
      {
        name: 'bizplace',
        label: i18next.t(`field.company`),
        type: 'object',
        queryName: 'bizplaces',
        field: 'name',
        handlers: {
          click: this._showSearchCustomer.bind(this)
        },
        props: { searchOper: 'eq', readonly: true }
      },
      {
        name: 'name',
        label: i18next.t('field.inventory_check_no'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        name: 'executionDate',
        label: i18next.t('field.execution_date'),
        type: 'date',
        props: { searchOper: 'eq' }
      },
      {
        name: 'status',
        label: i18next.t('field.order_status'),
        type: 'select',
        options: [
          { value: '' },
          ..._orderStatus.map(status => {
            return { name: i18next.t(`label.${status.name}`), value: status.value }
          })
        ],
        props: { searchOper: 'eq' }
      }
    ]

    this.config = {
      list: {
        fields: ['inventoryCheck', 'type', 'Customer', 'executionDate', 'status', 'createdAt', 'updatedAt']
      },
      rows: { appendable: false },
      columns: [
        { type: 'gutter', gutterName: 'dirty' },
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              if (!record.id) return
              navigate(`cycle_count_report/${record.name}`)
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.inventory_check_no'),
          sortable: true,
          width: 170,
          imex: {
            header: i18next.t('field.inventory_check_no'),
            key: 'inventoryCheck.name',
            width: 50,
            type: 'string'
          }
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          sortable: true,
          width: 250,
          imex: {
            header: i18next.t('field.company'),
            key: 'bizplace.name',
            width: 30,
            type: 'array',
            arrData: []
          }
        },
        {
          type: 'date',
          name: 'executionDate',
          header: i18next.t('field.execution_date'),
          sortable: true,
          width: 120,
          imex: {
            header: i18next.t('field.execution_date'),
            key: 'executionDate',
            width: 30,
            type: 'string'
          }
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.order_status'),
          sortable: true,
          width: 150,
          imex: {
            header: i18next.t('field.order_status'),
            key: 'status',
            width: 20,
            type: 'string'
          }
        },
        {
          type: 'datetime',
          name: 'createdAt',
          header: i18next.t('field.created_at'),
          sortable: true,
          width: 160,
          imex: {
            header: i18next.t('field.created_at'),
            key: 'createdAt',
            width: 30,
            type: 'datetime'
          }
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          sortable: true,
          width: 160,
          imex: {
            header: i18next.t('field.updated_at'),
            key: 'updatedAt',
            width: 30,
            type: 'datetime'
          }
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          sortable: true,
          width: 150,
          imex: {
            header: i18next.t('field.updater'),
            key: 'updater.name',
            width: 30,
            type: 'object'
          }
        }
      ]
    }
  }

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

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

  get bizplace() {
    return this.searchForm.shadowRoot.querySelector('input[name=bizplace]')
  }

  async fetchHandler({ page, limit, sorters = [{ name: 'updatedAt', desc: true }] }) {
    const filters = await this.searchForm.getQueryFilters()

    const pagination = { page, limit }
    const sortings = sorters

    const response = await client.query({
      query: gql`
        query inventoryChecks($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          inventoryChecks(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              description
              executionDate
              status
              createdAt
              updatedAt
              bizplace {
                id
                name
                description
              }
              updater {
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: {
        filters,
        pagination,
        sortings
      }
    })

    if (!response.errors) {
      return {
        total: response.data?.inventoryChecks?.total || 0,
        records: response.data?.inventoryChecks?.items || []
      }
    }
  }

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

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

  _showSearchCustomer() {
    openPopup(
      html`
        <search-popup
          .complete="${async data => {
            this.bizplace.value = data.name
          }}"
        ></search-popup>
      `,
      {
        backdrop: true,
        size: 'large',
        title: i18next.t('field.company')
      }
    )
  }

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

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

  async _exportableData() {
    let records = []
    records = this.dataGrist.data.records

    const fetchBizplaces = await this._fetchBizplaceList()

    var headerSetting = this.dataGrist._config.columns
      .filter(column => column.type !== 'gutter' && column.record !== undefined && column.imex !== undefined)
      .map(column => {
        if (column.imex.key == 'bizplace.name') {
          column.imex.arrData = fetchBizplaces.map(item => {
            return {
              id: item.id,
              name: item.name
            }
          })
        }
        return column.imex
      })

    var data = records.map(item => {
      return {
        id: item.id,
        ...this.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)
            if (column.type === 'datetime' && record[column.imex.key] !== '' && record[column.imex.key] !== null) {
              record[column.imex.key] = new Date(parseInt(record[column.imex.key])).toLocaleString()
            }
            return record
          }, {})
      }
    })
    return { header: headerSetting, data: data }
  }
}

window.customElements.define('inventory-check-list', InventoryCheckList)
