<template>
  <div class="fx-column" v-loading="calculating">
    <!--  选择  -->
    <el-form ref="form" :model="groupModel" :rules="settingRules" label-width="70px" label-position="right">
      <el-form-item prop="groupIds" label="组合">
        <el-checkbox-group v-model="groupModel.groupIds" @change="resetCalculateStatus">
          <el-checkbox v-for="(opt,idx) in listGroupsOptions" :key="idx" :label="opt.value">{{ opt.text }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>

    <!--  明细  -->
    <mx-table :prop-defines="groupLimitDefines" :rows="mergedRoundGroups">
      <template #replace="{row, value, $index}">
        <el-popover :ref="'replace_'+$index" width="80" trigger="click" popper-class="zero-padding-popover">
          <div class="fx-column">
            <el-divider>替换</el-divider>
            <el-button v-for="(g,i) in replaceGroupOptions" :key="i" class="ml0" plain type="text"
                       @click="replaceGroup(row.groupId, g.value)&&$refs['replace_'+$index].doClose()">{{ g.text }}
            </el-button>
          </div>
          <el-button slot="reference" type="text" :disabled="!enableEdit||!replaceGroupOptions.length">
            {{ value }}
            <i class="el-icon-refresh" v-if="enableEdit&&replaceGroupOptions.length"></i>
          </el-button>
        </el-popover>
      </template>
      <template #input="{row,key}">
        <el-input-number v-model="row[key]" :min="0" style="width: 120px"
                         @change="key=='classCount'&&resetCalculateStatus()"></el-input-number>
      </template>
      <template #switch="{row,key}">
        <el-switch v-model="row[key]"></el-switch>
      </template>
      <template #view="{row,key}">
        <el-button type="text" @click="handleView(row, key)" icon="el-icon-view">查看</el-button>
      </template>
    </mx-table>

    <!--  师资填写  -->
    <div class="mt20 mb5">
      <el-button-group>
        <el-button v-if="groupsValid" :type="enableFacultyForm?'primary':''" size="small"
                   @click="openFacultyForm">AI师资匹配
        </el-button>
        <el-button v-if="groupsValid&&(enableFacultyForm||enableFacultyResult)" size="small"
                   :plain="!groupModel.completed"
                   :type="groupModel.completed?enableFacultyResult?'primary':'':'warning'"
                   @click="calculateFacultyResult">
          {{ groupModel.completed ? '' : '生成' }}师资匹配结果
        </el-button>
      </el-button-group>
    </div>
    <faculty-forms ref="formFaculty" v-if="groupsValid&&enableFacultyForm" :rows="groupModel.faculties"
                   @change="resetCalculateStatus"></faculty-forms>

    <!--  师资结果  -->
    <faculty-result v-if="groupsValid&&enableFacultyResult" :rows="groupModel.faculties"></faculty-result>

    <!--  操作  -->
    <div class="fx-row mt20">
      <el-popover ref="popoverAdd" trigger="click" placement="top" width="80" popper-class="zero-padding-popover"
                  :disabled="!enableAdd">
        <div class="fx-column">
          <el-button plain type="text" @click="$emit('new')&&$refs.popoverAdd.doClose()">重新创建</el-button>
          <el-button v-for="(gm,idx) in settingModel['groupModels']" :key="idx" plain type="text" class="ml0"
                     @click="$emit('clone', gm)&&$refs.popoverAdd.doClose()">
            从'{{ gm.displayName }}'复制
          </el-button>
        </div>
        <el-button slot="reference" :disabled="!enableAdd" plain size="medium" type="primary" class="mr10">新增模型
        </el-button>
      </el-popover>
      <el-popconfirm placement="top" width="300" confirm-button-text='确认' cancel-button-text='取消' icon="el-icon-info"
                     icon-color="red"
                     :title="`确定删除'${groupModel.displayName}'吗？`" @confirm="$emit('delete', groupModel)">
        <el-button slot="reference" :disabled="!enableDelete" plain size="medium" type="danger">删除模型</el-button>
      </el-popconfirm>
    </div>

    <!--  查看成绩  -->
    <el-dialog v-if="scoreQueryVisible" :visible.sync="scoreQueryVisible" title="成绩查询" width="70%" append-to-body>
      <round-score-query :setting-model="settingModel" :group-model-index="groupModelIndex"
                         :group-model="groupModel" :default-group-id="scoreQueryGroupId"></round-score-query>
    </el-dialog>
    <!--  查看专业  -->
    <choose-subject-dialog ref="chooseDialog"></choose-subject-dialog>
    <!--  选科大数据分析  -->
    <group-query-dialog ref="groupQueryDialog"></group-query-dialog>
  </div>
</template>

<script>
import ChooseSubjectDialog from '@/views/system/user/profile/components/choose-subject-dialog'
import selectTranslateMixin from '@/components/Cache/modules/mx-select-translate-mixin'
import RoundScoreQuery from '@/views/elective/publish/components/round-score-query'
import FacultyForms from '@/views/elective/publish/components/steps/fauclty/faculty-forms'
import RoundModelConvert from '../round-model-convert'
import { calculateFaculties, generateFaculties } from '@/api/webApi/selection'
import FacultyResult from '@/views/elective/publish/components/steps/fauclty/faculty-result'
import GroupQueryDialog from '../group-query-dialog'

export default {
  components: { FacultyResult, FacultyForms, RoundScoreQuery, ChooseSubjectDialog, GroupQueryDialog },
  mixins: [selectTranslateMixin, RoundModelConvert],
  name: 'round-setting-group',
  props: {
    settingModel: {
      type: Object,
      default: _ => ({})
    },
    groupModelIndex: {
      type: Number,
      default: 0
    },
    groupModel: {
      type: Object,
      default: () => ({})
    },
    enableAdd: {
      type: Boolean,
      default: false
    },
    enableDelete: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      //
      scoreQueryVisible: false,
      scoreQueryGroupId: 0,
      //
      settingRules: {
        groupIds: [{
          required: true,
          message: '至少选择一种组合'
        }]
      },
      //
      enableEdit: true, // 可编辑状态是纯组件内行为，旨在防止用户误操作，和后台数据没有直接关系
      enableFacultyForm: false, // 打开师资填写部分
      enableFacultyResult: false, // 打开师资结论部分
      calculating: false
    }
  },
  watch: {
    'groupModel': {
      immediate: true,
      handler: function(newVal) {
        if (newVal.completed) {
          this.enableFacultyResult = true
          this.enableFacultyForm = !this.enableFacultyResult
        } else if (newVal.faculties?.length) {
          this.enableFacultyForm = true
          this.enableFacultyResult = !this.enableFacultyForm
        }
      }
    }
  },
  computed: {
    groupsValid() {
      return !!this.groupModel.groupIds.length
    },
    roundGroups() {
      // 按选项显示顺序排序
      if (!this.groupModel?.groupIds?.length) return []
      this.groupModel.groupIds.sort(
        (l, r) => this.listGroupsOptions.findIndex(opt => opt.value == l)
          - this.listGroupsOptions.findIndex(opt => opt.value == r))
      // 转化为groupSettingModel
      return this.groupModel.groupIds.map(id => ({
        groupId: id,
        groupName: this.translateGroup(id),
        personCount: 0,
        classCount: 0,
        limitPerson: false, // 开启人数限制
        rankOut: false // 开启排名挤出
      }))
    },
    mergedRoundGroups() {
      // 合并，只能用新的去补全，以此适应编辑场景
      const rawRoundGroups = this.groupModel.roundGroups
      const newRoundGroups = this.roundGroups
      const merged = newRoundGroups.map(rg => {
        const finalRg = rawRoundGroups.find(g => g.groupId == rg.groupId) || rg
        finalRg.groupName = rg.groupName
        return finalRg
      })
      this.$set(this.groupModel, 'roundGroups', merged)
      // calc replace
      return merged
    },
    hasImportWeight() {
      return !!this.settingModel.importWeight?.length
    },
    groupLimitDefines() {
      return {
        groupName: { label: '组合', slot: 'replace', width: '100px' },
        personCount: { label: '人数', slot: 'input', minWidth: '130px' },
        classCount: { label: '班级数', slot: 'input', minWidth: '130px' },
        limitPerson: { label: '人数限制', slot: 'switch' },
        rankOut: { label: '排名挤出', slot: 'switch', hidden: !this.hasImportWeight },
        scoreQuery: { label: '成绩查询', slot: 'view', hidden: !this.hasImportWeight },
        majorQuery: { label: '专业查询', slot: 'view' },
        dataQuery: { label: '数据查询', slot: 'view' }
      }
    },
    replaceGroupOptions() {
      return this.listGroupsOptions.filter(op => !this.groupModel.groupIds.includes(op.value))
    }
  },
  methods: {
    replaceGroup(from, to) {
      const fromSetting = this.groupModel.roundGroups.find(g => g.groupId == from)
      this.groupModel.groupIds.remove(from)
      this.groupModel.groupIds.push(to)
      // above will cause computed properties re-calculate
      // below will copy values from replaced setting.
      const toSetting = this.roundGroups.find(g => g.groupId == to)
      toSetting.personCount = fromSetting.personCount
      toSetting.classCount = fromSetting.classCount
      toSetting.limitPerson = fromSetting.limitPerson
      toSetting.rankOut = fromSetting.rankOut
      this.resetCalculateStatus()
      return true // return for next op in html
    },
    async openFacultyForm() {
      await this.$refs.form.validate()
      this.enableFacultyForm = true
      this.enableFacultyResult = !this.enableFacultyForm
      if (!this.groupModel.faculties.length) {
        generateFaculties().then(res => {
          this.groupModel.faculties = res.data
        })
      }
    },
    async calculateFacultyResult() {
      await this.$refs.formFaculty.validate()
      // switch directly
      if (this.groupModel.completed) {
        this.enableFacultyResult = true
        this.enableFacultyForm = !this.enableFacultyResult
        return
      }
      // need re-calculate
      this.calculating = true
      const commit = this.toApiModel(this.settingModel)
      commit.activeGroupModelIndex = this.groupModelIndex // 借参
      calculateFaculties(commit).then(res => {
        this.groupModel.faculties = res.data.groupModels[this.groupModelIndex].faculties
        this.$set(this.groupModel, 'completed', true)
        this.groupModel.completed = true
        this.enableFacultyResult = true
        this.enableFacultyForm = !this.enableFacultyResult
        this.$parent.$forceUpdate()
      }).finally(() => this.calculating = false)
    },
    resetCalculateStatus() {
      this.groupModel.completed = false
      const clearFields = ['levelClassCount', 'qualifiedClassCount', 'requiredClassesCount', 'actualClassesCount', 'missingClassesCount', 'missingTeacherCount']
      if (!this.groupsValid) {
        this.enableFacultyForm = false
        this.enableFacultyResult = false
        this.groupModel.faculties = []
      } else {
        this.groupModel.faculties?.forEach(faculty => {
          clearFields.forEach(field => faculty[field] = 0)
        })
      }
      if (this.enableFacultyForm || this.enableFacultyResult) {
        this.enableFacultyForm = true
        this.enableFacultyResult = !this.enableFacultyForm
      }
      this.$parent.$forceUpdate()
      this.$forceUpdate()
    },
    shouldGoNext() {
      return new Promise(((resolve, reject) => {
        this.$refs.form.validate()
          .then(_ => resolve(true))
          .catch(_ => {
            const msg = `${this.groupModel.displayName}：未完成组合设置`
            this.$alert(msg)
            reject(msg)
          })
      }))
    },
    handleView(row, key) {
      if (key == 'scoreQuery') {
        this.scoreQueryGroupId = row.groupId
        this.scoreQueryVisible = true
      }
      if (key == 'dataQuery') {
        const year = this.settingModel.year
        this.$refs.groupQueryDialog.open(year)
      }
      if (key == 'majorQuery') {
        // 打开选科弹窗
        const course0 = this.translateCourse0(row.groupId)
        const course1 = this.translateCourse1(row.groupId)
        const year = this.settingModel.year
        this.$refs.chooseDialog.open(course0, course1, year)
      }
    }
  }
}
</script>

<style scoped>
</style>
