<template>
  <div class="aclassone-auth" :class="{ closeShow: closefromBtn == true }">
    <!--收回授權弹窗 -->
    <Modal class="aclassone-auth-modal" v-model="isOpenRemove" :title="titletext">
      <p>{{ $t("serviceDriveAuth['收回授權後使用數會直接設置為0，如欲給予授權可針對目標對象進行套用。']") }}</p>

      <div slot="footer">
        <Button type="text" @click="isOpenRemove = false">{{ $t("serviceDriveAuth['取消']") }}</Button>
        <Button type="primary" @click="resetAll">{{ $t("serviceDriveAuth['確定']") }}</Button>
      </div>
    </Modal>
    <div class="title">
      {{ $t("serviceDriveAuth['服務授權管理']") }}<span @click="close()"><v-icon class="close-icon" iconClass="close"/></span>
    </div>
    <div class="dashboard-title">{{ $t("serviceDriveAuth['AClassONE智慧學伴服務授權']") }}</div>
    <p class="dashboard-note">
      {{ $t("serviceDriveAuth['賦予持有該服務授權的學生TEAM Modal ID使用AClassONE智慧學伴App的權限']") }}
    </p>
    <Row class="dashboard">
      <i-col :xs="24" :sm="8" :md="8" :lg="8">
        <p class="info-num">
          <CountTo class="auth-info-num" :endVal="totalAuth" :duration="600"></CountTo>
        </p>
        <p class="info-text">{{ $t("serviceDriveAuth['總授權數']") }}</p>
      </i-col>
      <i-col :xs="24" :sm="8" :md="8" :lg="8">
        <p class="info-num">
          <CountTo class="auth-info-num" :endVal="currentAssignNum" :duration="600"></CountTo>
        </p>
        <p class="info-text">{{ $t("serviceDriveAuth['本次套用數']") }}</p>
      </i-col>
      <i-col :xs="24" :sm="8" :md="8" :lg="8">
        <p class="info-num">
          <CountTo class="auth-info-num" :endVal="usedAuth" :duration="600"></CountTo>
        </p>
        <p class="info-text">{{ $t("serviceDriveAuth['已使用數']") }}</p>
      </i-col>
    </Row>

    <!--分頁控件--->
    <span class="tab-btn" :class="{ 'tab-now': currentTab == 0 }" @click="setCurrentTab(0)">{{ $t("serviceDriveAuth['授權總覽']") }}</span>
    <span class="tab-btn" :class="{ 'tab-now': currentTab == 1 }" @click="setCurrentTab(1)">{{ $t("serviceDriveAuth['授權管理']") }}</span>
    <Row class="tabContent-wrap">
      <!--授權總攬-->
      <div v-if="currentTab == 0" class="tab-page">
        <i-col :xs="24" :sm="12" :md="12" :lg="16">
          <p class="chart-title">
            {{ $t("serviceDriveAuth['已購授權總數']") }}<span class="chart-totalnum">{{ totalAuth }}</span>
          </p>
          <AuthNumChart :clickTab="clickTab" :dbPieNumData="pieNumData" />
        </i-col>
        <i-col :xs="24" :sm="12" :md="12" :lg="8" class="chart-label">
          <div class="chart-item" v-for="(item, index) in pieNumData" :key="index">
            <div class="item-ball" :style="{ 'background-color': color[index] }" />
            <span class="item-text">{{ item.name }}</span>
            <p class="item-num">{{ item.value }}</p>
          </div>
        </i-col>

        <div class="chart-note"><span class="list-icon">*</span>&nbsp;{{ $t("serviceDriveAuth['note']") }}</div>
        <div class="bottom-border" />
        <div v-if="currentTab == 0" class="save-btn buy-btn">{{ $t("serviceDriveAuth['添購其他授權']") }}</div>
      </div>
      <!--授權管理-->
      <div v-if="currentTab == 1" class="option-group">
        <p class="small-title">{{ $t("serviceDriveAuth['快速套用授權']") }}</p>
        <Row class="option-item">
          <i-col :xs="24" :sm="12" :md="12" :lg="22"
            ><p class="option-text">{{ $t("serviceDriveAuth['套用至所有當前勾選項目']") }}</p></i-col
          >
          <i-col :xs="24" :sm="12" :md="12" :lg="2"
            ><div class="assign-btn" style="margin-top: -2px" @click="assignType(1)" :class="{ 'light-btn': currentAssignType == 1 }">
              {{ $t("serviceDriveAuth['套用']") }}
            </div></i-col
          >
        </Row>
        <Row class="option-item">
          <i-col :xs="24" :sm="12" :md="12" :lg="22"
            ><p class="option-text">
              {{ $t("serviceDriveAuth['套用至當前勾選目標第']") }}
              <input :disabled="selected.length == 0" class="input-num" v-model="inputSelectMin" type="number" placeholder="-" :max="selected.length" min="1" />{{ $t("serviceDriveAuth['項至第']") }} <input :disabled="selected.length == 0" placeholder="-" class="input-num" v-model="inputSelectMax" type="number" :min="inputSelectMin" :max="selected.length" />{{ $t("serviceDriveAuth['項']") }}
            </p></i-col
          >
          <i-col :xs="24" :sm="12" :md="12" :lg="2"
            ><div
              class="assign-btn"
              style="margin-top: 2px"
              @click="assignType(2)"
              :class="{
                'light-btn': currentAssignType == 2,
                'disabled-btn': inputSelectMin > selected.length == true || inputSelectMax > selected.length == true || inputSelectMin > inputSelectMax == true || inputSelectMax <= 0 || inputSelectMax == '' || inputSelectMin <= 0 || inputSelectMin == ''
              }"
            >
              {{ $t("serviceDriveAuth['套用']") }}
            </div></i-col
          >
        </Row>
        <Row class="option-item">
          <i-col :xs="24" :sm="12" :md="12" :lg="22"
            ><p class="option-text">
              {{ $t("serviceDriveAuth['套用至']") }}
              <!-- 學制Select -->
              <Select class="dark-iview-select" v-model="searchPeriod" :placeholder="$t('stuAccount.periodHolder')" clearable @on-clear="currentFilter = -1" @on-open-change="cleanData(0)" @on-change="filterData">
                <Option v-for="(item, index) in periods" :value="item.id" :key="index">{{ item.name }}</Option>
              </Select>
              {{ $t("serviceDriveAuth['所有項目']") }}
            </p></i-col
          >
          <i-col :xs="24" :sm="12" :md="12" :lg="2"
            ><div
              class="assign-btn"
              style="margin-top: 2px"
              @click="assignType(3)"
              :class="{
                'light-btn': currentAssignType == 3,
                'disabled-btn': currentFilter != 0 || searchPeriod == ''
              }"
            >
              {{ $t("serviceDriveAuth['套用']") }}
            </div></i-col
          >
        </Row>
        <Row class="option-item">
          <i-col :xs="24" :sm="12" :md="12" :lg="22"
            ><p class="option-text">
              {{ $t("serviceDriveAuth['套用至']") }}

              <!-- 學級Select -->
              <Select class="dark-iview-select" v-model="searchGrade" :placeholder="$t('stuAccount.gradeHolder')" not-found-text="请先选择学段" clearable @on-clear="currentFilter = -1" @on-open-change="cleanData(1)" @on-change="filterData">
                <Option v-for="(item, index) in grades" :value="item.id" :key="index">{{ item.name }}</Option>
              </Select>
              {{ $t("serviceDriveAuth['所有項目']") }}
            </p></i-col
          >
          <i-col :xs="24" :sm="12" :md="12" :lg="2"
            ><div
              class="assign-btn"
              style="margin-top: 2px"
              @click="assignType(4)"
              :class="{
                'light-btn': currentAssignType == 4,
                'disabled-btn': currentFilter != 1 || searchGrade == ''
              }"
            >
              {{ $t("serviceDriveAuth['套用']") }}
            </div></i-col
          >
        </Row>
        <Row class="option-item">
          <i-col :xs="24" :sm="12" :md="12" :lg="22"
            ><p class="option-text">
              {{ $t("serviceDriveAuth['套用至']") }}
              <!-- 教室Select -->
              <Select v-model="searchClassroom" class="dark-iview-select" ref="classroom" :placeholder="selectClasses" clearable @on-clear="currentFilter = -1" @on-open-change="cleanData(2)" @on-change="filterData" :not-found-text="searchGrade ? '此年级暂无教室' : '请先选择年级'">
                <Option v-for="(item, index) in classes" :value="item.id" :key="index">{{ item.name }}</Option>
                <Option value="noclass">{{ $t("serviceDriveAuth['未关联班级']") }}</Option>
              </Select>
              {{ $t("serviceDriveAuth['所有項目']") }}
            </p></i-col
          >
          <i-col :xs="24" :sm="12" :md="12" :lg="2"
            ><div
              class="assign-btn"
              style="margin-top: 2px"
              @click="assignType(5)"
              :class="{
                'light-btn': currentAssignType == 5,
                'disabled-btn': currentFilter != 2 || searchClassroom == ''
              }"
            >
              {{ $t("serviceDriveAuth['套用']") }}
            </div></i-col
          >
        </Row>
        <Row class="option-item">
          <i-col :xs="24" :sm="12" :md="12" :lg="22"
            ><p class="option-text">{{ $t("serviceDriveAuth['套用至全校所有項目']") }} ({{ $t("serviceDriveAuth['共']") }} {{ students.length }} {{ $t("serviceDriveAuth['個']") }}，{{ students.length > totalAuth ? $t("serviceDriveAuth['大於總授權數，無法使用']") : '' }})</p></i-col
          >
          <i-col :xs="24" :sm="12" :md="12" :lg="2"
            ><div
              class="assign-btn"
              style="margin-top: -4px"
              @click="assignType(6)"
              :class="{
                'light-btn': currentAssignType == 6,
                'disabled-btn': students.length > totalAuth
              }"
            >
              {{ $t("serviceDriveAuth['套用']") }}
            </div></i-col
          >
        </Row>
        <Row>
          <i-col :xs="24" :sm="24" :md="24" :lg="24">
             <div class="bottom-border" />
            <div v-if="currentTab == 1" class="unAssign-btn" @click="isOpenRemove = true">
              {{ $t("serviceDriveAuth['收回所有授權']") }}
            </div>
            <div v-if="currentTab == 1" class="save-btn" @click="saveAuth()">
              {{ $t("serviceDriveAuth['保存所有變更']") }}
            </div></i-col
          >
        </Row>
      </div>
    </Row>
  </div>
</template>

<script>
import CountTo from 'vue-count-to'
import '@/icons/svg/close.svg'
import AuthNumChart from './AuthNumChart.vue'
import { mapGetters, mapMutations } from 'vuex'
export default {
  name: 'AclassOneAuth',
  props: ['closefromBtn', 'selected', 'students'],
  components: {
    AuthNumChart,
    CountTo
  },
  data() {
    return {
      isOpenRemove: false,
      searchPeriod: '',
      searchGrade: '',
      searchClassroom: '',
      inputSelectMin: '',
      inputSelectMax: '',
      currentTab: 0,
      clickTab: false,

      totalAuth: 0,
      usedAuth: 0,
      currentAssignType: 0, //存放目前套用的類目 0為選，1當前選中，2選中並指定長度，3學制，4學籍，5班級，6全校
      currentAssignNum: 0, //存放目前所套用所選之數量
      currentFilter: -1, //當前所選中的篩選器

      tableShowData: [],
      tableFilterData: [],
      tableColumns: [],
      basicCount: 99,
      pointNum: 0,
      pieNumData: [
        { value: 0, name: this.$t("serviceDriveAuth['固定分配授權數']") },
        { value: 0, name: this.$t("serviceDriveAuth['今日動態取用數']") },
        { value: 0, name: this.$t("serviceDriveAuth['今日可用授權數']") }
      ],

      color: ['#eb974e', '#fb62bb', '#00f492'],
      studentIds: [],
      sentParams: {
        schoolCode: '',
        studentIds: []
      },
      finalAdd: 0
    }
  },

  computed: {
    ...mapGetters({
      periods: 'user/getPeriods', // 學制s
      grades: 'user/getGrades', // 年級
      classes: 'user/getClasses', // 教室ID
      aclassOneInfoNum: 'studentAclassOneAuth/getSchoolAclassOneInfoNum'
    }),
    selectClasses: function() {
      return this.$t("serviceDriveAuth['選擇班級']")
    },
    titletext: function() {
      return this.$t("serviceDriveAuth['確定收回所有授權']")
    },
    filterGrades: function() {
      var data = this.grades
      if (this.searchPeriod) {
        let periodId = this.searchPeriod
        data = data.filter(function(item) {
          return item.periodId == periodId
        })
        return data
      } else {
        return []
      }
    },
    filterClasses: function() {
      return this.classes
      var data = this.classes
      if (this.searchGrade) {
        let gradeId = this.searchGrade
        data = data.filter(function(item) {
          return item.gradeId == gradeId
        })
        return data
      } else {
        return []
      }
    }
  },
  watch: {
    //只要勾選有變動就預設套用第一項，初始化時
    aclassOneInfoNum: function(value) {
      if (value != undefined) {
        this.totalAuth = value.total
        ;(this.usedAuth = value.staNum + value.dyncNum), (this.pieNumData[0].value = value.staNum)
        this.pieNumData[1].value = value.dyncNum
        this.pieNumData[2].value = value.total - (this.pieNumData[1].value + this.pieNumData[0].value)
      }
    },
    selected: function(value) {
      this.currentAssignType = 1

      this.currentAssignNum = this.selected.length
    }
  },
  methods: {
    ...mapMutations({
      setStudents: 'schoolBaseInfo/setStudents',
      setFirstOpenAuth: 'studentAclassOneAuth/setFirstOpenAuth'
    }),

    saveAuth() {
      if (this.currentAssignType == 0) {
        this.$Message.warning(this.$t("serviceDriveAuth['請先選擇套用，再按保存']"))
      }

      //情況1:純勾選
      if (this.currentAssignType == 1) {
        this.selected.forEach(element => {
          if (this.aclassOneInfoNum.staIds.includes(element.id) == false && this.aclassOneInfoNum.dyncIds.includes(element.id) == false) {
            this.finalAdd++
            this.studentIds.push(element.id)
          }
        })
      }

      //情況2:勾選再選目標序號
      if (this.currentAssignType == 2) {
        let chooseSelected = this.selected.slice(this.inputSelectMin - 1, this.inputSelectMax)
        chooseSelected.forEach(element => {
          if (this.aclassOneInfoNum.staIds.includes(element.id) == false && this.aclassOneInfoNum.dyncIds.includes(element.id) == false) {
            this.finalAdd++
            this.studentIds.push(element.id)
          }
        })
      }
      //情況3:選擇學段學級班級
      if (this.currentAssignType == 3 || this.currentAssignType == 4 || this.currentAssignType == 5) {
        let filterDataNow = this.tableFilterData
        //console.log(filterDataNow)
        filterDataNow.forEach(element => {
          if (this.aclassOneInfoNum.staIds.includes(element.id) == false && this.aclassOneInfoNum.dyncIds.includes(element.id) == false) {
            this.finalAdd++
            this.studentIds.push(element.id)
          }
        })
      }

      this.aclassOneInfoNum.staIds.forEach(element => {
        if (this.studentIds.includes(element) == false) {
          //記得把目前有的固定分配加回去
          this.studentIds.push(element)
        }
      })

      if (this.finalAdd <= this.aclassOneInfoNum.total - this.aclassOneInfoNum.staNum - this.aclassOneInfoNum.dyncNum) {
        this.sentParams.schoolCode = this.$store.state.user.schoolCode
        this.sentParams.studentIds = this.studentIds
        //傳給後端
        this.$store.dispatch('studentAclassOneAuth/setSchoolAclassOneState', this.sentParams)
        if (this.finalAdd == 0) {
          this.$Message.success(this.$t("serviceDriveAuth['保存成功，本次尚無新增授權數量']"))
        } else {
          this.$Message.success(this.$t("serviceDriveAuth['保存成功，本次新增']") + this.finalAdd + this.$t("serviceDriveAuth['個固定分配']"))
          //保存後重置狀態
          this.pieNumData[0].value = this.aclassOneInfoNum.total - this.aclassOneInfoNum.dyncNum
          this.pieNumData[2].value = this.aclassOneInfoNum.total - (this.pieNumData[1].value + this.pieNumData[0].value)
        }
      } else {
        this.$Message.error(this.$t("serviceDriveAuth['保存失敗，超過可用授權數！']"))
      }

      this.currentFilter = -1
      this.searchPeriod = ''
      this.searchGrade = ''
      this.searchClassroom = ''
      this.currentAssignNum = 0
      this.inputSelectMin = ''
      this.inputSelectMax = ''
      this.currentAssignType = 0
      this.studentIds = []
      this.sentParams.studentIds = []
      this.finalAdd = 0
    },
    getSchoolAclassOne(schoolCode) {
      this.$store.dispatch('studentAclassOneAuth/getSchoolAclassOne', schoolCode).then(
        res => {
          this.isloading = false
          //this.$Message.success('取得getSchoolAclassOne API資料')
        },
        err => {
          //this.$Message.error('取得getSchoolAclassOne API資料失敗')
        }
      )
    },
    resetAll() {
      this.$store.dispatch('studentAclassOneAuth/recallSchoolAclassOne', this.$store.state.user.schoolCode)
      this.$Message.success(this.$t("serviceDriveAuth['全部收回成功']"))
      this.isOpenRemove = false
    },

    assignType(type) {
      this.currentAssignType = type
      switch (type) {
        case 0:
          this.currentFilter = -1
          this.currentAssignNum = 0
          break
        case 1:
          this.currentFilter = -1
          this.searchPeriod = ''
          this.searchGrade = ''
          this.searchClassroom = ''
          if (this.selected.length == 0) {
            this.$Message.warning(this.$t("serviceDriveAuth['請先勾選欲授權之學生']"))
          }
          this.currentAssignNum = this.selected.length

          break
        case 2:
          this.currentFilter = -1
          this.searchPeriod = ''
          this.searchGrade = ''
          this.searchClassroom = ''
          if (this.selected.length == 0) {
            this.$Message.warning(this.$t("serviceDriveAuth['請先勾選欲授權之學生']"))
          }
          if (this.inputSelectMin > this.selected.length == true || this.inputSelectMax > this.selected.length == true || this.inputSelectMin > this.inputSelectMax == true || this.inputSelectMax <= 0 || this.inputSelectMax == '' || this.inputSelectMin <= 0 || this.inputSelectMin == '') {
            this.$Message.warning(this.$t("serviceDriveAuth['請設定有效的目標項 !']"))
            this.currentAssignNum = 0
          } else {
            this.currentAssignNum = parseInt(this.inputSelectMax) - (parseInt(this.inputSelectMin) - 1)
          }

          break
        case 3:
          if (this.currentFilter == 0) {
            this.currentAssignNum = this.tableFilterData.length
            if (this.tableFilterData.length == 0) {
              this.$Message.warning(this.$t("serviceDriveAuth['目前所選學制人數為 0 人！']"))
            }
          } else {
            this.$Message.warning(this.$t("serviceDriveAuth['請先選學制！']"))
            this.currentAssignNum = 0
          }
          break
        case 4:
          if (this.currentFilter == 1) {
            this.currentAssignNum = this.tableFilterData.length
            if (this.tableFilterData.length == 0) {
              this.$Message.warning(this.$t("serviceDriveAuth['目前所選學級人數為 0 人！']"))
            }
          } else {
            this.$Message.warning(this.$t("serviceDriveAuth['請先選學級！']"))
            this.currentAssignNum = 0
          }
          break
        case 5:
          if (this.currentFilter == 2) {
            this.currentAssignNum = this.tableFilterData.length
            if (this.tableFilterData.length == 0) {
              this.$Message.warning(this.$t("serviceDriveAuth['目前所選班級人數為 0 人！']"))
            }
          } else {
            this.$Message.warning(this.$t("serviceDriveAuth['請先選班級！']"))
            this.currentAssignNum = 0
          }
          break

        case 6:
          {
            this.currentFilter = -1
            this.searchPeriod = ''
            this.searchGrade = ''
            this.searchClassroom = ''
            if (this.students.length > this.totalAuth) {
              this.$Message.warning(this.$t("serviceDriveAuth['全校人數超過所購買授權數，無法使用']"))
              this.currentAssignNum = 0
            } else {
              this.currentAssignNum = this.students.length
            }
          }
          break
      }
    },
    cleanData: function(type) {
      if (type == 0) {
        this.currentFilter = 0
        this.currentAssignNum = 0
        this.currentAssignType = 0 //切換選單就跟隨所選的那一項進行套用
        this.searchGrade = ''
        this.searchClassroom = ''
      }
      if (type == 1) {
        this.currentFilter = 1
        this.currentAssignNum = 0
        this.currentAssignType = 0
        this.searchPeriod = ''
        this.searchClassroom = ''
      }
      if (type == 2) {
        this.currentFilter = 2
        this.currentAssignNum = 0
        this.currentAssignType = 0
        this.searchPeriod = ''
        this.searchGrade = ''
      }
      //只要選中選擇器，其他兩個就清空
    },
    setCurrentTab(page) {
      this.setFirstOpenAuth(false)
      this.currentTab = page
      if (this.currentTab == 0) {
        this.clickTab = true
      } else {
        this.clickTab = false
      }
    },
    close() {
      this.setFirstOpenAuth(false)
      this.clickTab = false
      this.currentAssignType = 0
      this.currentAssignNum = 0
      this.$emit('closeAuth', {
        action: 0
      })
    },
    /**根据学段、年级、班级搜索 */
    filterData: function() {
      let data = this.students

      // 筛选没有关联班级的学生
      if (this.searchClassroom == 'noclass') {
        if (this.searchClassroom) {
          let id = this.searchClassroom
          data = data.filter(function(item) {
            return item.classId == null
          })
        }

        this.tableFilterData = data
        this.pointNum = this.basicCount
        this.tableShowData = data.slice(0, this.basicCount)
        return
      }

      // 帳號資訊搜尋
      if (this.searchText) {
        let text = this.searchText
        data = data.filter(function(item) {
          return item.name.indexOf(text) >= 0 || item.id.indexOf(text) >= 0
        })
        // console.log(data);
      }

      // 學制篩選
      if (this.searchPeriod) {
        let id = this.searchPeriod
        data = data.filter(function(item) {
          return item.periodId == id
        })
      }

      // 年級篩選
      if (this.searchGrade) {
        let id = this.searchGrade
        data = data.filter(function(item) {
          return item.gradeId == id
        })
      }

      // 教室篩選
      if (this.searchClassroom) {
        let id = this.searchClassroom
        data = data.filter(function(item) {
          return item.classId == id
        })
      }

      this.tableFilterData = data
      this.pointNum = this.basicCount
      this.tableShowData = data.slice(0, this.basicCount)

      //console.log('tableFilterData')
      //console.log(this.tableFilterData)
    }
  }
}
</script>

<style lang="less">
@import './AclassOneAuth.less';

.aclassone-auth-modal {
  .ivu-modal-header {
    border-radius: 5px 5px 0px 0px !important;
  }
  .ivu-modal-footer {
    border-radius: 0px 0px 5px 5px !important;
  }

  .ivu-modal-header,
  .ivu-modal-body,
  .ivu-modal-footer {
    background-color: rgb(88, 88, 88) !important;
    color: white !important;
    border: none !important;
  }
  .ivu-btn-text {
    color: white;
    &:hover {
      background-color: transparent !important;
      color: #1cc0f3;
    }
  }
  .ivu-modal-header-inner {
    color: white !important;
    font-weight: bolder !important;
  }
}
</style>
