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

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

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

function formatLocalDate(date = new Date()) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

class JobSheetList 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.job_sheet_list'),
      actions: [],
      printable: {
        accept: ['preview'],
        content: this
      },
      exportable: {
        name: i18next.t('title.job_sheet_list'),
        data: this._exportableData.bind(this)
      }
    }
  }

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

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

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

  async pageInitialized() {
    const partners = await this._fetchPartners()

    this._searchFields = [
      {
        label: i18next.t('field.company'),
        name: 'bizplaceId',
        type: 'select',
        options: [
          { value: '' },
          ...partners
            .map(partner => {
              return {
                name: `${partner.name} ${partner.description ? `(${partner.description})` : ''}`,
                value: partner.id
              }
            })
            .sort(this._compareValues('name', 'asc'))
        ],
        props: { searchOper: 'eq' }
      },
      {
        label: i18next.t('field.job_sheet'),
        name: 'name',
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        name: 'containerNo',
        label: i18next.t('field.container_no'),
        type: 'text',
        props: { searchOper: 'i_like' }
      },
      {
        label: i18next.t('field.from_date'),
        name: 'fromDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          max: formatLocalDate(new Date())
        },
        attrs: ['custom'],
        value: (() => {
          const date = new Date()
          date.setMonth(date.getMonth() - 1)
          return formatLocalDate(date)
        })(),
        handlers: { change: this._modifyDateRange.bind(this) }
      },
      {
        label: i18next.t('field.to_date'),
        name: 'toDate',
        type: 'date',
        props: {
          searchOper: 'eq',
          min: (() => {
            const date = new Date()
            date.setMonth(date.getMonth() - 1)
            return formatLocalDate(date)
          })(),
          max: formatLocalDate(new Date())
        },
        attrs: ['custom'],
        value: formatLocalDate(new Date())
      }
    ]

    this.config = {
      pagination: { limit: 500, pages: [20, 50, 100, 500, 700] },
      rows: { appendable: false },
      list: { fields: ['arrivalNoticeRefNo', 'name', 'bizplace', 'containerNo', 'updatedAt'] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        {
          type: 'gutter',
          gutterName: 'button',
          icon: 'reorder',
          handlers: {
            click: (columns, data, column, record, rowIndex) => {
              navigate(`job_sheet_report/${record.arrivalNoticeRefNo}`)
            }
          }
        },
        {
          type: 'string',
          name: 'name',
          header: i18next.t('field.job_sheet'),
          sortable: true,
          width: 150
        },
        {
          type: 'string',
          name: 'arrivalNoticeRefNo',
          header: i18next.t('field.gan_no'),
          sortable: true,
          width: 150
        },
        {
          type: 'object',
          name: 'bizplace',
          header: i18next.t('field.company'),
          sortable: true,
          width: 250
        },
        {
          type: 'string',
          name: 'containerNo',
          header: i18next.t('field.container_no'),
          sortable: true,
          width: 150
        },
        {
          type: 'datetime',
          name: 'updatedAt',
          header: i18next.t('field.updated_at'),
          sortable: true,
          width: 150
        },
        {
          type: 'object',
          name: 'updater',
          header: i18next.t('field.updater'),
          sortable: true,
          width: 150
        }
      ]
    }
  }

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

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

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

  async fetchHandler({ page, limit, sorters = [{ name: 'updatedAt', desc: true }] }) {
    try {
      this._validate()

      const response = await client.query({
        query: gql`
          query jobSheets($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
            jobSheets(filters: $filters, pagination: $pagination, sortings: $sortings) {
              items {
                name
                description
                containerNo
                arrivalNoticeRefNo
                bizplace {
                  id
                  name
                  description
                }
                updatedAt
                updater {
                  id
                  name
                  description
                }
              }
              total
            }
          }
        `,
        variables: {
          filters: await this.searchForm.getQueryFilters(),
          pagination: { page, limit },
          sortings: sorters
        }
      })

      if (!response.errors) {
        return {
          total: response.data.jobSheets.total || 0,
          records: response.data.jobSheets.items || []
        }
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  _validate() {
    if (!this.searchForm.shadowRoot.querySelector('form').checkValidity())
      throw new Error(i18next.t('text.invalid_form_value'))
    if (!this._fromDateInput.value) throw new Error(i18next.t('text.from_date_is_empty'))
    if (!this._toDateInput.value) throw new Error(i18next.t('text.to_date_is_empty'))
  }

  _modifyDateRange(e) {
    this._toDateInput.value = ''
    const fromDate = e.currentTarget.value
    const minDate = new Date(fromDate)
    if (Number.isNaN(minDate.getTime())) return

    const maxDate = new Date(minDate)
    maxDate.setMonth(maxDate.getMonth() + 1)
    maxDate.setHours(0, 0, 0, 0)

    const today = new Date()
    today.setDate(today.getDate() + 1)
    today.setHours(0, 0, 0, 0)

    if (maxDate >= today) maxDate.setTime(today.getTime())

    const min = formatLocalDate(minDate)
    const max = formatLocalDate(maxDate)

    // this._fromDateInput.max = max
    this._toDateInput.min = min
    // this._toDateInput.max = max
  }

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

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

  async _exportableData() {
    try {
      var headerSetting = [
        { header: i18next.t('field.job_sheet'), key: 'name', width: 50, type: 'string' },
        { header: i18next.t('field.gan_no'), key: 'arrivalNoticeRefNo', width: 50, type: 'string' },
        { header: i18next.t('field.company'), key: 'bizplace|name', width: 25, type: 'string' },
        { header: i18next.t('field.container_no'), key: 'containerNo', width: 25, type: 'string' },
        { header: i18next.t('field.updated_at'), key: 'updatedAt', width: 25, type: 'string' },
        { header: i18next.t('field.updater'), key: 'updater|name', width: 25, type: 'string' }
      ]

      var exportData = {
        header: [...headerSetting],
        data: (await this.fetchHandler({ page: 1, limit: 9999999 })).records.map(itm =>
          flattenObject({ ...itm, updatedAt: new Date(parseInt(itm.updatedAt)).toLocaleString() })
        )
      }

      return exportData
    } catch (e) {
      this._showToast(e)
    }
  }

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

window.customElements.define('job-sheet-list', JobSheetList)
