<template>
  <mx-table :prop-defines="resolvedTable.columns" :rows="resolvedTable.rows" border>
    <template #elective-cell="{value}">
      {{ value && value.value }}
    </template>
  </mx-table>
</template>

<script>
import MxGroupTranslateMixin from '@/components/Cache/modules/mx-select-translate-mixin'

export default {
  mixins: [MxGroupTranslateMixin],
  name: 'elective-generation-table',
  props: ['chartBinding'],
  computed: {
    resolvedTable() {
      console.log('resolvedTable called', this.listGroupsOptions, this.chartBinding)
      if (!this.listGroupsOptions.length) return {}
      const columns = { groupName: { label: '组合', fixed: true }, expectedCount: { label: '设置人数', fixed: true } }
      const rows = this.chartBinding.generation.status.roundGroups.map(rg => ({
        groupId: rg.groupId,
        groupName: this.translateGroup(rg.groupId),
        expectedCount: rg.personCount
      }))
      const mergedColumns = []
      this.chartBinding.tableData.forEach(item => {
        const ext = { roundId: item.roundId, generation: item.generation }
        const isPreference = item.categories.every(item => Array.isArray(item))
        if (isPreference) {
          item.categories.forEach((subItem, idx) => {
            const prefix = item.categories.length > 1 ? `第${idx + 1}志愿` : ''
            subItem.forEach(data => this.resolveTableGeneration(ext, data, columns, rows, mergedColumns, prefix))
          })
        } else {
          item.categories.forEach(data => this.resolveTableGeneration(ext, data, columns, rows, mergedColumns))
        }
      })
      return {
        mergedColumns,
        columns,
        rows
      }
    }
  },
  mounted() {
    window.tableVue = this
  },
  methods: {
    resolveTableGeneration(ext, data, columnsRef, rowsRef, mergedColumnsRef, prefix = '') {
      // resolve core
      const prop = prefix + ext.generation + '_' + data.category
      const name = prefix + data.displayName
      const shouldMerge = data.values.length != rowsRef.length
        || data.values.some(v => v.groupId == 0)

      columnsRef[prop] = { label: name, slot: 'elective-cell' }
      if (!shouldMerge) {
        data.values.forEach(val => {
          const row = rowsRef.find(row => row.groupId == val.groupId)
          if (row) {
            row[prop] = val
          }
        })
      } else {
        // mark for table rows merge
        mergedColumnsRef.push(prop)

        // keep value in display row
        const val = data.values.first()
        const row = rowsRef.first()
        row[prop] = val
      }
    }
  }
}
</script>

<style scoped>

</style>
