<template>
  <div>
    <div class="mb10 fx-row fx-end-base">
      <div>
        <el-button type="primary" @click="toAiAnalysis" v-if="generation > 0">AI分析</el-button>
        <el-button>选科历史记录</el-button>
      </div>
    </div>

    <mx-table :propDefines="formatCols" :rows="formatRows">
      <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 > 0">可报名</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="generation == 0">
      <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-else>
      <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" :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'

export default {

  props: {
    generation: Object
  },
  components: {
    SelectSubjectReportDialog,
    ReportStep,
    EsignDialog,
    TestDrage,
    ChooseSubjectDialog,
    AiDialog
  },
  mixins: [
    MxSelectTranslate,
    PrimaryResolverMixins,
    PrimaryDMResolverMixins,
    BackTrackingResolverMixins,
    BackTrackingDMResolverMixins,
    FinalAdjustDMResolverMixins,
    FinalAdjustResolverMixins,
    ForceAdjustResolverMixins
  ],
  data() {
    return {
      popoShow: false,
      activeStep: '',
      regInfo: '',
      prevPreferences: [1], // 选科前一轮报名的group
      optionalMajors: [],
      dialogVisible: false,
      modelsWrapper: {},
      selectedList: [],
      singleList: [], // 单志愿列表
      formatRows: []
    }
  },
  mounted() {
    // this.$refs.drage.init(this.selectedList)
  },
  computed: {
    resolveTablePrefix() {
      return {
        index: {
          type: 'index',
          label: '编号'
        },
        groupName: {
          label: '选科组合'
        },
        scoreSumGroup:{
          label:'组合成绩'
        },
        classCount: {
          label: '开设班级数'
        },
        personCount: {
          label: '人数设置'
        }
      }
    },
    resolveTableSuffix() {

      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'
        }
      }
    },
    resolveDynamicTable() {
      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)
          Object.assign(dynamicColumns, genColumns)
        }
      }
      console.log('resolveDynamicTable',dynamicColumns)
      return dynamicColumns
    },
    formatRows() {
      if(!this.selectObj?.groupIds) return []
      return this.selectObj.groupIds.split(',').map(item => {
        groupId: item
      })
    },
    formatCols() {
      return {
        ...this.resolveTablePrefix,
        ...this.resolveDynamicTable,
        ...this.resolveTableSuffix
      }
    }
    // formatTable() {
    //   // if (!this.models.length) return {}
    //   // if (!this.optionalMajors) return {}
    //   return {}
    //   // 初始化 rows cols
    //   // let rows = this.models[0].models.map(item => {
    //   //   item.allowSelectTips = item.allowSelect ? '报名中' : '无法报名'
    //   //   item.subjects = this.optionalMajors.filter(college => {
    //   //     if (college.matchedGroupIds.indexOf(item.groupId) != -1) return college.majorCategoryName
    //   //   }).map(item => item.majorCategoryName)
    //   //   item.colleges = this.optionalMajors.filter(college => {
    //   //     if (college.matchedGroupIds.indexOf(item.groupId) != -1) return college.majorCategoryName
    //   //   }).map(item => {
    //   //     return {
    //   //       college: item.collegeName,
    //   //       major: item.majorCategoryName
    //   //     }
    //   //   })
    //   //   return item
    //   // })
    //   // let formatCols  = this.formatCols({})
    //   // let stateCol = {}
    //   // // 判断当前步骤
    //   // const step = this.models.length
    //   // // step = 1  reutrn cols 选科人数比 组合实时排名 学校实时排名
    //   // console.log(this.activeOpt)
    //   // switch (this.activeOpt) {
    //   //   // 初录报名
    //   //   case config.electiveGenerationOptions.primary:
    //   //     console.log(2222222222222)
    //   //     // cols
    //   //     stateCol = {
    //   //       applyCount: {
    //   //         label: '选科人数比'
    //   //       },
    //   //       rankInGroup: {
    //   //         label: '当前组合实时排名',
    //   //       },
    //   //       rankInGrade: {
    //   //         label: '选科全校排名',
    //   //       }
    //   //     }
    //   //     formatCols = this.formatCols(stateCol)
    //   //     // rows
    //   //     console.log(rows)
    //   //     rows  = rows.map(item => {
    //   //       item.applyCount = `${item.actualCount}/${item.personCount}`
    //   //       return item
    //   //     })
    //   //     break
    //   //   // 初录结果
    //   //   case config.electiveGenerationOptions.primaryDM:
    //   //     stateCol = {
    //   //       applyCount: {
    //   //         label: '选科人数比'
    //   //       },
    //   //       groupIndicator: {
    //   //         label: '超/缺'
    //   //       },
    //   //       rankInGroup: {
    //   //         label: '当前组合实时排名',
    //   //       },
    //   //       rankInGrade: {
    //   //         label: '选科全校排名',
    //   //       }
    //   //     }
    //   //     rows  = rows.map(item => {
    //   //       item.applyCount = `${item.actualCount}/${item.personCount}`
    //   //       item.groupIndicator = item.groupIndicator
    //   //       return item
    //   //     })
    //   //     formatCols = this.formatCols(stateCol)
    //   // }
    //   //
    //   // return {
    //   //   rows,
    //   //   formatCols
    //   // }
    // }
  },
  methods: {
    getModelsByStep() {
      return this.models.findIndex()
    },
    toReport() {
      this.$refs.reportDialog.open()
    },
    toAiAnalysis() {
      //
      const currentGeneration = 1
      // AI 分析 跳转
      this.$refs.aiDialog.open(this.formatTable, currentGeneration)
    },
    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 count = this.modelsWrapper.models.reduce((prev, cur) => {
        return prev += cur.selected ? 1 : 0
      })
      if (count >= this.preferenceCount) {
        this.$message.warning(`最多选择${this.preferenceCount}个志愿`)
        return
      }
      row.selected = true
      this.selectedList.push(row)
    },
    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
        }))
        console.log(start)
        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>
