<template>
  <div>
    <div class="mb10 fx-row fx-bet-cen">
      <div class="fx-row fx-end-cen">
        <el-button circle icon="el-icon-refresh" @click="refreshData" class="mr30"></el-button>
        <elective-enroll-info v-if="enrollInfoVisible" :generation="generation"
                              :enroll-status="enrollStatus"></elective-enroll-info>
      </div>
      <el-button v-if="enableAIFeature" type="primary" @click="toAiAnalysis">AI分析</el-button>
    </div>

    <mx-table :propDefines="formatCols" :rows="formatRows">
      <template #underOver="{value}">
        <over-under-badge :value="value"></over-under-badge>
      </template>
      <template #group="{row}">
        <elective-table-group-tag :generation="generation" :group="row"></elective-table-group-tag>
      </template>
      <template #temp="{row}">
        <span class="btn-blue mr5" @click="toSelectSub(row)">选择</span>
        <span class="btn-green" @click="toReport">查看记录</span>
      </template>
      <template #signUp="{row}">
        <elective-preference-command :generation="generation" :group="row"></elective-preference-command>
      </template>
      <template #subjects="{row}">
        <elective-major-thumbnail :group="row"></elective-major-thumbnail>
      </template>
      <template #colleges="{row}">
        <elective-major-college :group="row"></elective-major-college>
      </template>
    </mx-table>
    <elective-preference-info :generation="generation"></elective-preference-info>
    <elective-preference-batch v-if="enableMultipleDrag" :generation="generation" :disabled="!enableSelect"></elective-preference-batch>
    <elective-preference-reject v-if="enableReject" :generation="generation"></elective-preference-reject>
    <elective-esign-dialog ref="esignDialog"></elective-esign-dialog>
    <choose-subject-dialog ref="chooseDialog"></choose-subject-dialog>
    <select-subject-report-dialog ref="reportDialog"></select-subject-report-dialog>
    <elective-ai-analysis-dialog ref="aiDialog" :optionalMajors="optionalMajors"
                                 :generation="generation"></elective-ai-analysis-dialog>
  </div>
</template>
<script>
import consts from '@/common/mx-const'
import { mapGetters } from 'vuex'
import MxSelectTranslate from '@/components/Cache/modules/mx-select-translate-mixin.js'
import ChooseSubjectDialog from '../../../system/user/profile/components/choose-subject-dialog'
import SelectSubjectReportDialog from '@/views/system/user/profile/components/select-subject-report-dialog'
import OverUnderBadge from '@/views/elective/publish/components/steps/fauclty/over-under-badge'
import ElectiveEnrollInfo from '@/views/elective/select/components/elective-enroll-info'
import ElectiveToolsMixin from './elective-tools-mixins'
import ElectivePreferenceInfo from '@/views/elective/select/components/elective-preference-info'
import ElectivePreferenceReject from '@/views/elective/select/components/elective-preference-reject'
import ElectivePreferenceCommand from '@/views/elective/select/components/elective-preference-command'
import ElectiveAiAnalysisDialog from '@/views/elective/select/components/elective-ai-analysis-dialog'
import ElectiveEsignDialog from '@/views/elective/select/components/elective-esign-dialog'
import ElectiveMajorThumbnail from '@/views/elective/select/components/elective-major-thumbnail'
import ElectiveMajorCollege from '@/views/elective/select/components/elective-major-college'
import ElectivePreferenceBatch from '@/views/elective/select/components/elective-preference-batch'
import ElectiveTableGroupTag from '@/views/elective/select/components/elective-table-group-tag'

const resolverModules = require.context('./round-select-resolvers', false, /\.js$/)
const resolvers = resolverModules.keys().map(key => resolverModules(key).default)

export default {
  mixins: [ElectiveToolsMixin, MxSelectTranslate, ...resolvers],
  name: 'elective-table',
  props: {
    generation: Object,
    readonly: Boolean, // 校长端不允许操作
    optionalMajors: { type: Array, default: () => [] }
  },
  components: {
    ElectiveTableGroupTag,
    ElectivePreferenceBatch,
    ElectiveMajorCollege,
    ElectiveMajorThumbnail,
    ElectiveEsignDialog,
    ElectiveAiAnalysisDialog,
    ElectivePreferenceCommand,
    ElectivePreferenceReject,
    ElectivePreferenceInfo,
    ElectiveEnrollInfo,
    OverUnderBadge,
    SelectSubjectReportDialog,
    ChooseSubjectDialog
  },
  inject: {
    refreshData: {
      default: function() {
      }
    }
  },
  computed: {
    ...mapGetters(['hasPermissions']),
    enrollInfoVisible() {
      return this.generation.active > this.generation.options.primary.value
    },
    enrollStatus() {
      const enrolledGroup = this.generation.activeModel.models?.find(this.isGroupEnrolled)
      if (enrolledGroup) {
        let enrolledModel = this.generation.activeModel
        do {
          const matched = enrolledModel.models?.find(this.isGroupEnrolled)
          if (matched
            && matched.groupId == enrolledGroup.groupId
            && enrolledModel.selectedList.includes(matched)) {
            return {
              enrolledGroup,
              enrolledModel
            }
          }
          enrolledModel = enrolledModel.prevModel
        }
        while (enrolledModel)
      }
      return { enrolledGroup, enrolledModel: null }
    },
    stepMatched() {
      return this.generation.active == this.generation.current
    },
    selectStep() {
      return !this.generation.activeOpt.decisionMaking
    },
    enableSelect() {
      return this.stepMatched && this.selectStep && !!!this.enrollStatus.enrolledGroup && !this.readonly
    },
    selectedList() {
      return this.generation.activeModel.selectedList
    },
    multipleSelect() {
      return this.generation.activeModel.preferenceCount > 1
    },
    enableMultipleDrag() {
      return this.selectStep && this.multipleSelect
    },
    enableReject() {
      return this.enableSelect && this.generation.active > this.generation.options.primary.value
    },
    enableAIFeature() {
      return !this.generation.activeOpt.decisionMaking
        && this.generation.activeOpt != this.generation.options.primary
        && !this.readonly
    },
    resolveTablePrefix() {
      return {
        index: {

          type: 'index',
          label: '编号'
        },
        groupName: {
          label: '选科组合',
          slot: 'group',
          width: '85px'
        },
        scoreSumGroup: {
          label: '组合成绩',
          hidden: this.hasPermissions([consts.enum.electivePermission.rankInGroup.scoreByGroup])
        },
        classCount: {
          label: '开设班级数'
        },
        personCount: {
          label: '人数设置'
        }
      }
    },
    resolveTableSuffix() {
      const stepMatched = this.generation.active == this.generation.current
      const enableApply = !this.generation.currentOpt.decisionMaking
      const enableSignUp = stepMatched && enableApply && !this.readonly

      return {
        rankInGroup: {
          label: '当前组合实时排名',
          hidden: this.hasPermissions([consts.enum.electivePermission.rankInGroup])
        },
        rankInGrade: {
          label: '选科全校排名',
          hidden: this.hasPermissions([consts.enum.electivePermission.rankInGrade])
        },
        allowSelectTips: {
          label: '报名状态'
        },
        temp: {
          label: '选择专业',
          width: '140',
          slot: 'temp',
          hidden: this.readonly
        },
        subjects: {
          label: '自选专业',
          slot: 'subjects',
          minWidth: '150'
        },
        colleges: {
          label: '院校',
          slot: 'colleges',
          minWidth: '250'
        },
        signUp: {
          label: '操作',
          slot: 'signUp',
          width: '100',
          fixed: 'right',
          hidden: !enableSignUp
        }
      }
    },
    resolveDynamicTable() {
      if (!Object.keys(this.formatRows).length) return {}
      const options = this.generation.options
      if (!options || !this.generation.active) return {}
      const optValues = Object.values(options)
      const dynamicColumns = {}
      for (let gen = options.primary.value; gen <= this.generation.active; gen++) {
        const opt = optValues.find(opt => opt.value == gen)
        const resolverKey = opt.key + 'Resolver'
        const resolver = this[resolverKey]
        if (typeof resolver === 'function') {
          const genColumns = resolver(gen, this.generation.active, dynamicColumns)
          Object.assign(dynamicColumns, genColumns)
        }
      }
      return dynamicColumns
    },
    formatRows() {
      if (!this.optionalMajors) return []
      if (!this.generation.roundGroups?.length) return []
      if (!this.generation.activeModels?.length) return []
      const activeModel = this.generation.activeModel
      return this.generation.roundGroups.map(rg => {
        const row = activeModel.models?.find(item => item.groupId == rg.groupId) || {}
        row.allowSelectTips = this.combineGroupStatus(row, activeModel)
        const matchedMajors = this.optionalMajors.filter(college => college.matchedGroupIds.includes(row.groupId))
        row.colleges = matchedMajors.map(m => ({ college: m.collegeName, major: m.majorCategoryName }))
        row.subjects = matchedMajors.map(m => m['majorCategoryName'])
        return row
      })
    },
    formatCols() {
      return {
        ...this.resolveTablePrefix,
        ...this.resolveDynamicTable,
        ...this.resolveTableSuffix
      }
    }
  },
  methods: {
    preventSelectedListChanged() {
      if (!this.enableSelect) return Promise.resolve(true)
      const from = this.generation.activeModel.selectedList
      const to = this.generation.activeModel.selectedListSnapshot
      let changedMsg = '请先提交更改过的志愿', changed = false
      if (from.length != to.length) {
        changed = true
      } else if (from.length) {
        const elementCheckFields = ['selected', 'rejected', 'groupId']
        from.forEach((eleFrom, idx) => {
          const eleTo = to[idx]
          const eleChanged = elementCheckFields.some(f => eleFrom[f] != eleTo[f])
          if (eleChanged) changed = true
        })
      }
      if (changed) this.$message.warning(changedMsg)
      return changed ? Promise.reject(changedMsg) : Promise.resolve(true)
    },
    async toReport() {
      await this.preventSelectedListChanged()
      this.$refs.reportDialog.open()
    },
    async toSelectSub(row) {
      await this.preventSelectedListChanged()
      // 打开选科弹窗
      const course0 = this.translateCourse0(row.groupId)
      const course1 = this.translateCourse1(row.groupId)
      this.$refs.chooseDialog.open(course0, course1)
    },
    toAiAnalysis() {
      // AI 分析 跳转
      this.$refs.aiDialog.open(this.formatRows)
    }
  }
}
</script>
<style scoped>
</style>
