<template>
  <span v-if="!group.allowSelect">{{ group.disabledReason || '无法报名' }}</span>
  <span v-else-if="isRejected">已拒绝</span>
  <span v-else-if="group.selected" class="f-red btn-red" @click="handleCancel">已报名/重新报名</span>
  <span v-else-if="enableCommit" class="f-warning">不能报名</span>
  <span v-else class="btn-green" @click="handleCommit">报名</span>
</template>

<script>
import ElectiveToolsMixin from './elective-tools-mixins'
import { submitElectiveModels } from '@/api/webApi/elective/selected-subject'

export default {
  mixins: [ElectiveToolsMixin],
  name: 'elective-preference-command',
  props: ['generation', 'group'],
  inject: {
    refreshData: {
      default: function() {
      }
    }
  },
  computed: {
    selectedList() {
      return this.generation.activeModel.selectedList
    },
    isRejected() {
      return this.selectedList.some(this.isGroupRejected)
    },
    enableCommit() {
      return this.selectedList.length >= this.generation.status.preferenceCount
    },
    preferenceCount() {
      return this.generation.status.preferenceCount
    }
  },
  methods: {
    async handleCommit() {
      if (this.enableCommit) {
        this.$message.error(this.preferenceCount == 1 ? `只能填报1个志愿` : `最多只能填报${this.preferenceCount}个志愿`)
        return
      }
      if (this.preferenceCount > 1) {
        // 多志愿在elective-preference-drag中有确认环节，这里直接操作即可
        this.group.selected = true
        this.selectedList.push(this.group)
      } else {
        let confirmTip = `确认填报 ${this.group.groupName}`
        let extraDesc = ''
        if (this.generation.current > this.generation.options.primary.value) {
          extraDesc = this.group.isRecommend ? '（推荐）' : '（非推荐）'
        }
        confirmTip += extraDesc
        await this.$confirm(confirmTip)
        this.group.selected = true
        this.selectedList.push(this.group)
        try {
          await submitElectiveModels({ models: this.selectedList.map(g => ({ groupId: g.groupId })) })
          this.$message.success('报名成功')
        } finally {
          this.refreshData()
        }
      }
    },
    async handleCancel() {
      if (this.preferenceCount > 1) {
        // 同上
        this.group.selected = false
        this.selectedList.remove(this.group)
      } else {
        await this.$confirm(`确认取消填报 ${this.group.groupName}`)
        this.group.selected = false
        this.selectedList.remove(this.group)
        try {
          await submitElectiveModels({ models: this.selectedList.map(g => ({ groupId: g.groupId })) })
          this.$message.success('报名取消成功，您可以重新填报')
        } finally {
          this.refreshData()
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
