<template>
  <div :id="gridId" :style="styles" />
</template>

<script>
import './css/w2ui-1.5.rc1.css'
let $ = require('jquery') // npm copy (installed via "npm install jquery --save"), not CDN copy
global.jQuery = global.$ = $ // kludge: w2ui wants global jQuery and $
const w2ui_top = require('./js/w2ui-1.5.rc1') // use explicit path (loading via browser path in package.json didn't seem to work)
$ = global.$ // kludge: w2ui attached functions to global.$, not $, so propagate them back to my local copy
global.w2ui = w2ui_top.w2ui
global.w2obj = w2ui_top.w2obj
global.w2utils = w2ui_top.w2utils
export default {
  name: 'TaDataTable',
  props: {
    gridProps: {
      type: Object,
      default () {
        return {}
      },
    },
    styles: {
      type: String,
      default () {
        return 'height:300px;'
      },
    },
    url: {
      type: String,
      default () {
        return ''
      },
    },
    gridId: {
      type: String,
      default () {
        return ''
      },
    },
    urlParam: {
      type: Object,
      default () {
        return {}
      },
    },
  },
  data () {
    return {
    }
  },
  mounted () {
    const {gridProps, gridId} = this.$props
    $('#' + gridId).w2grid(gridProps).refresh()
    this.gridDataPromise()
  },
  destroyed () {
    const {gridProps, gridId} = this.$props
    $('#' + gridId).w2destroy(gridProps['name'])
  },
  methods: {
    gridDataPromise () {
      const {url, gridId, urlParam} = this.$props
      if (!url) {
        return
      }
      const params = {
        url: url,
        data: {
          ...urlParam,
          gridId,
        },
      }
      this.Base.submit(null, params).then((result) => {
        const gridData = result.data[gridId]
        const columns = this.gridProps.columns
        columns.forEach(v => {
          const collectionType = v['collectionType']
          const field = v['field']
          if (collectionType) {
            gridData.forEach(data => {
              const oldValue = data[field]
              const newValue = this.CollectionLabel(collectionType, oldValue)
              data[field] = newValue
            })
          }
        })
        $('#' + gridId).w2grid().add(gridData)
      }).catch((rs) => {
        console.error(rs)
      })
    },
  },
}
</script>

<style scoped>

</style>
