<template>
  <div>
    <div class="mb10 fx-row fx-end-base">
      <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 #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">可报名</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-tag type="success" class="mb10">{{ college.major[0] }}</el-tag>
            :
            <span>{{ college.college }}</span>
          </el-col>
        </el-row>
      </template>
    </mx-table>
    <!-- 初录 多志愿拖拽 -->
    <div v-if="this.generation.current == 1">
      <p>您的选科志愿: <span v-for="(item,index) in selectedList">
      {{ item.groupName }}{{ index + 1 < selectedList.length ? '、' : '' }}</span>
      </p>
      <test-drage ref="drage" :sortList="selectedList"></test-drage>
      <el-button @click="commit" type="primary">提交</el-button>
    </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 mt5">
        <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">提交</el-button>
            </p>
          </div>

          <el-button slot="reference" type="danger">不同意</el-button>
        </el-popover>
      </div>
      {{ resolveDynamicTable }}
    </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" :prevPreferences="prevPreferences"></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'

export default {

  props: {
    generation: Object,
    readonly: Boolean, // 校长端不允许操作
    optionalMajors: { type: Array, default: () => [] }
  },
  components: {
    OverUnderBadge,
    SelectSubjectReportDialog,
    ReportStep,
    EsignDialog,
    TestDrage,
    ChooseSubjectDialog,
    AiDialog
  },
  mixins: [
    MxSelectTranslate,
    PrimaryResolverMixins,
    PrimaryDMResolverMixins,
    BackTrackingResolverMixins,
    BackTrackingDMResolverMixins,
    FinalAdjustDMResolverMixins,
    FinalAdjustResolverMixins,
    ForceAdjustResolverMixins
  ],
  data() {
    return {
      popoShow: false,
      activeStep: '',
      regInfo: '',
      prevPreferences: [1], // 选科前一轮报名的group
      dialogVisible: false,
      selectedList: [],
      singleList: [], // 单志愿列表
      rows: []
    }
  },
  computed: {
    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: '选科组合'
        },
        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'
        },
        subjects: {
          label: '自选专业',
          slot: 'subjects',
          width: '150'
        },
        colleges: {
          label: '院校',
          slot: 'colleges',
          width: '250'
        },
        signUp: {
          label: '操作',
          slot: 'signUp',
          width: '100',
          fixed: 'right',
          hidden: !enableSignUp
        }
      }
    },
    resolveDynamicTable() {
      if (!this.formatRows) 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
    },
    // 初始化 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 || '无法报名'
        row.subjects = this.optionalMajors.filter(college => {
          if (college.matchedGroupIds.indexOf(row.groupId) != -1) return college.majorCategoryName
        }).map(item => item.majorCategoryName)
        row.colleges = this.optionalMajors.filter(college => {
          if (college.matchedGroupIds.indexOf(row.groupId) != -1) return college.majorCategoryName
        }).map(item => {
          return {
            college: item.collegeName,
            major: item.majorCategoryName
          }
        })
        const matchedMajors = this.optionalMajors.filter(college => college.matchedGroupIds.includes(row.groupId))
        return {
          groupId: row.groupId,
          groupName: row.groupName,
          selected: row.selected,
          scoreSumGroup: row.scoreSumGroup,
          classCount: row.classCount,
          personCount: row.personCount,
          allowSelectTips: row.allowSelectTips,
          colleges: matchedMajors.map(m => ({ college: m.collegeName, major: m.majorCategoryName })),
          subjects: matchedMajors.map(m => m['majorCategoryName']),
          allowSelect: row.allowSelect
        }
      })
    },
    formatCols() {
      return {
        ...this.resolveTablePrefix,
        ...this.resolveDynamicTable,
        ...this.resolveTableSuffix
      }
    }
  },
  methods: {
    getModelsByStep() {
      return this.models.findIndex()
    },
    toReport() {
      this.$refs.reportDialog.open()
    },
    toAiAnalysis() {
      // AI 分析 跳转
      console.log(this.formatRows)
      this.$refs.aiDialog.open(this.formatRows)
    },
    commit() {
      console.log(this.selectedList)
      if (this.generation == 0) {
        const real = this.selectedList.filter(item => {
          return item.selected == true
        })
        if (real.length < this.preferenceCount) {
          this.$message.warning(`初录报名需要选择${this.preferenceCount}个志愿`)
          return
        }
      }

      this.$refs.esignDialog.open()
    },
    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
      }
      row.selected = true
      this.selectedList.push(row)
      this.$refs.drage.init(this.selectedList)
    },
    toUnSelect(row) {
      this.$confirm(`是否解除选科组合【${row.groupName}】`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.selected = false
        const start = this.selectedList.indexOf(this.selectedList.find((selected) => {
          return selected.groupId == row.groupId
        }))
        this.selectedList.splice(start, 1)

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    toSelectSub(row) {
      // 打开选科弹窗
      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>
