<template>
  <div class="app-container">
    <el-card :shadow="selectMode?'none':'always'">
      <template #header>老师信息</template>
      <mx-condition :query-params="queryParams" @query="handleQuery" @invalid="handleInvalidQuery"></mx-condition>
      <div v-if="dataList.length" class="mt20 fx-column">
        <template v-for="(group,idx) in displayGradeClass">
          <el-card shadow="never" :class="{'mt20':idx>0}">
            <template #header>{{ group.grade.label }}(共{{ group.grade.children.length }}个班)</template>
            <template v-if="group.headteachers.length">
              <div class="f14 f-666 mb5">班主任</div>
              <el-row :gutter="12">
                <el-col :span="6" v-for="(item,index) in group.headteachers" :key="index" class="mb12">
                  <mx-teacher-info :avatar="item.avatar" :name="item.nickName" content-height="90px"
                                   :select-mode="selectMode" :selected="item.localSelected"
                                   :selected-class-name="getSelectedClassName(item)"
                                   :classes="intersectGradeClass(item.headteacherClassNames, group.grade).toString()"
                                   @click.native="setTeacherSelected(item)">
                  </mx-teacher-info>
                </el-col>
              </el-row>
            </template>
            <template v-if="group.teachers.length">
              <div class="f14 f-666 mb5">授课老师</div>
              <el-row :gutter="12">
                <el-col :span="6" v-for="(item,index) in group.teachers" :key="index" class="mb12">
                  <mx-teacher-info content-height="90px" :avatar="item.avatar" :name="item.nickName"
                                   :subjects="item.subjectNames.toString()"
                                   :selected-class-name="getSelectedClassName(item)"
                                   :select-mode="selectMode" :selected="item.localSelected"
                                   :classes="intersectGradeClass(item.classNames, group.grade).toString()"
                                   @click.native="setTeacherSelected(item)">
                  </mx-teacher-info>
                </el-col>
              </el-row>
            </template>
          </el-card>
        </template>
      </div>
      <evaluation-empty v-else class="mt20" :shadow="false"></evaluation-empty>
    </el-card>
  </div>
</template>

<script>

import {
  resourcesPerms
} from '@/api/webApi/back.js'
import classTreeMixin from '@/components/Cache/modules/mx-classTree-translate-mixin'
import MxTeacherInfo from './components/mx-teacher-info.vue'
import MxCondition from '@/components/MxCondition/mx-condition'

export default {
  mixins: [classTreeMixin],
  components: {
    MxCondition,
    MxTeacherInfo
  },
  model: {
    prop: 'selectedCode',
    event: 'change'
  },
  props: {
    selectMode: {
      type: Boolean,
      default: false
    },
    headTeacherSettings: {
      type: Object,
      default: {}
    },
    selectedCode: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      queryParams: {
        classGradeId: '',
        classId: '',
        userSubjectId: ''
      },
      dataList: [],
      displayGradeClass: []
    }
  },
  computed: {
    selectedTeacher() {
      return this.dataList.find(item => item['localSelected'])
    },
    dataListWithSelected() {
      if (this.selectMode && this.dataList.length && this.selectedCode) {
        this.dataList.forEach(user => {
          // 本地字段，强制进入双向绑定
          this.$set(user, 'localSelected', user.customerCode == this.selectedCode)
        })
      }
      return this.dataList
    }
  },
  methods: {
    getSelectedClassName(row) {
      const headTeacherSettings = this.headTeacherSettings
      for (const key in headTeacherSettings) {
        if (headTeacherSettings[key].customerCode == row.customerCode) {
          return this.getClassName(key)
        }
      }
      return ''
    },
    handleInvalidQuery() {
      this.dataList = []
    },
    handleQuery(model) {
      resourcesPerms({
        gradeId: model.classGradeId,
        classId: model.classId,
        subjectId: model.userSubjectId
      }).then(res => {
        this.dataList = res.data || []
        this.resetDisplayTree()
      })
    },
    translateClassTreeReady() {
      this.resetDisplayTree()
    },
    resetDisplayTree() {
      if (!this.classTreeReady) return
      // 使用standardClassTree结构简单些
      const result = []
      this.standardClassTree.forEach(grade => {
        const classes = grade.children
        const matchedTeachers = this.dataListWithSelected
          .filter(t => t.classes.some(tc => classes.some(c => c.label == tc.className)))
        const matchedHeadteachers = this.dataListWithSelected
          .filter(t => t.headteacherClassIds.some(tcId => classes.some(c => c.value == tcId)))
        if (matchedTeachers.length || matchedHeadteachers.length) {
          const gradeResult = {
            grade,
            teachers: matchedTeachers,
            headteachers: matchedHeadteachers
          }
          gradeResult.teachers.forEach(t => {
            t.classNames = t.classes.map(c => c.className)
            t.subjectNames = t.subjects.map(s => s.subjectName)
          })
          gradeResult.headteachers.forEach(t => {
            t.headteacherClassNames = t.headteacherClassIds.map(id => {
              return classes.find(c => c.value == id)?.label || '未知班级'
            })
          })
          result.push(gradeResult)
        }
      })
      console.log('formatted grade class teachers', result)
      this.displayGradeClass = result
    },
    intersectGradeClass(classNames, grade) {
      return classNames.filter(name => grade.children.some(c => c.label == name))
    },
    setTeacherSelected(teacher) {
      if (!this.selectMode) return
      if (teacher.customerCode == this.selectedTeacher?.customerCode) return
      if (this.selectedTeacher) this.selectedTeacher.localSelected = false
      teacher.localSelected = true // single select mode
      this.$emit('change', teacher.customerCode)
      console.log('teacher selected:', teacher.customerCode, teacher.nickName)
    }
  }
}
</script>

<style scoped>

</style>
