<template>
  <div class="app-container" v-loading="loading">
    <form-search :searchformShow="filterParams" ref="formSearch" @handleQuery="handleQuery"></form-search>
    <el-card class="mb20">
      <el-button type="primary" @click="openAll" size="small" round>全部开启</el-button>
      <el-button type="warning" @click="closeAll" size="small" round>全部关闭</el-button>
    </el-card>
    <el-row :gutter="12">
      <el-col :span="6" v-for="(user,index) in dataList" :key="index" class="mb12">
        <mx-teacher-info :avatar="user.avatar" :name="user.nickName"
                         :subjects="user.subjects.map(s => s.subjectName).toString()"
                         :classes="user.classes.map(c => c.gradeName + ' ' + c.className).toString()">
          <template #extra>
            <el-switch v-model="user[currentKey]" @change="changePermissionAction(user)"></el-switch>
          </template>
        </mx-teacher-info>
      </el-col>
    </el-row>
    <evaluation-empty v-if="!dataList.length"/>
  </div>
</template>
<script>
import {
  resourcesPerms,
  saveResourcesPerms
} from '@/api/webApi/back.js'
import MxTeacherInfo from '@/views/permission/components/mx-teacher-info'

export default {
  components: { MxTeacherInfo },
  data() {
    return {
      loading: false,
      filterParams: {
        gradeid: '',
        userSubject: ''
      },
      queryParams: {
        gradeId: '',
        subjectId: ''
      },
      dataList: []
    }
  },
  computed: {
    currentKey: function() {
      return this.$route.name.toLowerCase().endsWith('upload') ? 'isUpload' : 'isDownload'
    }
  },
  created() {
    this.handleQuery()
  },
  methods: {
    handleQuery(ctrlParams = {}) {
      this.queryParams.gradeId = ctrlParams.gradeid || ''
      this.queryParams.subjectId = ctrlParams.userSubject || ''
      this.getList()
    },
    getList() {
      resourcesPerms(this.queryParams).then(res => {
        this.dataList = res.data || []
      })
    },
    changePermissionAction(user) {
      saveResourcesPerms([user]).then(_ => {
      }).catch(e => this.getList())
    },
    openAll() {
      this.batchAction(true)
    },
    closeAll() {
      this.batchAction(false)
    },
    batchAction(val) {
      if (this.dataList.length == 0) {
        this.msgError('暂无数据')
        return
      }
      this.loading = true
      this.dataList.forEach(u => u[this.currentKey] = val)
      saveResourcesPerms(this.dataList).then(_ => {
        this.loading = false
        this.msgSuccess('操作成功')
      }).catch(e => {
        this.loading = false
        this.getList()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.mx-name {
  font-size: 14px;
  font-weight: 500;
  color: #5b5b5b;
}

.mx-class {
  font-size: 14px;
  font-weight: 400;
  color: #a1a1a1;
}
</style>
