<template>
  <div class="mb5 mt10 text-right">
    <el-popover v-if="!this.isSelected" ref="pop" placement="right" width="300" trigger="click">
      <div>
        <el-input type="textarea" :rows="4" placeholder="请输入原因" v-model="recommendGroup.rejectedReason"></el-input>
        <p class="fx-row jc-between mt10">
          <el-button type="primary" size="mini" @click="handlePopClose">取消</el-button>
          <el-button type="danger" size="mini" @click="handleRejected">提交</el-button>
        </p>
      </div>
      <el-button slot="reference" type="danger">不同意</el-button>
    </el-popover>
    <el-button v-if="isRejected" type="primary" @click="handleCancelRejected">撤销拒绝</el-button>
  </div>
</template>

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

export default {
  mixins: [ElectiveToolsMixin],
  name: 'elective-preference-reject',
  props: ['generation'],
  inject: {
    refreshData: {
      default: function() {
      }
    }
  },
  computed: {
    selectedList() {
      return this.generation.activeModel.selectedList
    },
    recommendGroup() {
      return this.generation.activeModel.models.find(g => g.isRecommend) || {}
    },
    isSelected() {
      return this.selectedList.some(this.isGroupSelected)
    },
    isRejected() {
      return this.selectedList.some(this.isGroupRejected)
    }
  },
  methods: {
    handlePopClose() {
      this.$refs.pop.doClose()
    },
    async handleCancelRejected() {
      try {
        this.selectedList.clear()
        await submitElectiveModels({ models: [] })
        this.$message.success('撤销成功，您可以重新报名')
      } finally {
        this.refreshData()
      }
    },
    async handleRejected() {
      if (!this.recommendGroup.rejectedReason) {
        this.$message.error('拒绝原因不能为空')
        return
      }
      try {
        const rejects = this.generation.activeModel.models
          .filter(g => g.allowSelect)
          .map(g => g.groupName).join(' ')
        await this.$confirm(`确认拒绝填报 ${rejects}`)
        this.recommendGroup.rejected = true
        this.selectedList.clear()
        this.selectedList.push(this.recommendGroup)
        await rejectRecommend({
          models: this.selectedList.map(g => ({
            groupId: g.groupId,
            rejected: g.rejected,
            rejectedReason: g.rejectedReason
          }))
        })
        this.handlePopClose()
        this.$message.warning('拒绝成功，您未填报任何组合。您可以撤销后重新填报。')
      } finally {
        this.refreshData()
      }
    }
  }
}
</script>

<style scoped>

</style>
