<template>
  <div>
    <el-dialog
      :title="title"
      class="upload-upload"
      :visible.sync="topVisible"
      :before-close="handleClose"
      :width="selectType ? '50%' : '30%'">
      <template v-if="selectType">
        <template v-if="gradeData.length > 0">
          <div style="margin-bottom: 15px;">
            <div style="text-align: center;" v-if="selectType == 'class'">
              <el-radio-group v-model="selTab">
                <el-radio-button label="班级"></el-radio-button>
                <el-radio-button label="个人"></el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <div style="border: 1px solid #ebebeb; padding: 8px;">
            <div style="font-weight: 600;margin-bottom: 8px;">选择年级</div>
            <el-radio-group v-model="checkedGrade" size="mini">
              <el-radio v-for="grade in gradeData" :label="grade.gradeId" :key="grade.gradeId" @change="changeGrade"
                        border>{{ grade.gradeName }}
              </el-radio>
            </el-radio-group>

            <div v-if="classData.length > 0">
              <div style="font-weight: 600;margin-bottom: 8px;margin-top: 8px;">选择班级</div>
              <el-radio-group v-model="checkedClass" size="mini">
                <el-radio v-for="classes in classData" :label="classes.classId" :key="classes.classId"
                          @change="changeClass" border>{{ classes.className }}
                </el-radio>
              </el-radio-group>
            </div>
          </div>
        </template>

        <div v-else style="color: #dbdbdb; text-align: center;margin-bottom: 20px;">当前用户没有查找到班级和学生信息</div>


        <template v-if="'class' != selectType || selTab == '个人'">
          <div class="student_container" v-if="studentData.length > 0"
               style="border: 1px solid #ebebeb; padding: 15px;margin-top: 15px;">
            <el-checkbox :indeterminate="studentIndeterminate" v-model="studentAll" @change="handleStudentAllChange">
              全选学生
            </el-checkbox>
            <el-checkbox-group v-model="checkedStudent" @change="handleStudentChange">
              <el-checkbox v-for="student in studentData" :label="student.code" :key="student.id"
                           :disabled="defaultSelected.includes(student.code)">{{ student.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </template>

        <div style="margin-top: 8px;" v-if="'class' != selectType">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="remark"></el-input>
        </div>
      </template>

      <div v-else class="text-center" style="margin: 20px 0 50px 0;">
        <el-button v-if="pageName" :type="type==1?'primary':''" @click="type=1">{{ pageName }}</el-button>
        <el-button v-if="isZdy" :type="type==2?'primary':''" @click="type=2,visible=true" style="margin-left:20px">自定义
        </el-button>
      </div>
      <div class="text-center">
        <el-button type="primary" style="margin-top: 20px;" round @click="handleSave">确定{{ scene }}</el-button>
      </div>
    </el-dialog>

    <el-dialog class="upload-upload" title="自定义" :visible.sync="visible" width="30%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin-top:20px">
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
      </el-form>
      <div class="text-center">
        <el-button type="primary" round @click="save" style=" margin-top: 30px;margin-bottom: 30px;">确定{{ scene }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import * as back from '@/api/webApi/back'
import { getClassStudents } from '@/api/webApi/front'

export default {
  props: {
    title: { //标题
      type: String,
      default: () => {
      }
    },
    pageName: {
      type: String,
      default: () => {
      }
    },
    dialogVisible: {// 显示隐藏
      type: Boolean,
      default: false
    },
    isZdy: {
      // 是否自定义
      type: Boolean,
      default: true
    },
    selectType: {
      type: String,
      default: ''
    },
    scene: {
      type: String,
      default: '上传'
    },
    defaultSelected: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {
        name: ''
      },
      visible: false,
      type: 1,
      gradeData: [],
      classData: [],
      studentData: [],
      checkedGrade: '',
      checkedClass: '',
      checkedStudent: [...this.defaultSelected],
      gradeIndeterminate: true,
      classIndeterminate: true,
      studentIndeterminate: true,
      gradeAll: false,
      classAll: false,
      studentAll: false,
      rules: {
        name: [
          { required: true, message: '请输入文件名称', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ]
      },

      selTab: this.selectType == 'class' ? '班级' : '个人',
      remark: ''
    }
  },
  computed: {
    topVisible: {
      get: function() {
        return this.dialogVisible
      },
      set: function(val) {
        this.$emit('update:dialogVisible', val)
      }
    }
  },
  watch: {
    'gradeId': function(value) {
      this.checkList = []
      this.group = []
      if (value) {
        let subjectParam = {
          gradeId: value
        }
        back.getUserClasses(subjectParam).then(response => {
          this.group = response.data
        }).catch(err => {

        })
      } else {

      }
    }
  },
  created() {
    if (this.selectType) {
      this.getStudentsData()
    }
  },
  methods: {
    handleGradeAllChange(val) {
      this.checkedGrade = val ? this.forClassStudent(this.gradeData, 'gradeId') : []
      if (val) {
        this.handleClassAllChange(true)
        this.handleStudentAllChange(true)
      } else {
        this.handleClassAllChange(false)
        this.handleStudentAllChange(false)
      }
    },
    handleGradeChange(value) {
      let checkedCount = value.length
      this.gradeAll = checkedCount === this.gradeData.length
      this.gradeIndeterminate = checkedCount > 0 && checkedCount < this.gradeData.length
    },
    changeGrade() {
      this.checkedClass = ''
      this.studentData = []
      this.checkedStudent = [...this.defaultSelected]
      this.gradeData.forEach(item => {
        if (item.gradeId == this.checkedGrade) {
          this.classData = item.classes
        }
      })
    },

    handleClassAllChange(val) {
      this.checkedClass = val ? this.forClassStudent(this.classData, 'classId') : []
      if (val) {
        this.handleStudentAllChange(true)
      } else {
        this.handleStudentAllChange(false)
      }
    },
    handleClassChange(value) {
      let checkedCount = value.length
      this.classAll = checkedCount === this.classData.length
      this.classIndeterminate = checkedCount > 0 && checkedCount < this.classData.length
    },
    changeClass() {
      this.checkedStudent = [...this.defaultSelected]
      this.classData.forEach(item => {
        if (item.classId == this.checkedClass) {
          this.studentData = item.students
        }
      })
    },

    handleStudentAllChange(val) {
      this.checkedStudent = val ? this.forClassStudent(this.studentData, 'code') : []
    },
    handleStudentChange(value) {
      let checkedCount = value.length
      this.studentAll = checkedCount === this.studentData.length
      this.studentIndeterminate = checkedCount > 0 && checkedCount < this.studentData.length
    },

    forClassStudent(data, k) {
      return data.map(item => item[k])
    },
    getStudentsData() {
      getClassStudents().then(response => {
        this.gradeData = []
        // this.classData = []
        // this.studentData = []
        response.data.forEach(gitem => {
          this.gradeData.push(gitem)
          // if (gitem.classes) {
          //   gitem.classes.forEach((citem, cindex) => {
          //     citem.gradeId = gitem.gradeId
          //     this.classData.push(citem)
          //     if (citem.students) {
          //       citem.students.forEach(sitem => {
          //         sitem.gradeId = gitem.gradeId
          //         sitem.classId = citem.classId
          //         this.studentData.push(sitem)
          //       })
          //     }
          //   })
          // }
        })
      }).catch(err => {

      })
    },
    handleClose(done) {
      this.$emit('dialogVisibleClose', false)
      done()
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('handleClose', this.type, this.form.name)
        } else {
          return false
        }
      })
    },
    handleSave() {
      if (this.selectType) {
        // this.$emit('handleClose', this.type ,'')
        if (this.selTab == '班级') {
          if (this.checkedClass) {
            // todo 调接口只要传classId（参数：this.checkedClass，年级id不是必传参数，把数据返回到父页面调接口）
            let ids = []
            this.studentData.forEach(item => {
              ids.push(item.code)
            })
            let resData = {
              checkedGrade: this.checkedGrade,
              checkedClass: this.checkedClass,
              // checkedStudent:ids,
              remark: this.remark
            }
            this.$emit('handleClose', this.type, '', resData)
          } else {
            this.$message.warning('请选择年级和班级！')
            return
          }
        } else {
          if (this.checkedStudent.length == 0) {
            this.$message.warning('请选择年级班级与学生！')
            return
          } else {
            // todo 调接口保存数据（参数：this.checkedClass 和 this.checkedStudent ，年级id不是必传参数，全选传全部学生的code，把数据返回到父页面调接口）
            let resData = {
              checkedGrade: this.checkedGrade,
              checkedClass: this.checkedClass,
              checkedStudent: this.checkedStudent,
              remark: this.remark
            }
            this.$emit('handleClose', this.type, '', resData)
          }
        }
      } else {
        this.$emit('handleClose', this.type, '')
      }
    }
  }
}
</script>

<style scoped>
.upload-upload .student_container /deep/ .el-checkbox-group {
  max-height: 105px;
  overflow-y: auto;
}

.upload-upload /deep/ .el-dialog__header {
  text-align: center;
  background: #47C6A2;
}

.upload-upload /deep/ .el-dialog__body {
  max-height: 570px;
  overflow-y: auto;
}

.upload-upload /deep/ .el-dialog__title {
  color: #fff
}

.upload-upload /deep/ .el-icon-close {
  color: #fff
}

/deep/ .checkbox-list {
  border: 1px solid #999;
  padding: 10px;
  margin: 20px 0;
}

.el-checkbox {
  margin-bottom: 10px
}

/deep/ .el-radio.is-bordered + .el-radio.is-bordered {
  margin-left: 0px;
  margin-bottom: 3px;
}
</style>
