<template lang="pug">
  #pivot
    table#t1(ref="place")
</template>

<script>
  import * as d3 from 'd3'
  import _ from 'lodash'

  import D3Table from './D3Table.vue'
  
  import pivotData from '../src/pivot.data'
  import Hot from './Hot.vue'
  import Handsontable from 'handsontable'
  import { span } from '../src/helper'

  const data = function () {
    return {
      tableData: pivotData(this.data, this.dimension, this.measure)
    }
  }

  export default {
    props: ['data', 'dimension', 'measure'],
    components: {Hot},
    data,
    methods: {
      d3Pivot(pivotData, el = 'table') {
        const {orientInfo, measure} = pivotData
        const $table = d3.select(el)
        let rows = $table.selectAll('tr').data(pivotData).enter().append('tr')
        rows = rows.selectAll('td').data(d => d).enter().append('td')
          .text(d => d)
        if (measure.length === 1 && measure.orient === 2) {
          const measureCol = orientInfo.filter(v => v === 2).length
          d3.selectAll(`${el} tr:nth-child(${measureCol})`).remove()
        }
        orientInfo.filter(v => v === 2).map((v, k) => d3.selectAll(`${el} tr:nth-child(${k + 1}) td`))
          .forEach(v => v.call(span, 'col'))
        orientInfo.filter(v => v === 1).map((v, k) => d3.selectAll(`${el} td:nth-child(${k + 1})`))
          .forEach(v => v.call(span, 'row'))
      },
      hotPivot(tableData, selector) {
        const colHeaders = this.tableData.slice(3, 4)[0]
        const hotElement = document.querySelector(selector)
        const hotSettings = {
          data: tableData.slice(3),
          colHeaders
        }
        new Handsontable(hotElement, hotSettings)
      }
    },
    mounted() {
      const {orientInfo, measure} = this.tableData
      const table = this.$refs.place
      this.hotPivot(this.tableData.slice(1), '#hot')
      this.d3Pivot(this.tableData)
    }

  }

</script>

<style lang="sass" scoped>
  @import '~handsontable/dist/handsontable.full.css'
</style>
