<template>
  <mx-table :rows="logTable.rows" :prop-defines="logTable.columns" border class="elective-flow-table">
    <template #group-header="{key, label}">
      <elective-flow-major v-if="logTable.majors[key]" :icon-classes="['f-fff']"
                           :matched-majors="logTable.majors[key]"></elective-flow-major>
      {{ label }}
    </template>
    <template #group-flow="{value}">
      <span v-if="value.text">{{ value.text }}</span>
      <span v-else v-html="'&#12288'"></span>
      <elective-flow-rank-descriptor v-if="value.rankDescriptors"
                                     :rank-descriptors="value.rankDescriptors"></elective-flow-rank-descriptor>
    </template>
  </mx-table>
</template>

<script>
import config from '@/common/mx-config'
import ElectiveFlowMajor from '@/views/elective/generation/components/elective-flow-major'
import ElectiveFlowRankDescriptor from '@/views/elective/generation/components/elective-flow-rank-descriptor'

export default {
  name: 'elective-generation-flow-log',
  components: { ElectiveFlowRankDescriptor, ElectiveFlowMajor },
  props: ['groups', 'matchedMajors', 'histories'],
  computed: {
    logTable() {
      if (!this.histories.length) return {}
      const maxGeneration = this.histories.last().generation
      const options = Object.values(config.electiveGenerationOptions)
      // columns & rows
      const rows = []
      for (let g = 1; g <= maxGeneration; g++) {
        const opt = options.find(opt => opt.value == g)
        rows.push({ opt, generation: opt.title })
      }
      const columns = { generation: { label: '进程' } }
      const majors = {}
      this.groups.forEach(group => {
        const keyPrefix = 'group_'
        const key = keyPrefix + group.groupId
        columns[key] = { label: group.groupName, minWidth: '160px', slot: 'group-flow', slotHeader: 'group-header' }
        // match major
        const groupMajors = (this.matchedMajors?.majors
          ?.filter(m => m['matchedGroupIds'].some(id => id == group.groupId)) || [])
          .groupBy(m => m.collegeName)
        if (groupMajors.length) majors[key] = groupMajors
        // fill rows
        rows.forEach(row => {
          const g = row.opt.value
          const gHistories = this.histories.filter(h => h.generation == g && h.groupId == group.groupId)
          row[key] = {
            text: gHistories.map(h => h.description).join('/'),
            histories: gHistories,
            rankDescriptors: gHistories.last(i => !!i.rankDescriptors?.length)?.rankDescriptors
          }
        })
      })

      return {
        columns,
        rows,
        majors
      }
    }
  }
}
</script>

<style>
@import url('./elective-flow-table-style.css');
</style>
