import '@things-factory/form-ui'
import '@things-factory/grist-ui'

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

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

class ReceivedNoteList 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.goods_received_notes'),
      exportable: {
        name: i18next.t('title.goods_received_notes'),
        data: this._exportableData.bind(this)
      },
      help: 'operato-wms/goods-received-note/received-note-list'
    }
  }

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

  async pageInitialized() {
    const _grnStatus = await getCodeByName('GRN_STATUS')
    const _ganStatus = await getCodeByName('GAN_REQUESTS_STATUS')
    const _partners = await this._fetchPartners()

    this._searchFields = [
      {
        label: i18next.t('field.grn'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.company'),
        name: 'bizplaceName',
        type: 'select',
        options: [
          { value: '' },
          ..._partners
            .map(partner => {
              return {
                name: `${partner.name} ${partner.description ? `(${partner.description})` : ''}`,
                value: partner.name
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      {
        name: 'arrivalNoticeNo',
        label: i18next.t('field.gan'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.ref_no'),
        name: 'refNo',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.ref_no_2'),
        name: 'refNo2',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.ref_no_3'),
        name: 'refNo3',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.grn_status'),
        name: 'grnStatus',
        type: 'select',
        options: [
          { value: '' },
          ..._grnStatus.map(status => {
            return { name: i18next.t(`label.${status.description}`), value: status.name }
          })
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.from'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq'
        },
        value: (() => {
          let date = new Date()
          date.setMonth(date.getMonth() - 6)
          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.gan_status'),
        name: 'ganStatus',
        type: 'select',
        options: [
          { value: '' },
          ..._ganStatus.map(status => {
            return { name: i18next.t(`label.${status.description}`), value: status.name }
          })
        ],
        props: { searchOper: 'eq' }
      }
    ]

    this.config = {
      list: {
        fields: ['name', 'bizplace', 'orderRefNo', 'arrivalNotice', 'updater', 'updatedAt']
      },
      rows: { appendable: false, selectable: { multiple: true } },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              navigate(`received_note_detail/${record.name}`)
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.grn'),
          imex: { header: i18next.t('field.grn'), key: 'name', width: 25, type: 'string' },
          sortable: true,
          width: 180,
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              if (record.attachments[0] && record.attachments[0].path) {
                window.open(`/attachment/${record.attachments[0].path}`)
              }
            }
          }
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          imex: { header: i18next.t('field.company'), key: 'bizplace', width: 25, type: 'string' },
          sortable: true,
          width: 230
        },
        {
          type: 'string',
          name: 'refNo',
          header: i18next.t('field.ref_no'),
          imex: { header: i18next.t('field.ref_no'), key: 'refNo', width: 25, type: 'string' },
          sortable: true,
          width: 160
        },
        {
          type: 'string',
          name: 'refNo2',
          header: i18next.t('field.ref_no_2'),
          imex: { header: i18next.t('field.ref_no_2'), key: 'refNo2', width: 25, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'refNo3',
          header: i18next.t('field.ref_no_3'),
          imex: { header: i18next.t('field.ref_no_3'), key: 'refNo3', width: 25, type: 'string' },
          sortable: true,
          width: 150
        },
        {
          type: 'object',
          name: 'arrivalNotice',
          header: i18next.t('field.gan'),
          imex: { header: i18next.t('field.gan'), key: 'arrivalNotice', width: 25, type: 'string' },
          sortable: true,
          width: 180
        },
        {
          type: 'string',
          name: 'ganStatus',
          header: i18next.t('field.gan_status'),
          imex: { header: i18next.t('field.gan_status'), key: 'ganStatus', width: 25, type: 'string' },
          sortable: true,
          width: 180
        },
        {
          type: 'string',
          name: 'status',
          header: i18next.t('field.grn_status'),
          imex: { header: i18next.t('field.grn_status'), key: 'status', width: 25, type: 'string' },
          sortable: true,
          width: 180
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          imex: { header: i18next.t('field.updated_at'), key: 'updatedAt', width: 25, type: 'date' },
          sortable: true,
          width: 160
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          imex: { header: i18next.t('field.updater'), key: 'updater', width: 25, type: 'string' },
          sortable: true,
          width: 160
        }
      ]
    }
  }

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

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

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

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

  _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 fetchHandler({ page, limit, sorters = [{ name: 'createdAt', desc: true }] }) {
    const response = await client.query({
      query: gql`
        query goodsReceivalNotes($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          goodsReceivalNotes(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              arrivalNotice {
                id
                name
                description
                status
                refNo
                refNo2
                refNo3
              }
              status
              description
              bizplace {
                id
                name
                description
              }
              attachments {
                id
                name
                refBy
                path
              }
              createdAt
              updatedAt
              updater {
                id
                name
                description
              }
            }
            total
          }
        }
      `,
      variables: {
        filters: this.searchForm.queryFilters,
        pagination: { page, limit },
        sortings: sorters
      }
    })

    if (!response.errors) {
      return {
        total: response.data.goodsReceivalNotes.total || 0,
        records:
          response.data.goodsReceivalNotes.items.map(grn => {
            return {
              ...grn,
              refNo: grn.arrivalNotice.refNo || '',
              refNo2: grn.arrivalNotice.refNo2 || '',
              refNo3: grn.arrivalNotice.refNo3 || '',
              ganStatus: grn.arrivalNotice.status
            }
          }) || []
      }
    }
  }

  async _fetchPartners() {
    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
    }
  }

  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 {
        ...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
          }, {}),
          id: item.id,
          name:item.name,
          bizplace:item.bizplace.name,
          refNo:item.refNo,
          refNo2:item.refNo2,
          refNo3:item.refNo3,
          arrivalNotice:item.arrivalNotice.name,
          ganStatus:item.ganStatus,
          status:item.status,
          updatedAt:item.updatedAt,
          updater:item.updater.name
          

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

}

window.customElements.define('received-note-list', ReceivedNoteList)
