<template>
  <div>
    <div class="mb10 fx-row fx-end-base jc-between">
      <div class="fx-row fx-end-cen">
        <slot name="header-prefix"></slot>
        <p v-if="generation.active > 1" v-html="currentSupplyInfo"></p>
      </div>
      <div>
        <el-button v-if="aiButtonShow" type="primary" @click="toAiAnalysis">AI分析</el-button>
        <!--        <el-button>选科历史记录</el-button>-->
      </div>
    </div>

    <mx-table :propDefines="formatCols" :rows="formatRows">
      <template #underOver="{value}">
        <over-under-badge :value="value"></over-under-badge>
      </template>
      <template #group="{row}">
        <over-under-badge :value="row.isRecommend?1:0" over-text="荐" over-type="success">
          <el-tag size="medium" :type="isGroupOverSetting(row) ? 'danger' : 'warning'">{{ row.groupName }}</el-tag>
        </over-under-badge>
      </template>
      <template #temp="{row}">
        <span class="btn-blue mr5" @click="toSelectSub(row)">选择</span>
        <span class="btn-green" @click="toReport">查看记录</span>
        <!--        <el-button>查看</el-button>-->
      </template>
      <template #signUp="{row}">
        <div v-if="!row.allowSelect">
          <div v-if="row.selected">
            <span class="btn-red" v-if="!row.rejected" @click="singleCommit('','取消报名')">取消报名</span>
            <span v-else>已拒绝</span>
          </div>
          <span v-else>{{ row.disabledReason || '无法报名' }}</span>
        </div>
        <div v-else>
          <!-- 初录后报名代 -->
          <span v-if="generation.current > 1" @click="singleCommit(row)" class="btn-green">报名</span>
          <!-- 初录报名代 -->
          <div v-else>
            <span class="f-red btn-red" v-if="row.selected" @click="toUnSelect(row)">取消报名</span>
            <span class="btn-green" v-else @click="toSelect(row)">报名</span>
          </div>
        </div>
      </template>
      <template #subjects="{row}">
        <el-row>
          <el-col :span="8" v-for="subject in row.subjects">
            <el-popover
              placement="top"
              popper-class="zero-padding-popover"
              trigger="hover"
            >
              <div class="fx-column">
                <el-button plain type="text">{{ subject }}</el-button>
              </div>
              <el-tag type="success" slot="reference" class="mr10 mb10">{{ subject[0] }}</el-tag>
            </el-popover>
          </el-col>
        </el-row>
      </template>
      <template #colleges="{row}">
        <el-row>
          <el-col :span="12" v-for="college in row.colleges">
            <el-popover
              placement="top"
              popper-class="zero-padding-popover"
              trigger="hover"
            >
              <div class="fx-column">
                <el-button plain type="text">{{ college.major }}</el-button>
              </div>
              <el-tag type="success" slot="reference" class="mr10 mb10">{{ college.major[0] }}</el-tag>
            </el-popover>
            :
            <span>{{ college.college }}</span>
          </el-col>
        </el-row>
      </template>
    </mx-table>
    <!-- 初录 多志愿拖拽 -->
    <div
      v-if="this.generation.active == generation.options.primary.value || this.generation.active == generation.options.primaryDM.value">
      <p>您的选科志愿: <span v-for="(item,index) in activeModels.generation.selectedList">
        {{ item.groupName }}
      </span>
      </p>
      <div>
        <test-drage ref="drage" :btnDisabled="this.generation.current != generation.options.primary.value"
                    :selectedList="activeModels.generation.selectedList"
        ></test-drage>
        <el-button @click="commit" type="primary" v-if="this.generation.current == generation.options.primary.value">
          提交
        </el-button>
      </div>
    </div>
    <div v-if="generation.current > generation.active && generation.active > generation.options.primaryDM.value">
      <!--  补录报名和二次补录报名和调剂报名历史报名信息 -->
      {{ historySupply }}
    </div>
    <!--  补录报名和二次补录报名和调剂报名 -->
    <div v-if="flagShow">
      <div class="mb5 mt10 text-right">
        <el-popover
          v-if="activeModels.generation.models.filter(item => {return item.selected}).length == 0"
          placement="right"
          width="300"
          v-model="popoShow"
          trigger="click"
        >
          <div>
            <!--            确定拒绝<span class="f-primary">{{recommendGroup.groupName}}</span>组合么？-->
            <!--            确定拒绝系统给您推荐的<span class="f-primary">{{ recommendGroup.groupName }}</span>组合么？-->
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入原因"
              v-model="regInfo"
            >
            </el-input>
            <p class="fx-row jc-between mt10">
              <el-button type="primary" size="mini" @click="popoShow = false">取消</el-button>
              <el-button type="danger" size="mini" @click="handleRejectRecommend">提交</el-button>
            </p>
          </div>
          <el-button slot="reference" type="danger">不同意</el-button>
        </el-popover>
        <el-button v-if="activeModels.generation.models.filter(item => {return item.rejected}).length > 0"
                   type="primary" @click="singleCommit('','撤销拒绝报名')">撤销拒绝报名
        </el-button>
      </div>
    </div>
    <esign-dialog ref="esignDialog"></esign-dialog>
    <choose-subject-dialog ref="chooseDialog"></choose-subject-dialog>
    <select-subject-report-dialog ref="reportDialog"></select-subject-report-dialog>
    <Ai-dialog ref="aiDialog" :prevPreferencesInfo="currentSupplyInfo" :generation="generation"></Ai-dialog>
  </div>
</template>
<script>
import AiDialog from './ai-analysis-dialog'
import MxSelectTranslate from '@/components/Cache/modules/mx-select-translate-mixin.js'
import TestDrage from './test-drage'
import ChooseSubjectDialog from './choose-subject-dialog'
import SelectSubjectReportDialog from '@/views/system/user/profile/components/select-subject-report-dialog'
import EsignDialog from '@/views/system/user/profile/components/esign-dialog'
import ReportStep from './report-step'
import OverUnderBadge from '@/views/elective/publish/components/steps/fauclty/over-under-badge'
import { rejectRecommend, submitElectiveModels } from '@/api/webApi/elective/selected-subject'

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

export default {
  props: {
    generation: Object,
    readonly: Boolean, // 校长端不允许操作
    optionalMajors: { type: Array, default: () => [] }
  },
  components: {
    OverUnderBadge,
    SelectSubjectReportDialog,
    ReportStep,
    EsignDialog,
    TestDrage,
    ChooseSubjectDialog,
    AiDialog
  },
  inject: {
    'refreshData': {
      default: function() {
        // do nothing
      }
    }
  },
  mixins: [MxSelectTranslate, ...resolvers],
  data() {
    return {
      popoShow: false,
      activeStep: '',
      regInfo: '', // 拒绝原因
      dialogVisible: false,
      singleList: [], // 单志愿列表
      rows: []
    }
  },
  computed: {
    historySupply() {
      // 当前代历史报名信息
      if (!this.generation.models.length) return ''
      // 填报 || 拒绝  || 未选择
      // 当前代
      const activeModels = this.generation.models.find(item => item.generation == this.generation.active)
      const isRefuse = activeModels.models.filter(item => item.rejected)
      if (isRefuse.length > 0) {
        // 拒绝了
        return '您拒绝了填报志愿'
      } else {
        //  填报 or 未选择
        const supply = activeModels.models.filter(item => item.selected)
        if (supply.length > 0) {
          return `填报志愿为${supply[0].groupName}`
        } else {
          return '您未填报志愿'
        }
      }
    },
    // 不符
    currentSupplyInfo() {
      if (!this.generation.models.length) return ''
      // console.log(this.generation)
      if (this.generation.active < this.generation.options.primaryDM.value) return ''
      let info = ''
      const activeModels = this.generation.models.find(item => item.generation == this.generation.active)
      console.log(activeModels)
      // 当前代是否被录取？
      const approved = activeModels.models.filter(item => {
        return item.approved
      })
      if (approved.length) {
        // 查找在哪一阶段被录取 ？ 根据selected 和 approved 都为true
        const model = this.generation.activeModels.filter(model => {
          const flag = model.models.some(item => {
            return item.selected && item.approved
          })
          if (flag) return model
        })
        console.log(model)
        const admissionAgent = Object.values(this.generation.options).find(item => item.value == model[0].generation - 1)
        console.log(Object.values(this.generation.options))
        // 已被录取
        info = `你在${admissionAgent.title}所选择的${approved[0].groupName}已被录取`
      } else {
        // 已报名未被录取的group 取当前models的前一个
        const prevModels = this.generation.models.find(item => item.generation == activeModels.generation - 1)

        // 是否拒绝 ？
        const isRefuse = prevModels.models.filter(item => item.rejected)
        if (isRefuse.length > 0) {
          // 拒绝报名
          let tips = ''
          const prevGen = Object.values(this.generation.options).find(item => item.value == prevModels.generation)
          if (prevGen.decisionMaking) {
            tips = Object.values(this.generation.options).find(item => item.value == prevModels.generation - 1).title
          } else {
            tips = prevGen.title
          }
          const isSupply = prevGen.decisionMaking ? '，现有以下标黄组合可以重新报名' : ''
          info = `<p>你在${tips}时拒绝填报志愿 ${isSupply} </p>`
        } else {
          // 没被录取的组合
          const refuseGroup = prevModels.models.filter(item => {
            return item.selected
          })
          // 获取报名的阶段
          let tips = ''
          const prevGen = Object.values(this.generation.options).find(item => item.value == prevModels.generation)
          if (prevGen.decisionMaking) {
            tips = Object.values(this.generation.options).find(item => item.value == prevModels.generation - 1).title
          } else {
            tips = prevGen.title
          }
          const isSupply = prevGen.decisionMaking ? '，现有以下标黄组合可以重新报名' : ''
          if (refuseGroup.length > 0) {
            info = `<p>你在${tips}所选择的 <span class="f-red">${refuseGroup.map(g => g.groupName).join(',').toString()}</span> 不符合条件${isSupply} </p>`
          } else {
            info = `<p>你在${tips}时未填报志愿 ${isSupply} </p>`
          }
        }
      }
      return info
    },
    flagShow() {
      const stepMatched = this.generation.active == this.generation.current
      const selectStep = !this.generation.activeOpt.decisionMaking
      return stepMatched && selectStep && !this.readonly && !this.activeModels.isAdmission
    },
    aiButtonShow() {
      if (!this.generation.activeOpt) return false
      const options = this.generation.options
      return !this.generation.activeOpt.decisionMaking &&
        this.generation.activeOpt != options.primary &&
        !this.readonly
    },
    resolveTablePrefix() {
      return {
        index: {
          type: 'index',
          label: '编号'
        },
        groupName: {
          label: '选科组合',
          slot: 'group',
          width: '85px'
        },
        scoreSumGroup: {
          label: '组合成绩'
        },
        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: '当前组合实时排名'
        },
        rankInGrade: {
          label: '选科全校排名'
        },
        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
    },
    activeModels() {
      if (!this.generation) return {}
      const generation = this.generation.models.find(item => item.generation == this.generation.active)
      // 是否被录取
      const isAdmission = generation.models.some(item => item.approved || item.forceAdjusted)
      console.log(isAdmission)
      // generation.selectedList = generation.models.filter(item => {
      //   return item.selected
      // })
      return {
        isAdmission,
        generation
      }
    },
    recommendGroup() {
      return this.activeModels?.generation.models?.find(m => m.isRecommend) || {}
    },
    // 初始化 rows 填充固定数据
    formatRows() {
      if (!this.optionalMajors) return []
      if (!this.generation.roundGroups?.length) return []
      if (!this.generation.activeModels?.length) return []
      const generationModels = this.generation.activeModels.last()?.models || []
      return this.generation.roundGroups.map(rg => {
        const row = generationModels.find(item => item.groupId == rg.groupId) || {}
        row.allowSelectTips = row.rejected ? '已拒绝' : row.allowSelect ? '报名中' : row.selected ? '已报名' : row.disabledReason || '无法报名'
        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: {
    getModelsByStep() {
      return this.models.findIndex()
    },
    isGroupOverSetting(row) {
      if (this.generation.activeOpt.decisionMaking) {
        console.log('isGroupOverSetting decisionMaking', row.groupApprovedCount >= row.personCount, row)
        return row.groupApprovedCount >= row.personCount
      } else {
        console.log('isGroupOverSetting', row.actualCount >= row.groupIndicator, row)
        return row.actualCount >= row.groupIndicator
      }
    },
    toReport() {
      // 是否更改了报名数据 ?
      const flag = this.activeModels.generation.models.filter(item => item.selected).length == this.activeModels.generation.selectedList.length
      if (!flag) {
        this.$message.warning('请先提交更改过的志愿')
        return
      }
      this.$refs.reportDialog.open()
    },
    toAiAnalysis() {
      // AI 分析 跳转
      this.$refs.aiDialog.open(this.formatRows)
    },
    singleCommit(row, tips) {
      const type = row == '' ? tips : '提交报名'
      // 补录及之后
      this.$confirm(`是否要${type}`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const arrRow = row == '' ? [] : [row]
        submitElectiveModels({
          models: arrRow
          // esign:this.base64Img
        }).then(res => {
          if (res.code == 200) {
            this.$message.success('操作成功')
            this.refreshData()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: `已取消${type}`
        })
      })
    },
    commit(row) {
      // 初录
      const real = this.activeModels.generation.selectedList.filter(item => {
        return item.selected == true
      })
      if (real.length < this.generation.status.preferenceCount) {
        this.$message.warning(`需要选择${this.generation.status.preferenceCount}个志愿`)
        return
      }
      this.$confirm(`是否要提交报名`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        submitElectiveModels({
          models: this.activeModels.generation.selectedList
          // esign:this.base64Img
        }).then(res => {
          if (res.code == 200) {
            this.$message.success('报名成功')
            this.refreshData()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消提交'
        })
      })

      //
      // this.$refs.esignDialog.open(this.activeModels.selectedList)
    },
    toSelect(row) {
      const preferenceCount = this.generation.status.preferenceCount
      const count = this.formatRows.reduce((prev, cur) => {
        return prev += cur.selected ? 1 : 0
      }, 0)
      if (count >= preferenceCount) {
        this.$message.warning(`最多选择${preferenceCount}个志愿`)
        return
      }
      this.activeModels.generation.models.find(item => item.groupId == row.groupId).selected = true
      row.selected = true
      if (!this.activeModels.selectedList.includes(row)) this.activeModels.generation.selectedList.push(row)
    },
    toUnSelect(row) {
      this.$confirm(`是否解除选科组合【${row.groupName}】`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.activeModels.generation.models.find(item => item.groupId == row.groupId).selected = false
        row.selected = false
        const start = this.activeModels.generation.selectedList.findIndex(item => item.groupId == row.groupId)
        this.activeModels.generation.selectedList.splice(start, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消解除报名'
        })
      })
    },
    toSelectSub(row) {
      // 是否更改了报名数据 ?
      const flag = this.activeModels.generation.models.filter(item => item.selected).length == this.activeModels.generation.selectedList.length
      if (!flag) {
        this.$message.warning('请先提交更改过的志愿')
        return
      }
      // 打开选科弹窗
      const course0 = this.translateCourse0(row.groupId)
      const course1 = this.translateCourse1(row.groupId)
      this.$refs.chooseDialog.open(course0, course1)
    },
    async handleRejectRecommend() {
      if (!this.regInfo.length) {
        this.$message.error('拒绝原因不能为空')
        return
      }
      const rejectRow = this.activeModels.generation.models.filter(item => item.allowSelect)
      await this.$confirm(`是否拒绝报名${rejectRow.map(item => item.groupName).join(',')}？`)
      // 可以报名的组合都拒绝
      rejectRecommend({
        models: rejectRow
      }).then(res => {
        if (res.code == 200) {
          this.refreshData()
        }
      }).finally(_ => {
        this.regInfo = ''
      })
    },
    initOption(optionalMajors) {
      this.optionalMajors = optionalMajors
    }
  }
}
</script>
<style scoped>
/*.cell .el-tag {*/
/*  margin-right: 2px;*/
/*}*/

/*.group /deep/ .el-badge__content.is-fixed {*/
/*  top: 8px;*/
/*  right: 14px;*/
/*}*/
</style>
