<template>
  <div class="app-container">
    <el-card class="mb20">
      <mx-condition ref="condition" :query-params="queryParams" :require-fields="requireFields" @query="handleQuery"
                    @invalid="handleInvalidQuery"></mx-condition>
    </el-card>

    <el-card v-if="queryParams.roundId">
      <div>
        <div>
          <div  v-if="round.allowDispatch && !round.dispatchCompleted" class="fx-row jc-between mb10">
            <el-button type="primary" @click="keepAll">一键维持原班级</el-button>
            <el-button type="primary" @click="send">发送名单</el-button>
          </div>
          <p class="text-right mt5 mb5 f14 mr5" v-if="round.dispatchCompleted">班主任分班完成，在 {{settings.activeDate}} 生效</p>
        </div>
        <mx-table :propDefines="propDefines" :rows="formatRows" >
          <template #temp="{row}">
            <el-popover
              placement="bottom"
              trigger="click">
              <span class="btn-green mr5" @click="changeMaster(row)">班主任</span>
              <span class="btn-green" v-if="!!row.headteacherName" @click="changeClass(row)">班级</span>

              <el-button  type="primary" slot="reference" size="mini">更换</el-button>
            </el-popover>
          </template>
          <template #cancel="{row}">
            <el-button type="danger" size="mini" @click="cancel(row)">取消</el-button>
          </template>
        </mx-table>
      </div>
    </el-card>
    <evaluation-empty v-else-if="!queryParams.roundId" shadow title="当前学年没有班主任选班数据"></evaluation-empty>
    <choose-master-teacher ref="chooseMasterTeacher" :roundId="queryParams.roundId"
                           :headTeacherSettings="headteacherSettings" @completed="handleQuery"></choose-master-teacher>
    <choose-class :roundId="queryParams.roundId" ref="chooseClass" :year="queryParams.year"
                  :headTeacherSettings="headteacherSettings" @completed="handleQuery"></choose-class>
  </div>
</template>
<script>
import {
  getTeacherSettings,
  keepAllOfTeacher,
  getPublish,
  saveTeacherSettings,
  getRound
} from '@/api/webApi/elective/dispatch'
import ChooseMasterTeacher from './components/choose-master-teacher'
import classTreeMixin from '@/components/Cache/modules/mx-classTree-translate-mixin'
import ChooseClass from './components/choose-class'
import MxCondition from '@/components/MxCondition/mx-condition'

export default {
  components: {
    MxCondition,
    ChooseMasterTeacher,
    ChooseClass
  },
  mixins: [classTreeMixin],
  data() {
    return {

      round: {},
      requireFields: ['year', 'roundId'],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        total: '',
        year: '',
        roundId: ''
      },
      settings: {}, // 分班时间配置
      headteacherSettings: null
    }
  },
  computed: {
    propDefines() {
      if(!this.round) return {}
      return  {
        year: {
          label: '学年'
        },
        className: {
          label: '原班级'
        },
        headteacherName: {
          label: '原班主任姓名'
        },
        temp: {
          label: '确认班主任',
          slot: 'temp',
          hidden:this.round.dispatchCompleted
        },
        newClassName: {
          label: '新班级号'
        },
        newHeadteacherName: {
          label: '新班主任姓名'
        },
        cancel: {
          label: '操作',
          slot: 'cancel',
          hidden:this.round.dispatchCompleted
        }
      }
    },
    formatRows() {
      if (!this.classTree.length) return []
      if (!this.headteacherSettings) return []
      return this.classTree.find(item => item.year == this.queryParams.year)
        ?.classList.map(item => {
          const copy = { ...item }
          const setting = this.headteacherSettings[copy.classId]
          copy.year = this.queryParams.year
          copy.newClassId = setting ? copy.classId : ''    // 新班级Id
          copy.newClassName = setting ? copy.className : ''    // 新班级名称
          copy.newHeadteacherName = setting ? setting.nickName : ''    // 新班主任名称
          copy.newHeadteacherCode = setting ? setting.customerCode : ''    // 新班主任code
          return copy
        }) || []
    },
    classList() {
      return this.classTree.find(item => item.year == this.queryParams.year).classList
    }
  },
  methods: {
    getPublish() {
      getPublish({
        roundId: this.queryParams.roundId
      }).then(res => {
        this.settings = res.data
        console.log(res)
      })
    },
    async keepAll() {
      // 是否含有原班级班主
      const isExist = this.classList.filter(item =>  {
        return item.headteacherCode}).length > 0
      if(!isExist) {
        this.$message.warning('没有原班级班主任')
        return
      }
      if (this.headteacherSettings && Object.keys(this.headteacherSettings).length > 0) {
        await this.$confirm(`一键维持原班级会覆盖您之前的设置，是否继续?`)
        this.keepAllOfTeacher()
      } else {
        await this.$confirm(`是否一键维持原班级?`)
        this.keepAllOfTeacher()
      }
      // 维持原班级
    },
    getHeadteacherSettings() {
      getTeacherSettings({
        roundId: this.queryParams.roundId
      }).then(res => {
        this.headteacherSettings = res.data
      })
    },
    keepAllOfTeacher() {
      keepAllOfTeacher({
        roundId: this.queryParams.roundId
      }).then(res => {
        // 维持班级后刷新
        this.getHeadteacherSettings()
      })
    },
    send() {
      const headteacherSettings = Object.values(this.headteacherSettings).map(item => {
        return item.customerCode
      })
      if (headteacherSettings.length < this.classList.length) {
        this.$message.warning('还有班级未分配新班主任和新班级号')
        return
      }
      console.log(headteacherSettings)
      // 验证重复
      if((new Set(headteacherSettings)).size != headteacherSettings.length) {
        this.$message.warning('有重复的班主任,请先校验好再发布')
        return
      }

      this.$Dialog('DispatchMaster',{
        settings: this.settings
      },(val) => {
        this.handleQuery()
      })
    },
    async cancel(row) {
      console.log(row)
      if (!row.newHeadteacherCode) {
        this.$message.warning('请先设定新班级')
        return
      }
      await this.$confirm(`是否撤回你对该班级(原${row.className})的操作?`)
      saveTeacherSettings({
        roundId: this.queryParams.roundId,
        classId: row.newClassId
      }).then(res => {
        this.$message.success('取消成功')
        this.handleQuery()
        console.log(res)
      })
    },
    handleQuery() {
      // 获取班主任 settings
      this.getRound()
      this.getHeadteacherSettings()
      this.getPublish()
    },
    changeMaster(row) {
      this.$refs.chooseMasterTeacher.init(row)
    },
    // 获取批次的组合
    getRound() {
      getRound({
        year:this.queryParams.year,
        round:this.queryParams.roundId,
      }).then(res => {
        this.round = res.data
      })
    },
    changeClass(row) {
      this.$refs.chooseClass.init(row)
    },
    handleInvalidQuery() {
      this.headteacherSettings = null
    }
  }

}
</script>
<style>

</style>
