<template>
  <div class="app-container">
    <el-card>
      <template #header>学校信息</template>
      <el-form label-position="right" label-width="80px">
        <el-form-item label="学校">
          {{ school && school.schoolName }}
        </el-form-item>
        <el-form-item v-if="!allowClassSelect&&isSenior&&isFrontStudent" class="form-item-readonly">
          未到重选班级时间<span class="f-red">*</span>
        </el-form-item>
      </el-form>
      <class-tree-form ref="studentForms" :data-source="classTree" :model-value="model"
                       :disabled="!allowClassSelect"></class-tree-form>
      <div class="fx-row fx-cen-cen mt20">
        <el-button v-if="isFrontTeacher" type="primary" round style="width: 150px" @click="handleExchange">申请换班
        </el-button>
        <el-button v-if="allowClassSelect" type="primary" round style="width: 150px" @click="handleSelectClass">保存班级
        </el-button>
      </div>
    </el-card>
    <el-card v-if="isFrontTeacher" class="mt20">
      <template #header>授课班级变更申请列表</template>
      <headteacher-form-list ref="formList" :options="formListOptions"></headteacher-form-list>
    </el-card>
    <el-dialog v-if="applyDialogVisible" :visible.sync="applyDialogVisible" title="申请更换授课班级" type="center"
               width="600px">
      <class-tree-form ref="form" :modelValue="model" :rules="rules" :dataSource="classTree">
      </class-tree-form>
      <div class="fx-row fx-end-cen mt20">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import ClassTreeMixin from '@/components/Cache/modules/mx-classTree-translate-mixin'
import ClassTreeForm from '@/views/system/user/profile/components/class-tree-form'
import { getSchoolParams, getUserForms } from '@/api/webApi/form'
import { updateUserGradeAndClasses } from '@/api/webApi/grade'
import HeadteacherFormList from '@/views/system/user/profile/components/headteacher-form-list'
import * as ext from '@/utils'
import consts from '@/common/mx-const'

export default {
  mixins: [ClassTreeMixin],
  name: 'school-detail',
  components: { HeadteacherFormList, ClassTreeForm },
  data() {
    return {
      model: {},
      rules: {},
      schoolSettings: {},
      applyDialogVisible: false,
      // form list
      dateRange: ext.getDefaultDateRange(1),
      queryFormTypes: [
        consts.enum.formType.addClass,
        consts.enum.formType.delClass,
        consts.enum.formType.updateClass
      ]
    }
  },
  computed: {
    ...mapGetters(['school', 'isFrontStudent', 'isFrontTeacher', 'isSenior']),
    allowClassSelect() {
      // allowSelectClass这个控制是给学生选班期间使用的
      return this.schoolSettings.allowSelectClass && this.isFrontStudent
    },
    formListOptions() {
      return {
        queryApi: getUserForms,
        queryParams: {
          begin: this.dateRange.first(),
          end: this.dateRange.last(),
          formType: this.queryFormTypes.toString()
        }
      }
    }
  },
  mounted() {
    this.loadSchoolSettings()
  },
  methods: {
    ...mapActions(['GetInfo']),
    translateClassTreeReady() {
      // 按年级建立动态监听
      this.classTree.forEach(grade => {
        // 需要动态组建model方便form交互
        const boundGrade = this.school.grade.find(g => g.gradeId == grade.grade)
        const boundClassList = boundGrade?.clazz.map(c => c.classId) || []
        this.model[grade.name] = boundClassList
        this.rules[grade.name] = [] // hht 22.1.27 因都涉及多对多，原来的校验规则已经失效
      })
      // 浅表拷贝，为了触发mxClassTreeForm watch
      this.model = {
        ...this.model
      }
    },
    loadSchoolSettings() {
      getSchoolParams().then(res => {
        this.schoolSettings = res.data
      })
    },
    handleExchange() {
      this.applyDialogVisible = true
    },
    handleClose() {
      this.applyDialogVisible = false
    },
    handleConfirm() {
      this.$refs.form.validate().then(data => {
        const submitModel = this.$refs.form.getModel()
        console.log('mx-float-form-page form valid:', data, submitModel)
        this.submit(submitModel)
      })
    },
    submit(submitModel) {
      // 因为data-checkbox只能选择value，所以最终要转化一下才能变成提交的格式
      const transferBounds = Object.keys(submitModel)
        .filter(gradename => submitModel[gradename].length)
        .map(gradename => {
          const boundClassIdList = submitModel[gradename]
          const matchGrade = this.classTree.find(g => g.name == gradename)
          const clone = {
            ...matchGrade
          }
          clone.classList = matchGrade.classList.filter(c => boundClassIdList.includes(c.classId))
          return clone
        })
      if (!transferBounds.length) {
        this.msgError('请至少选择1个班级进行绑定')
        return
      }
      this.handleClose()
      updateUserGradeAndClasses({
        gradeClass: transferBounds
      }).then(rp => {
        this.GetInfo().then(_ => {
          this.msgSuccess(this.isFrontStudent ? '保存成功' : '申请成功')
          this.translateClassTreeReady() // 重新绑定，有可能直接生效
          this.reloadFormList()
        })
      })
    },
    handleSelectClass() {
      this.$refs.studentForm.validate().then(data => {
        const submitModel = this.$refs.studentForm.getModel()
        console.log('mx-float-form-page student form valid:', data, submitModel)
        this.submit(submitModel)
      })
    },
    reloadFormList() {
      if (!this.isFrontTeacher) return
      this.$refs.formList.resetQuery()
    }
  }
}
</script>

<style scoped>

</style>
