<template>
  <div class="space-auth" :class="{ closeShow: closefromBtn == true }">
    <!--收回授權弹窗 -->
    <Modal class="space-auth-modal" v-model="isOpenRemove" :title="popupTitleOne">
      <p>{{ $t("serviceDriveAuth['確定後全部每位教師都直接設置為0GB。']") }}</p>

      <div slot="footer">
        <Button type="text" @click="isOpenRemove = false">{{ $t("serviceDriveAuth['取消']") }}</Button>
        <Button type="primary" @click="resetAllSpace()">{{ $t("serviceDriveAuth['確定']") }}</Button>
      </div>
    </Modal>
    <!--未存關閉弹窗 -->
    <Modal class="space-auth-modal" v-model="isOpenComfirmClose" :title="popupTitleTwo">
      <p>{{ $t("serviceDriveAuth['当前空間数据尚未保存。如果關閉，修改的数据将不会保存！']") }}</p>

      <div slot="footer">
        <Button type="text" @click="isOpenComfirmClose = false">{{ $t("serviceDriveAuth['取消']") }}</Button>
        <Button type="primary" @click="closeAuth()">{{ $t("serviceDriveAuth['確定']") }}</Button>
      </div>
    </Modal>
    <div class="title">
      {{ $t("serviceDriveAuth['分配教學空間']") }}<span @click="beforeCloseAuth()"><v-icon class="close-icon" iconClass="close"/></span>
      <div class="title-btn-group">
        <div class="assign-btn" @click="isOpenRemove = true">{{ $t("serviceDriveAuth['回收空間']") }}</div>
        <div class="assign-btn" @click="confirmSave()">{{ $t("serviceDriveAuth['保存變更']") }}</div>
      </div>
    </div>
    <div id="scrollTarget" class="scroll-sprite" :style="{ height: tableHeight + 12 + 'px' }">
      <p class="small-title">{{ $t("serviceDriveAuth['空間分配狀態']") }}</p>
      <Row class="chart-view">
        <i-col :xs="24" :sm="12" :md="12" :lg="15" align="center">
          <p class="chart-title">
            {{ $t("serviceDriveAuth['總空間量']") }}<span class="chart-totalnum">{{ numberWithCommas(originalSpace) }} GB</span>
          </p>
          <SpaceStatusChart />
        </i-col>
        <i-col :xs="24" :sm="12" :md="12" :lg="9" 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">
              {{ numberWithCommas(item.value) }}
              <span class="small-text">GB</span>
            </p>
          </div>
        </i-col>
      </Row>

      <div>
        <!--目前只需要單人-->
        <div>
          <p class="controlarea-title">{{ $t("serviceDriveAuth['單人固定容量分配']") }} ({{ $t("serviceDriveAuth['目前可被分配總量']") }}：{{ maxFixedAssignedValue }} GB)</p>

          <Row class="option-item">
            <p class="option-text">
              {{ $t("serviceDriveAuth['每人分配']") }}
              <input step="1" @keydown="preventDot" type="number" placeholder="-" min="1" class="input-num" v-model="multiAssignValue" />
              GB{{ $t("serviceDriveAuth['至']") }}
            </p>
          </Row>
          <Row class="option-item">
            <i-col :xs="24" :sm="12" :md="12" :lg="16">
              <p class="option-text">{{ $t("serviceDriveAuth['當前勾選之教師帳號']") }}</p>
            </i-col>
            <i-col :xs="24" :sm="12" :md="12" :lg="8">
              <div class="assign-btn" @click="setSelectedSpace()">{{ $t("serviceDriveAuth['套用']") }}</div>
            </i-col>
          </Row>
          <Row class="option-item">
            <i-col :xs="24" :sm="12" :md="12" :lg="16">
              <p class="option-text">
                {{ $t("serviceDriveAuth['所有']") }}<span class="strong-text">{{ $t("serviceDriveAuth['進階權限']") }}</span
                >{{ $t("serviceDriveAuth['之教師帳號']") }}
              </p>
            </i-col>
            <i-col :xs="24" :sm="12" :md="12" :lg="8">
              <div class="assign-btn" @click="setAdvancedPerMissionSpace(0)">
                {{ $t("serviceDriveAuth['套用']") }}
              </div>
            </i-col>
          </Row>
          <Row class="option-item">
            <i-col :xs="24" :sm="12" :md="12" :lg="16">
              <p class="option-text">
                {{ $t("serviceDriveAuth['所有']") }}<span class="strong-text">{{ $t("serviceDriveAuth['一般權限']") }}</span
                >{{ $t("serviceDriveAuth['之教師帳號']") }}
              </p>
            </i-col>
            <i-col :xs="24" :sm="12" :md="12" :lg="8">
              <div class="assign-btn" @click="setAdvancedPerMissionSpace(1)">
                {{ $t("serviceDriveAuth['套用']") }}
              </div>
            </i-col>
          </Row>

          <Row class="option-item">
            <i-col :xs="24" :sm="12" :md="12" :lg="16">
              <p class="option-text">
                {{ $t("serviceDriveAuth['職稱為']") }}
                <Select v-model="selectJob" class="dark-iview-select">
                  <Option :value="item" v-for="(item, index) in this.jobs" :key="index">{{ item == null ? '教師' : item }}</Option></Select
                >
                {{ $t("serviceDriveAuth['的教師帳號']") }}
              </p>
            </i-col>
            <i-col :xs="24" :sm="12" :md="12" :lg="8">
              <div class="assign-btn" @click="setJobSpace()">{{ $t("serviceDriveAuth['套用']") }}</div>
            </i-col>
          </Row>
          <Row class="option-item">
            <i-col :xs="24" :sm="12" :md="12" :lg="16">
              <p class="option-text">{{ $t("serviceDriveAuth['所有教師帳號']") }}</p>
            </i-col>
            <i-col :xs="24" :sm="12" :md="12" :lg="8">
              <div class="assign-btn" @click="setAllSpace()">{{ $t("serviceDriveAuth['套用']") }}</div>
            </i-col>
          </Row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SpaceStatusChart from './SpaceStatusChart.vue'
import { mapGetters, mapMutations } from 'vuex'
import '@/icons/svg/close.svg'
import CountTo from 'vue-count-to'
import { forEach } from 'jszip'

export default {
  name: 'SpaceAuth',
  components: {
    SpaceStatusChart,
    CountTo
  },
  props: ['closefromBtn', 'tableHeight'],

  data() {
    return {
      selectJob: '教師',
      areaScrollTop: 0,
      multiAssignValue: '-',
      color: ['#eb974e', '#fb62bb', '#00f492'],
      isOpenRemove: false,
      isOpenComfirmClose: false,

      tempTeacherAssignedData: [],

      previousAdvancedNum: 0,
      previousNormalNum: 0
    }
  },
  mounted() {
    this.tempTeacherAssignedData = []
  },

  computed: {
    ...mapGetters({
      schoolCode: 'user/getLoginSchooCode', // 取得學校簡碼
      data: 'user/getSchoolUserJoined', // 取得已加入此學校的使用者
      pieNumData: 'spaceAuth/getPieNumData',
      originalSpace: 'spaceAuth/getOriginalSpace',
      teacherSpaceData: 'spaceAuth/getTeacherSpaceData',
      maxFixedAssignedValue: 'spaceAuth/getMaxFixedAssignedValue',
      isloading: 'spaceAuth/getIsLoading',
      msgNum: 'spaceAuth/getMsgNum',
      getCurrentSelectedTeacherId: 'spaceAuth/getCurrentSelectedTeacherId',
      isKeyInSpace: 'spaceAuth/getIsKeyInSpace'
    }),
    popupTitleOne: function() {
      return this.$t("serviceDriveAuth['確定收回所有空間']")
    },
    popupTitleTwo: function() {
      return this.$t("serviceDriveAuth['保存提醒']")
    },
    advancedAcountNum: function() {
      let num = 0
      this.teacherSpaceData.forEach(item => {
        if (item.permissionCount > 0) {
          num++
        }
      })
      return num
    },
    normalAcountNum: function() {
      let num = 0
      this.teacherSpaceData.forEach(item => {
        if (item.permissionCount == 0) {
          num++
        }
      })
      return num
    },
    jobs: function() {
      //撈出職稱
      let temp = []
      this.teacherSpaceData.forEach(element => {
        if (temp.includes(element.job) == false && element.job != null) {
          temp.push(element.job)
        }
      })
      temp.push('教師')
      //console.log(temp)
      return temp
    }
  },
  watch: {
    multiAssignValue: function(val) {
      //input初步過濾負數與英文
      if (val == '') {
        this.$Message.warning(this.$t("serviceDriveAuth['請手動輸入數字!']"))
        this.multiAssignValue = '-'
      }
      //輸入的數字開頭為0
      if (this.isFloat(parseFloat(val)) == false && val.length > 1 && val[0] == 0) {
        this.$Message.warning(this.$t("serviceDriveAuth['輸入了開頭為0的數字，請重新輸入!']"))
        this.multiAssignValue = '-'
      }
    },
    msgNum: function(val) {
      //等後端回傳後Loading結束才傳給使用者訊息
      if (val == 1) {
        this.$Message.success(this.$t("serviceDriveAuth['回收成功']"))

        this.setIsKeyInSpace(false)
      }
      if (val == 2) {
        this.$Message.success(this.$t("serviceDriveAuth['更新成功']"))

        this.setIsKeyInSpace(false)
      }
      if (val == 3) {
        this.$Message.warning(this.$t("serviceDriveAuth['超出該校使用空間']"))

        this.setIsKeyInSpace(false)
      }
      if (val == 4) {
        this.$Message.warning(this.$t("serviceDriveAuth['有不存在老師的ID']"))

        this.setIsKeyInSpace(false)
      }
      this.setMsgNum(0)
      this.tempTeacherAssignedData = []
    }
  },
  methods: {
    ...mapMutations({
      updatePieNumData: 'spaceAuth/updatePieNumData',
      setTeacherUsedSpaceNum: 'spaceAuth/setTeacherUsedSpaceNum',
      setTeacherSpaceUIData: 'spaceAuth/setTeacherSpaceUIData',
      setIsLoading: 'spaceAuth/setIsLoading',
      setMsgNum: 'spaceAuth/setMsgNum',
      resetTeacherSpaceUIData: 'spaceAuth/resetTeacherSpaceUIData',
      setCurrentSelectedTeacherId: 'spaceAuth/setCurrentSelectedTeacherId',
      setIsKeyInSpace: 'spaceAuth/setIsKeyInSpace'
    }),
    confirmSave() {
      this.setCurrentSentData(this.teacherSpaceData)
      //console.log(this.tempTeacherAssignedData)
      if (this.tempTeacherAssignedData.length != 0) {
        let sentParams = {
          schoolCode: this.schoolCode,
          teachers: this.teacherSpaceData
        }

        this.$store.dispatch('spaceAuth/setTeacherSpace', sentParams).then(
          res => {
            this.setIsLoading(true)
          },
          err => {
            this.$Message.error(this.$t("serviceDriveAuth['保存失敗']"))
          }
        )
      } else {
        this.$Message.warning(this.$t("serviceDriveAuth['您未進行任何個別變更或批次套用，無需保存']"))
      }
      this.tempTeacherAssignedData = [] //清空暫存
    },
    setAllSpace() {
      if (this.multiAssignValue != '-') {
        this.setIsKeyInSpace(true)
        if (this.multiAssignValue > this.maxFixedAssignedValue / this.teacherSpaceData.length) {
          this.$Message.error(this.$t("serviceDriveAuth['超出剩餘空間量，套用失敗']"))
          this.multiAssignValue = '-'
        } else {
          this.teacherSpaceData.forEach(element => {
            element.size = parseInt(this.multiAssignValue)
            let item = element
          })

          //前端先做圖表的改變，此時還沒有寫到後端
          this.setTeacherUsedSpaceNum(this.teacherSpaceData)
          this.updatePieNumData()
          this.$Message.success(this.$t("serviceDriveAuth['套用完成，記得按保存']"))
          this.multiAssignValue = '-'

          this.$emit('reload')
        }
      } else {
        this.$Message.warning(this.$t("serviceDriveAuth['先輸入有效數字，再進行套用']"))
      }
    },
    setJobSpace() {
      let jobFitNum = 0
      let unchangedUsingSpace = 0
      if (this.multiAssignValue != '-') {
        this.setIsKeyInSpace(true)
        //選擇老師
        if (this.selectJob == '教師') {
          this.teacherSpaceData.forEach(element => {
            if (element.job == null) {
              jobFitNum++
            }
          })
          this.teacherSpaceData.forEach(element => {
            if (element.job != null) {
              unchangedUsingSpace += parseInt(element.size)
            }
          })
        }
        //選擇非老師
        if (this.selectJob != '教師') {
          this.teacherSpaceData.forEach(element => {
            if (element.job == this.selectJob) {
              jobFitNum++
            }
          })
          this.teacherSpaceData.forEach(element => {
            if (element.job != this.selectJob) {
              unchangedUsingSpace += parseInt(element.size)
            }
          })
        }

        if (this.multiAssignValue * jobFitNum + unchangedUsingSpace > this.maxFixedAssignedValue) {
          this.$Message.error(this.$t("serviceDriveAuth['超出剩餘空間量，套用失敗']"))

          this.multiAssignValue = '-'
        } else {
          this.teacherSpaceData.forEach(element => {
            if (element.job == null && this.selectJob == '教師') {
              element.size = parseInt(this.multiAssignValue)
            }
            if (element.job == this.selectJob) {
              element.size = parseInt(this.multiAssignValue)
            }
          })

          //前端先做圖表的改變，此時還沒有寫到後端
          this.setTeacherUsedSpaceNum(this.teacherSpaceData)
          this.updatePieNumData()
          this.$Message.success(this.$t("serviceDriveAuth['套用完成，記得按保存']"))
          this.multiAssignValue = '-'
        }
      } else {
        this.$Message.warning(this.$t("serviceDriveAuth['先輸入有效數字，再進行套用']"))
      }
      jobFitNum = 0
      unchangedUsingSpace = 0
    },
    setSelectedSpace() {
      if (this.multiAssignValue != '-' && this.getCurrentSelectedTeacherId.length != 0) {
        let unchangedUsingSpace = 0
        this.teacherSpaceData.forEach(element => {
          if (this.getCurrentSelectedTeacherId.includes(element.id) == false) {
            unchangedUsingSpace += parseInt(element.size)
          }
        })
        console.log(unchangedUsingSpace)
        if (unchangedUsingSpace + this.multiAssignValue * this.getCurrentSelectedTeacherId.length > this.maxFixedAssignedValue) {
          this.$Message.error(this.$t("serviceDriveAuth['超出剩餘空間量，套用失敗']"))
          this.multiAssignValue = '-'
        } else {
          this.teacherSpaceData.forEach(element => {
            if (this.getCurrentSelectedTeacherId.includes(element.id)) {
              element.size = this.multiAssignValue
            }
          })

          //前端先做圖表的改變，此時還沒有寫到後端
          this.setTeacherUsedSpaceNum(this.teacherSpaceData)
          this.updatePieNumData()

          this.multiAssignValue = '-'
          this.setCurrentSelectedTeacherId([])
          this.$Message.success(this.$t("serviceDriveAuth['套用完成']"))
        }
      } else {
        this.$Message.warning(this.$t("serviceDriveAuth['先輸入有效數字，並進行勾選，再套用']"))
        this.multiAssignValue = '-'
        this.setCurrentSelectedTeacherId([])
      }
    },

    //套用權限
    setAdvancedPerMissionSpace(type) {
      if (this.multiAssignValue != '-') {
        this.setIsKeyInSpace(true)

        let previousAdvancedNum = 0
        let previousNormalNum = 0
        this.teacherSpaceData.forEach(element => {
          if (type == 0 && element.permissionCount == 0) {
            previousNormalNum += parseInt(element.size)
          } else if (type == 1 && element.permissionCount > 0) {
            previousAdvancedNum += parseInt(element.size)
          }
        })
        if (type == 0) {
          //console.log('選進階空間，要算一般空間：' + previousNormalNum)
          this.previousNormalNum = previousNormalNum
        } else {
          //console.log('選一般空間，要算進階空間：' + previousAdvancedNum)
          this.previousAdvancedNum = previousAdvancedNum
        }

        //辨識是否超過總量
        let targetNum = type == 0 ? this.advancedAcountNum : this.normalAcountNum
        let previousNum = type == 0 ? this.previousNormalNum : this.previousAdvancedNum

        //console.log(previousNum, this.multiAssignValue * targetNum, this.maxFixedAssignedValue)

        if (previousNum + this.multiAssignValue * targetNum > this.maxFixedAssignedValue) {
          this.$Message.error(this.$t("serviceDriveAuth['超出剩餘空間量，套用失敗']"))
          this.multiAssignValue = '-'
        } else {
          //辨識可以發派時的情況
          this.teacherSpaceData.forEach(element => {
            if (type == 0 ? element.permissionCount > 0 : element.permissionCount == 0) {
              element.size = parseInt(this.multiAssignValue)
            }
          })

          //前端先做圖表的改變，此時還沒有寫到後端
          this.setTeacherUsedSpaceNum(this.teacherSpaceData)
          this.updatePieNumData()
          this.multiAssignValue = '-'
          this.$Message.success(this.$t("serviceDriveAuth['套用完成']"))
        }
      } else {
        this.$Message.warning(this.$t("serviceDriveAuth['先輸入有效數字，再進行套用']"))
        this.multiAssignValue = '-'
      }
    },

    setCurrentSentData(data) {
      let tempArr = []
      data.forEach(element => {
        if (element.size != element.initSize) {
          if (element.size != '-') tempArr.push({ id: element.id, size: element.size })
          else tempArr.push({ id: element.id, size: 0 })
        }
      })
      this.tempTeacherAssignedData = tempArr
    },

    handleScroll(e) {
      // Any code to be executed when the window is scrolled
      //console.log('目前區塊捲動高度：' + e.currentTarget.scrollTop)
      this.areaScrollTop = e.currentTarget.scrollTop
    },
    numberWithCommas(x) {
      if (x != undefined) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      }
    },
    beforeCloseAuth() {
      if (this.isKeyInSpace == true) {
        this.isOpenComfirmClose = true
      } else {
        this.closeAuth()
      }
    },
    closeAuth() {
      this.tempTeacherAssignedData = [] //清空暫存
      this.$emit('closeSpaceAuth')
      this.$emit('reload') //重新整理
      this.multiAssignValue = '-'
      //如果沒有存檔則重置
      if (this.isKeyInSpace == true) {
        this.resetTeacherSpaceUIData()
        this.updatePieNumData()
      }
      this.isOpenComfirmClose = false
      this.setIsKeyInSpace(false)
    },
    //回收空間
    resetAllSpace() {
      this.$store.dispatch('spaceAuth/resetAllSpace', this.schoolCode).then(
        res => {
          this.setIsLoading(true)
        },
        err => {
          this.$Message.error(err)
        }
      )
      this.isOpenRemove = false
    },

    isFloat(n) {
      return n === +n && n !== (n | 0)
    },
    preventDot(e) {
      if (e.keyCode == 190 || e.charCode == 46) {
        //console.log(true)
        e.preventDefault()
      }
    }
  }
}
</script>

<style lang="less">
@import './SpaceAuth.less';
.space-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>
