<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="formatTable.cols" :rows="formatTable.rows">
      <template #rankInGroup="{label, key}">
        <div class="fx-column">
          <span>{{ label }}</span>
          <el-popover
            placement="bottom"
            trigger="click"
          >
            <span>组合成绩在填报组合的排名</span>
            <i slot="reference" class="pointer el-icon-question el-icon"></i>
          </el-popover>
        </div>
      </template>
      <template #rankInGrade="{label, key}">
        <div class="fx-column">
          <span>{{ label }}</span>
          <el-popover
            placement="bottom"
            trigger="click"
          >
            <span>组合成绩在全校的排名</span>
            <i slot="reference" class="pointer el-icon-question el-icon"></i>
          </el-popover>
        </div>
      </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 > 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>
    </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'

export default {
  props: {
    generation: {
      type: Number,
      default: 1 // 模拟报名所处状态， 0为初录
    },
    preferenceCount: {
      type: Number,
      default: 3 // 多志愿个数
    }
  },
  components: {
    SelectSubjectReportDialog,
    ReportStep,
    EsignDialog,
    TestDrage,
    ChooseSubjectDialog,
    AiDialog
  },
  mixins: [MxSelectTranslate],
  data() {
    return {
      popoShow: false,
      activeStep: '',
      regInfo: '',
      prevPreferences: [1], // 选科前一轮报名的group
      optionalMajors: [],
      dialogVisible: false,
      modelsWrapper: {},
      selectedList: [],
      singleList: [] // 单志愿列表
    }
  },
  mounted() {
    // this.$refs.drage.init(this.selectedList)
  },
  computed: {
    formatTable() {
      if (!this.modelsWrapper.models) return {}
      if (!this.optionalMajors) return {}

      // 行
      const rows = this.modelsWrapper.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
      })

      // 列
      const statCols = {}
      this.modelsWrapper.statColumns.map((column, index) => {
        const prop = 'statistic_' + index
        statCols[prop] = { label: column.name }
        rows.forEach((row) => {
          const descriptors = column.groupDescriptors.find(desc => desc.groupId == row.groupId) ?
            column.groupDescriptors.find(desc => desc.groupId == row.groupId).descriptors : []
          row[prop] = descriptors.length > 0 ? descriptors.length > 1 ? `${descriptors[0].value}/${descriptors[1].value}` : `${descriptors[0].value}` : ''
        })
      })
      const cols = {
        index: {
          type: 'index',
          label: '编号'
        },
        groupName: {
          label: '选科组合'
        },
        classCount: {
          label: '开设班级数'
        },
        personCount: {
          label: '人数设置'
        },
        ...statCols,
        rankInGroup: {
          label: '当前组合实时排名',
          slotHeader: 'rankInGroup'
        },
        rankInGrade: {
          label: '选科全校排名',
          slotHeader: 'rankInGrade'
        },
        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'
        }
      }
      return {
        rows,
        cols
      }
    }

  },
  methods: {
    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)
    },
    init(list) {
      console.log(list)
      this.modelsWrapper = list
      this.selectedList = this.modelsWrapper.models.filter(item => {
        return item.selected
      })
      // generation > 0 时 是单志愿报名
      this.singleList = this.modelsWrapper.models.filter(item => {
        return item.allowSelect
      })
      this.$nextTick(() => this.$refs.drage.init(this.selectedList))
    },
    initOption(optionalMajors) {
      console.log(optionalMajors)
      this.optionalMajors = optionalMajors
    }
  }
}
</script>
<style scoped>
.cell .el-tag {
  margin-right: 5px;
}
</style>
