<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="!currentSupplyInfo.hidden" v-html="currentSupplyInfo.info"></p>
      </div>
      <div v-if="!readonly">
        <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}">
          <el-tag size="medium" :type="row.allowSelect ? 'warning' : 'danger'" >{{row.groupName}}</el-tag>
      </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}">
        <span class="f-red" v-if="!row.allowSelect">无法报名</span>
        <div v-else>
          <span v-if="generation.current > 1" @click="commit" 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 == 1">
      <p >您的选科志愿: <span v-for="(item,index) in activeModels.selectedList">
      {{ item.groupName }}
<!--        {{ index + 1 < selectedList.length ? '、' : '' }}-->
      </span>
      </p>
      <div >
        <test-drage ref="drage" :btnDisabled="this.generation.current != 1"  :selectedList="activeModels.selectedList"></test-drage>
        <el-button @click="commit" type="primary" v-if="this.generation.current == 1">提交</el-button>
      </div>
    </div>
    <!--  补录报名和二次补录报名和调剂报名 -->
    <div v-if="flagShow">
<!--      <div v-for="item in singleList" class="mb5 mt5">-->
<!--        <el-button @click="commit" type="primary">{{ `${item.groupName} : 报名` }}</el-button>-->
<!--      </div>-->
      <div class="mb5 mt10 text-right">
        <el-popover
          placement="right"
          width="300"
          v-model="popoShow"
          trigger="click"
        >
          <div>
            <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" v-if="">提交</el-button>
            </p>
          </div>

          <el-button slot="reference" type="danger">不同意</el-button>
        </el-popover>
      </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" :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 PrimaryResolverMixins
  from '@/views/system/user/profile/components/round-select-resolvers/primary-resolver-mixins'
import PrimaryDMResolverMixins
  from '@/views/system/user/profile/components/round-select-resolvers/primaryDM-resolver-mixins'
import BackTrackingResolverMixins
  from '@/views/system/user/profile/components/round-select-resolvers/backTracking-resolver-mixins'
import BackTrackingDMResolverMixins
  from '@/views/system/user/profile/components/round-select-resolvers/backTrackingDM-resolver-mixins'

import FinalAdjustResolverMixins
  from '@/views/system/user/profile/components/round-select-resolvers/finalAdjust-resolver-mixins'
import FinalAdjustDMResolverMixins
  from '@/views/system/user/profile/components/round-select-resolvers/finalAdjustDM-resolver-mixins'
import ForceAdjustResolverMixins
  from '@/views/system/user/profile/components/round-select-resolvers/forceAdjust-resolver-mixins'
import OverUnderBadge from '@/views/elective/publish/components/steps/fauclty/over-under-badge'
import { submitElectiveModels } from '@/api/webApi/elective/selected-subject'

export default {
  props: {
    generation: Object,
    readonly: Boolean, // 校长端不允许操作
    optionalMajors: { type: Array, default: () => [] }
  },
  components: {
    OverUnderBadge,
    SelectSubjectReportDialog,
    ReportStep,
    EsignDialog,
    TestDrage,
    ChooseSubjectDialog,
    AiDialog
  },
  inject: ['loadStudentSelected','getStudentElectiveModels'],
  mixins: [
    MxSelectTranslate,
    PrimaryResolverMixins,
    PrimaryDMResolverMixins,
    BackTrackingResolverMixins,
    BackTrackingDMResolverMixins,
    FinalAdjustDMResolverMixins,
    FinalAdjustResolverMixins,
    ForceAdjustResolverMixins
  ],
  data() {
    return {
      popoShow: false,
      activeStep: '',
      regInfo: '',
      dialogVisible: false,
      singleList: [], // 单志愿列表
      rows: [],
    }
  },
  computed: {
    // 不符
    currentSupplyInfo() {
      if(!this.generation.models.length) return {}
      // console.log(this.generation)
      if(this.generation.active < 2) return {}
      let info = ''
      const activeModels = this.generation.models.find(item => item.generation == this.generation.active)
      // 是否被录取？
      const approved =  activeModels.models.filter(item => {return item.approved})
      if(approved.length) {
        // 查找
        // 已被录取
        info = `同学，你好，你之前所选择的${approved.groupName}已被录取`
      }else {
        // 已报名未被录取的group 取当前models的前一个
        const prevModels =  this.generation.models.find(item => item.generation == activeModels.generation - 1)
        // 拒绝的组合
        const refuseGroup = prevModels.models.filter(item => {return item.selected})
        // 获取报名的阶段
        let tips = ''
        console.log( Object.values(this.generation.options))
        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
        }
        console.log(prevGen)

        console.log(refuseGroup)
        info = `<p>同学，你好，你在${tips}所选择的 <span class="f-red">${refuseGroup.map(g => g.groupName).join(',').toString()} </span> 不符合报名条件现有以下标黄组合可以重新报名</p>`
      }
      console.log(approved)
      const isHidden = this.generation.active > 1
      return {
        hidden: !isHidden,
        info:info
      }
    },
    flagShow() {
      return (this.generation.current == 3 && this.generation.active == 3) ||
        (this.generation.current == 5 && this.generation.active == 5) ||
        (this.generation.current == 5 && this.generation.active == 7)
    },
    aiButtonShow() {
      const aiButtonShow = !this.generation.activeOpt?.decisionMaking && this.generation.activeOpt?.key != 'primary'
      return aiButtonShow
    },
    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 {
        allowSelectTips: {
          label: '报名状态'
        },
        temp: {
          label: '选择专业',
          width: '140',
          slot: 'temp',
          hidden: this.readonly
        },
        subjects: {
          label: '自选专业',
          slot: 'subjects',
          width: '150'
        },
        colleges: {
          label: '院校',
          slot: 'colleges',
          width: '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)
          Object.assign(dynamicColumns, genColumns)
        }
      }
      return dynamicColumns
    },
    activeModels(){
      if(!this.generation) return {}
      const generation = this.generation.models.find(item => item.generation == this.generation.active)
      // generation.selectedList = generation.models.filter(item => {
      //   return item.selected
      // })
      return generation
    },
    // 初始化 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.allowSelect ? '报名中' : 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'])
        // this.$set(row,'colleges',matchedMajors.map(m => ({ college: m.collegeName, major: m.majorCategoryName })))
        // this.$set(row,'subjects',matchedMajors.map(m => m['majorCategoryName']))
        return row
      })
    },
    formatCols() {
      return {
        ...this.resolveTablePrefix,
        ...this.resolveDynamicTable,
        ...this.resolveTableSuffix
      }
    }
  },
  methods: {
    getModelsByStep() {
      return this.models.findIndex()
    },
    toReport() {
      // 是否更改了报名数据 ?
      const flag = this.activeModels.models.filter(item  => item.selected).length == this.activeModels.selectedList.length
      if(!flag) {
        this.$message.warning('请先提交更改过的志愿')
        return
      }
      this.$refs.reportDialog.open()
    },
    toAiAnalysis() {
      // AI 分析 跳转
      console.log(this.formatRows)
      this.$refs.aiDialog.open(this.formatRows)
    },
    commit() {
      if (this.generation.current == 1) {
        const real = this.activeModels.selectedList.filter(item => {
          return item.selected == true
        })
        console.log(real)
        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.selectedList,
          // esign:this.base64Img
        }).then(res => {
          if(res.code == 200) {
            this.$message.success('报名成功')
            this.loadStudentSelected()
            this.getStudentElectiveModels()
          }
          console.log(res)
        })
      }).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.models.find(item =>  item.groupId == row.groupId).selected = true
      row.selected = true
      this.activeModels.selectedList.push(row)
    },
    toUnSelect(row) {
      this.$confirm(`是否解除选科组合【${row.groupName}】`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.activeModels.models.find(item =>  item.groupId == row.groupId).selected = false
        row.selected = false
        const start = this.activeModels.selectedList.findIndex(item => item.groupId == row.groupId)
        console.log(start)
        this.activeModels.selectedList.splice(start, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消解除报名'
        })
      })
    },
    toSelectSub(row) {
      // 是否更改了报名数据 ?
      const flag = this.activeModels.models.filter(item  => item.selected).length == this.activeModels.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)
    },
    initOption(optionalMajors) {
      console.log(optionalMajors)
      this.optionalMajors = optionalMajors
    }
  }
}
</script>
<style scoped>
.cell .el-tag {
  margin-right: 5px;
}
</style>
