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

<style lang="less">
.serch-inp {
  width: 100%;
  max-width: 300px;
  .ivu-input {
    font-size: 13px;
    background-color: transparent;
    border-color: #ccc;
    color: #ccc;
  }
}
.multiSet {
  &:hover {
    span {
      color: #333;
    }
  }
  .icon {
    vertical-align: middle;
    margin-right: 7px;
  }
}
.userListContent {
  .ivu-table {
    background-color: transparent;
    .ivu-table-header {
      tr:first-child {
        background: -webkit-linear-gradient(left, #272727, #222222);
        background: -o-linear-gradient(right, #272727, #222222);
        background: -moz-linear-gradient(right, #272727, #222222);
        background: linear-gradient(to right, #272727, #222222);
      }
    }
    th {
      background-color: transparent;
      border-bottom: 1px solid #343434;
      color: #757575;
      font-size: 12px;
    }
    td {
      background-color: transparent;
    }
    .ivu-table-tbody {
      td {
        background-color: transparent;
        border-bottom: 1px solid #343434;
        color: #757575;
        font-size: 12px;
      }
      .ivu-table-row {
        td:nth-child(8) {
          .ivu-table-cell {
            display: none;
          }
        }
      }
    }
    .ivu-table-row-hover {
      background: -webkit-linear-gradient(left, #272727, #373737);
      background: -o-linear-gradient(right, #272727, #373737);
      background: -moz-linear-gradient(right, #272727, #373737);
      background: linear-gradient(to right, #272727, #373737);
      td:last-child {
        .ivu-table-cell {
          display: block !important;
        }
      }
    }
    .ivu-checkbox-inner {
      background-color: transparent;
      border: 2px solid #343434;
      border-radius: 3px;
    }
    .ivu-checkbox-checked .ivu-checkbox-inner:after {
      width: 8px;
      height: 14px;
      top: -2px;
      left: 4px;
      border-color: #1eb38d;
      border-right-width: 3px;
      border-bottom-width: 3px;
    }
    .ivu-table-overflowY {
      &::-webkit-scrollbar {
        width: 5px;
      }
      &::-webkit-scrollbar-track {
        // margin: 0px;
        background: transparent;
      }
      &::-webkit-scrollbar-thumb {
        border-radius: 10px;
        background: #94998a;
      }
      &::-webkit-scrollbar-thumb:hover {
        /* background: #555; */
      }
      &::-webkit-scrollbar-button {
        display: none;
      }
    }
  }
}
.authSetting {
  .ivu-btn {
    background-color: #1cc0f2;
    color: #fff;
    border-radius: 2px;
    border: 0;
  }
  .users {
    .jobInp {
      .ivu-input {
        background-color: transparent;
        border: 0;
        border-bottom: 1px solid #6b6a6a;
        padding-left: 0;
        color: #fefefe;
      }
    }
  }
}
.ids {
  .ivu-tooltip-inner {
    opacity: 0.5;
    background: rgba(100, 100, 100, 0.2);
    border: 1px rgba(160, 160, 160, 0.5) solid;
  }
  .ivu-tooltip-popper[x-placement^='bottom'] .ivu-tooltip-arrow {
    border-bottom-color: rgba(0, 0, 0, 0);
  }
  .userSelected {
    margin-right: 7px;
    display: inline-block;
    .ivu-tooltip-rel {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      width: 70px;
      text-align: center;
    }
    .userSelectedTooltipName {
      font-size: large;
      font-weight: bold;
      color: #fff;
    }
    .userSelectedTooltipContent {
      color: #aaa;
    }
    .usericon {
      display: inline-block;
      margin-right: 7px;
      width: 36px;
      border-radius: 50%;
      overflow: hidden;
      vertical-align: middle;
    }
  }
}
.jobModal {
  .ivu-modal {
    .ivu-modal-content {
      background-color: #2a292e;
      .ivu-modal-header,
      .ivu-modal-footer {
        border: 0;
      }
      .ivu-modal-header {
        padding: 5px 16px;
      }
      .jobModal-body {
        padding: 5px 12px;
        .name-box {
          display: flex;
          align-items: center;
          height: 50px;
          .name {
            text-align: left;
            width: 100%;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            color: #e8eaec;
          }
        }
        .content {
          display: block;
          height: 66px;
          width: 100%;
          color: #999;
          font-size: 10px;
        }
        .ivu-input {
          background-color: transparent;
          border: 0;
          border-bottom: 1px solid #6b6a6a;
          padding-left: 0;
          color: #fefefe;
          margin-bottom: 50px;
          border-radius: 0%;
        }
        .ivu-btn {
          background-color: #1cc0f2;
          color: white;
          border-radius: 0;
          border: 0;
        }
      }
    }
  }
}
</style>

<template>
  <div class="userList">
    <Loading v-if="isloading == true"></Loading>
    <!-- 使用者列表 -->
    <div class="userLists" :class="{ isSetting: authMulti || isOpenSpaceAuth == true }">
      <div class="serch-box">
        <Input class="serch-inp" suffix="ios-search" :placeholder="$t('teachermgmt.blurryFilter')" v-model="blurryFilter" />
        <Button class="multiSet" type="text" @click="openSpaceAuth()" v-if="!authMulti && isOpenSpaceAuth == false"><Icon class="share-icon" type="md-share" />&nbsp;{{ $t("serviceDriveAuth['分配教學空間']") }}</Button>
        <Button v-if="!authMulti && isOpenSpaceAuth == false" class="multiSet" type="text" @click="multiSet()"><icon class="icon" icon="shield-alt" /> {{ $t('teachermgmt.mulitSet') }}</Button>
      </div>
      <div class="userListContent">
        <Table v-if="isMockReloadAlive" class="scrollstyle" :height="tableHeight" ref="selection" :columns="tableColumns" :data="tableData" @on-selection-change="setTeachers" @on-sort-change="changeSort">
          <template slot-scope="{ row }" slot="picture">
            <PersonalPhoto :name="row.name" :picture="row.picture" />
          </template>
          <template slot-scope="{ row }" slot="action" v-if="isOpenSpaceAuth == false">
            <icon icon="shield-alt" style="font-size: 14px; color: #fff; margin-right: 20px; cursor: pointer;" @click="showAuth(row)" />
            <icon icon="trash" style="color: #fff; font-size: 14px; cursor: pointer" @click="removeUser(row)" />
          </template>
          <!---手動輸入空間欄位-->
          <template slot-scope="{ row }" slot="spaceShare" v-if="isOpenSpaceAuth == true"> <input class="input-num" type="number" @keydown="preventDot" @change="setSingleMockTeacherSpace(row.id)" @input="setSingleMockTeacherSpace(row.id)" min="0" placeholder="-" v-model="teacherSpaceData[findIndex(row.id)].size" /> GB </template>
        </Table>
      </div>
    </div>
    <!--空間分配組件 -->
    <SpaceAuth :style="{ height: this.tableHeight + 58 + 'px', right: isOpenSpaceAuth == true ? '0%' : '-30%', animation: isOpenSpaceAuth == true ? 'spaceAuthSlideIn 0.7s' : 'none' }" :closefromBtn="closefromBtn" :tableHeight="tableHeight" @closeSpaceAuth="closeSpaceAuth" @reload="reload" />
    <!-- 權限設定 -->
    <div class="authSetting" :class="{ isSetting: authMulti }">
      <div class="header">
        <span class="title">{{ $t('teachermgmt.authSet.title') }}</span>
        <div class="ctrlList">
          <Button class="btn" size="small" @click="clearAuth()">{{ $t('teachermgmt.authSet.reset') }}</Button>
          <Button class="btn" :class="{ 'ivu-disabled': !isAuthChanged && !isJobTitleChg }" size="small" @click="checkJobtitleChanged()" :disabled="!isAuthChanged && !isJobTitleChg">{{ $t('teachermgmt.authSet.save') }}</Button>
          <Icon class="icon" size="26" color="#ffffff" type="md-close" @click="closeAuthSeting()" />
        </div>
      </div>
      <div class="users">
        <div class="title">
          {{ $t('teachermgmt.authSet.subTitle') }}
        </div>
        <div class="ids scrollstyle" :class="{ singleMode: !multiSetMode }">
          <tooltip class="userSelected" v-for="(id, key) in ids" :key="key" placement="bottom-start" offset="10">
            <div slot="content" class="userSelectedTooltip">
              <span class="userSelectedTooltipName">{{ id.name }}</span
              ><br /><span class="userSelectedTooltipContent">{{ id.id }}</span>
            </div>

            <PersonalPhoto :name="id.name" :picture="id.picture" :color="id.nameColor" />
            <!-- <img class="usericon" :src="id.picture" /> -->
            <span class="usercontent" v-if="ids.length === 1">{{ id.name }}</span>
          </tooltip>
        </div>
        <!-- 職稱 -->
        <div v-show="!multiSetMode">
          <div class="title" style="height: 25px; line-height: 25px">
            {{ $t('teachermgmt.job.jobTitle') }}
          </div>
          <div class="jobInp">
            <Input :placeholder="$t('teachermgmt.job.teacher')" v-model="jobTitle" />
          </div>
        </div>
      </div>
      <!-- 權限列表 -->
      <div class="authContent scrollstyle">
        <div class="authBox" v-for="(authMain, rootkey) in authListAll" :key="rootkey">
          <div class="title">{{ $t('teachermgmt.authority.' + rootkey) }}</div>
          <div class="subTitle">
            <span>{{ $t('teachermgmt.authority.' + authMain.rowKey) }}</span>
            <span v-if="multiSetMode" class="checkSty">
              <div>
                <label class="checkTitle">{{ $t('teachermgmt.authSet.on') }}</label>
                <Checkbox
                  true-value="1"
                  false-value="0"
                  v-model="authstatusMulti['on'][authMain.rowKey]"
                  @on-change="
                    multiCheckPermissionPickOne($event, authMain.rowKey, 'on')
                    multiCheckDisable($event, authMain.rowKey, '', rootkey, 'on', 'parent')
                  "
                ></Checkbox>
              </div>
              <div>
                <label class="checkTitle">{{ $t('teachermgmt.authSet.off') }}</label>
                <Checkbox
                  true-value="1"
                  false-value="0"
                  v-model="authstatusMulti['off'][authMain.rowKey]"
                  @on-change="
                    multiCheckPermissionPickOne($event, authMain.rowKey, 'off')
                    multiCheckDisable($event, authMain.rowKey, '', rootkey, 'off', 'parent')
                  "
                ></Checkbox>
              </div>
            </span>
            <span v-else>
              <i-switch v-model="authstatus[authMain.rowKey]" :true-color="switchTrueColor" :false-color="switchFalseColor" class="switch" @on-change="singleCheckPermission($event, rootkey)" />
            </span>
          </div>
          <div class="detail" v-for="(authSub, subkey) in authMain.subitem" :key="subkey">
            <span class="auth">{{ $t('teachermgmt.authority.' + subkey) }}</span>
            <span v-if="multiSetMode" class="checkSty">
              <div>
                <label class="checkTitle">{{ $t('teachermgmt.authSet.on') }}</label>
                <Checkbox
                  true-value="1"
                  false-value="0"
                  v-model="authstatusMulti['on'][subkey]"
                  :disabled="authdisableMulti[rootkey]"
                  @on-change="
                    multiCheckPermissionPickOne($event, subkey, 'on')
                    multiCheckDisable($event, subkey, authMain.rowKey, rootkey, 'on', 'child')
                  "
                ></Checkbox>
              </div>
              <div>
                <label class="checkTitle">{{ $t('teachermgmt.authSet.off') }}</label>
                <Checkbox
                  true-value="1"
                  false-value="0"
                  v-model="authstatusMulti['off'][subkey]"
                  :disabled="authdisableMulti[rootkey]"
                  @on-change="
                    multiCheckPermissionPickOne($event, subkey, 'off')
                    multiCheckDisable($event, subkey, authMain.rowKey, rootkey, 'off', 'child')
                  "
                ></Checkbox>
              </div>
            </span>
            <span v-else>
              <i-switch v-model="authstatus[subkey]" :disabled="authdisableComputed[rootkey] ? !authdisableComputed[rootkey] : true" :true-color="switchTrueColor" :false-color="switchFalseColor" class="switch" />
            </span>
          </div>
        </div>
      </div>
    </div>
    <!-- 提示視窗 -->
    <Modal v-model="jobModal" width="360" :mask-closable="false" class-name="jobModal">
      <p slot="header"></p>
      <div class="jobModal-body">
        <div class="name-box" v-for="(id, key) in ids" :key="key">
          <PersonalPhoto :name="id.name" :picture="id.picture" style="margin-right: 7px" />
          <span class="name">{{ id.name }}</span>
        </div>
        <span class="content">{{ $t('teachermgmt.modal.text1') }}</span>
        <span style="font-size: 10px">{{ $t('teachermgmt.job.jobTitle') }}</span>
        <Input :placeholder="$t('teachermgmt.job.teacher')" v-model="jobTitle" />
        <Button size="large" long @click="setSchoolUserPermission()">{{ $t('teachermgmt.modal.text2') }}</Button>
      </div>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
import apiTools from '@/api'
import PersonalPhoto from '@/components/public/personalPhoto/Index.vue'
import SpaceAuth from './SubComponent/SpaceAuth.vue'
import { forEach } from 'jszip'
import EventLatestVue from '../../../../components/student-web/EventView/EventOverView/EventLatest.vue'
import Loading from '@/common/Loading.vue'

export default {
  name: 'userList',
  data() {
    return {
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: ' ',
          width: 80,
          slot: 'picture',
          // key: 'picture',
          align: 'center'
          // render: (h, params) => {
          //     return h('img', {
          //         attrs: {
          //             src: params.row.picture
          //         },
          //         style: {
          //             display: 'inline-block',
          //             width: '36px',
          //             'border-radius': '50%',
          //             'align-items': 'center',
          //             'justify-content': 'center',
          //             'overflow': 'hidden'
          //         }
          //     })
          // }
        },
        {
          title: this.$t('teachermgmt.table.th1'),
          width: 230,
          key: 'id',
          sortable: true
        },
        {
          title: this.$t('teachermgmt.table.th2'),
          key: 'name',
          sortable: true
        },
        {
          title: this.$t('teachermgmt.table.th3'),
          width: 300,
          key: 'job',
          sortable: true,
          render: (h, params) => {
            if (typeof params.row.job === 'undefined' || params.row.job == null || params.row.job === '') {
              return h('span', this.$t('teachermgmt.job.teacher'))
            } else {
              return h('span', params.row.job)
            }
          }
        },
        {
          title: this.$t('teachermgmt.table.th4'),
          sortable: true,
          show: true,
          width: 260,
          render: (h, params) => {
            if (params.row.permissionCount > 0) {
              return h(
                'span',
                {
                  style: {
                    color: '#1CC0F3'
                  }
                },
                this.$t('teachermgmt.table.text2')
              )
            } else {
              return h('span', this.$t('teachermgmt.table.text1'))
            }
          }
        },
        {
          title: ' ',
          slot: 'action',
          width: 200,
          align: 'center'
          // show: true
        }
      ],
      authMulti: false,
      blurryFilter: '',
      tableHeight: 100,
      screenHeight: document.documentElement.clientHeight, // 螢幕高度
      ids: [], // 操作中的ID列表
      multiSetMode: false, // 多筆設定
      teachers: [],
      switchTrueColor: '#1cc0f2',
      switchFalseColor: '#4e4d4d',
      authSelected: [], // 選取的權限
      userSelected: undefined, // 被選取的使用者資訊(單人) [object]
      authdisableMulti: {}, // 複數老師權限開關控制disable資料
      jobTitle: null,
      isAuthChanged: false,
      isJobTitleChg: false,
      jobModal: false,

      //Louise SpaceAuth 空間分配組件使用參數
      isOpenSpaceAuth: false,
      closefromBtn: false,
      isMockReloadAlive: true
    }
  },
  computed: {
    ...mapGetters({
      schoolCode: 'user/getLoginSchooCode', // 取得學校簡碼
      data: 'user/getSchoolUserJoined', // 取得已加入此學校的使用者
      authData: 'user/getschoolSettingAuthList', // 製作老師(單數)權限設定值及disable控制表
      authstatus: 'user/getTeacherAuthStatus', //製作老師(單數)權限設定值列表
      authstatusMulti: 'user/getTeacherAuthStatusMulti', //製作老師(複數)權限設定值列表
      teacherSpaceData: 'spaceAuth/getTeacherSpaceData',
      isloading: 'spaceAuth/getIsLoading',
      isKeyInSpace: 'spaceAuth/getIsKeyInSpace',
      maxFixedAssignedValue: 'spaceAuth/getMaxFixedAssignedValue'
    }),
    authListAll: function() {
      // 所有權限列表(階層構造)
      console.log('auth', this.authData.authListFormed)
      return this.authData.authListFormed
    },
    authdisable: {
      // (i-switch用)權限開關控制disable資料
      get() {
        return this.authData.authDisable
      },
      set(newAuthdisable) {
        return newAuthdisable
      }
    },
    //authstatus: function() { // (i-switch用)權限開關控制value資料
    //    return this.authData.authStatus
    //},
    authIdToPath: function() {
      // 權限ID <=> 權限路徑 對照表
      return this.authData.authIdToPath
    },
    randomColor: function() {
      let r = Math.floor(Math.random() * 255)
      let g = Math.floor(Math.random() * 255)
      let b = Math.floor(Math.random() * 255)
      return 'rgba(' + r + ',' + g + ',' + b + ',0.8)'
    },
    rectifyData: function() {
      let temp = this.data
      let _this = this
      temp.forEach(function(item) {
        item.nameColor = _this.randomColor
      })

      return temp
    },
    tableData: function() {
      let filterData = this.rectifyData
      if (this.blurryFilter) {
        // 可以客制調整
        filterData = this.data.filter(res => {
          let a = res.name.toLowerCase()
          let b = res.id.toLowerCase()
          return a.indexOf(this.blurryFilter) >= 0 || b.indexOf(this.blurryFilter) >= 0
        })
      }

      return filterData
    },
    tableColumns: function() {
      let column = []
      this.columns.forEach(res => {
        if (res.show) {
          if (!this.authMulti) {
            column.push(res)
          }
        } else {
          column.push(res)
        }
      })
      return column
    },
    authdisableComputed: function() {
      return this.authdisable
    }
  },

  watch: {
    tableData: function() {
      this.data.forEach(element => {
        Object.defineProperty(element, 'initSize', {
          value: element.size,
          writable: true
        })
      })
    },
    screenHeight: function(val) {
      this.tableHeight = val - this.$refs.selection.$el.offsetTop - 133
    },
    authData: {
      immediate: true,
      handler(val) {},
      deep: true
    },

    authstatus: {
      immediate: true,
      handler(newVal) {
        let org_authstatus = sessionStorage.getItem('authstatus')
        org_authstatus = JSON.parse(org_authstatus)

        if (this.authMulti && !this.multiSetMode && !this.$tools.isEqual(org_authstatus, newVal)) {
          this.isAuthChanged = true
        } else {
          this.isAuthChanged = false
        }
      },
      deep: true
    },
    authstatusMulti: {
      immediate: true,
      handler(newval) {
        let org_authstatusMulti = sessionStorage.getItem('authstatusMulti')

        if (!this.authMulti || !this.multiSetMode || typeof newval === 'undefined' || org_authstatusMulti === 'undefined') {
          this.isAuthChanged = false
        } else {
          org_authstatusMulti = JSON.parse(org_authstatusMulti)
          let equal_on = this.$tools.isEqual(org_authstatusMulti['on'], newval['on'])
          let equal_off = this.$tools.isEqual(org_authstatusMulti['off'], newval['off'])
          if (!equal_on || !equal_off) {
            this.isAuthChanged = true
          } else {
            this.isAuthChanged = false
          }
        }
      },
      deep: true
    },
    authdisableMulti: {
      handler(val) {},
      deep: true
    },
    jobTitle: {
      immediate: true,
      handler(val) {
        let orgjobtitle = sessionStorage.getItem('jobTitle')
        orgjobtitle = JSON.parse(orgjobtitle)

        if (this.authMulti && !this.multiSetMode && val != orgjobtitle) {
          this.isJobTitleChg = true
        } else {
          this.isJobTitleChg = false
        }
      },
      deep: true
    },
    isOpenSpaceAuth: function(val) {
      if (val == true) {
        this.columns = [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: ' ',
            width: 80,
            slot: 'picture',
            align: 'center'
          },
          {
            title: this.$t('teachermgmt.table.th1'),
            width: 160,
            key: 'id',
            sortable: true
          },
          {
            title: this.$t('teachermgmt.table.th2'),
            key: 'name',
            sortable: true
          },
          {
            title: this.$t('teachermgmt.table.th3'),
           
            key: 'job',
            sortable: true,
            render: (h, params) => {
              if (typeof params.row.job === 'undefined' || params.row.job == null || params.row.job === '') {
                return h('span', this.$t('teachermgmt.job.teacher'))
              } else {
                return h('span', params.row.job)
              }
            }
          },
          {
            title: this.$t('teachermgmt.table.th4'),
            sortable: true,

            show: true,
           
            render: (h, params) => {
              if (params.row.permissionCount > 0) {
                return h(
                  'span',
                  {
                    style: {
                      color: '#1CC0F3'
                    }
                  },
                  this.$t('teachermgmt.table.text2')
                )
              } else {
                return h('span', this.$t('teachermgmt.table.text1'))
              }
            }
          },
          {
            title: this.$t("serviceDriveAuth['空間分配']"),
            width: 250,
            slot: 'spaceShare',
            align: 'center'
          }
        ]
      } else {
        this.columns = [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: ' ',
            width: 80,
            slot: 'picture',
            // key: 'picture',
            align: 'center'
            // render: (h, params) => {
            //     return h('img', {
            //         attrs: {
            //             src: params.row.picture
            //         },
            //         style: {
            //             display: 'inline-block',
            //             width: '36px',
            //             'border-radius': '50%',
            //             'align-items': 'center',
            //             'justify-content': 'center',
            //             'overflow': 'hidden'
            //         }
            //     })
            // }
          },
          {
            title: this.$t('teachermgmt.table.th1'),
            width: 230,
            key: 'id',
            sortable: true
          },
          {
            title: this.$t('teachermgmt.table.th2'),
            key: 'name',
            sortable: true
          },
          {
            title: this.$t('teachermgmt.table.th3'),
            width: 300,
            key: 'job',
            sortable: true,
            render: (h, params) => {
              if (typeof params.row.job === 'undefined' || params.row.job == null || params.row.job === '') {
                return h('span', this.$t('teachermgmt.job.teacher'))
              } else {
                return h('span', params.row.job)
              }
            }
          },
          {
            title: this.$t('teachermgmt.table.th4'),
            sortable: true,
            show: true,
            width: 260,
            render: (h, params) => {
              if (params.row.permissionCount > 0) {
                return h(
                  'span',
                  {
                    style: {
                      color: '#1CC0F3'
                    }
                  },
                  this.$t('teachermgmt.table.text2')
                )
              } else {
                return h('span', this.$t('teachermgmt.table.text1'))
              }
            }
          },
          {
            title: ' ',
            slot: 'action',
            width: 200,
            align: 'center'
            // show: true
          }
        ]
      }
    }
  },
  methods: {
    showAuth: function(val) {
      // 個人設定
      this.ids = []
      this.ids.push({
        id: val.id,
        name: val.name,
        picture: val.picture,
        job: val.job,
        nameColor: val.nameColor
      })
      let selectUserList = this.$store.getters['user/getSchoolUserByID'](val.id)
      if (selectUserList.length > 0) {
        this.userSelected = selectUserList[0]
      }

      this.jobTitle = val.job
      sessionStorage.setItem('jobTitle', JSON.stringify(val.job))
      // 取得該老師權限
      apiTools.schoolUser
        .getPermissionByIdToken({
          school_code: this.schoolCode,
          id: val.id
        })
        .then(res => {
          if (typeof res.permissions !== 'undefined') {
            let permissions = res.permissions
            // 用既有權限變更前端
            // 開關控制
            let authRootDisableInfo = {}
            for (var authStatusId of Object.keys(this.authstatus)) {
              if (permissions.indexOf(authStatusId) > -1) {
                this.authstatus[authStatusId] = true
                if (typeof this.authIdToPath[authStatusId] !== 'undefined') {
                  authRootDisableInfo[this.authIdToPath[authStatusId]] = true
                  this.singleCheckPermission(true, this.authIdToPath[authStatusId])
                }
              } else {
                this.authstatus[authStatusId] = false
              }
            }

            // daisble控制
            for (var authDisableId of Object.keys(this.authdisable)) {
              if (typeof authRootDisableInfo[authDisableId] !== 'undefined') {
                this.singleCheckPermission(true, authDisableId)
              } else {
                this.singleCheckPermission(false, authDisableId)
              }
            }

            sessionStorage.setItem('authstatus', JSON.stringify(this.authstatus))
          }
        })
      this.authMulti = true // 調整位置讓保存變更的按鈕判斷正確
      this.multiSetMode = false // 關閉多筆設定
    },
    removeUser: function(val) {
      // val:使用者的資料(object)
      this.$Modal.confirm({
        title: this.$t('teachermgmt.model.delTeacher.title'),
        content: '<p>' + this.$t('teachermgmt.model.delTeacher.text1') + ' ' + val.name + '(' + val.id + ') ?</p>',
        onOk: () => {
          // this.$store.dispatch('user/rmvFromSchoolUserByID', { Ids: [val.id] }).then(  //参数不正确API报错
          this.$store.dispatch('user/rmvFromSchoolUserByID', { id: val.id }).then(
            res => {
              if (res.code === 1) {
                this.$Message.info(this.$t('teachermgmt.message.info1'))
              } else {
                this.$Message.error('Can not set Auth.')
              }
            },
            err => {
              this.$Message.error('user/setSchoolUser API error: ' + err)
            }
          )
        }
        // onCancel: () => {
        //     this.$Message.info('Clicked cancel');
        // }
      })
    },
    multiSet: function() {
      // 多人設定
      if (this.teachers.length > 0) {
        this.authMulti = true
        this.multiSetMode = true
        this.teachers.forEach(res => {
          this.ids.push({
            id: res.id,
            name: res.name,
            picture: res.picture,
            job: res.job
          })
        })
        sessionStorage.setItem('authstatusMulti', JSON.stringify(this.authstatusMulti))
      } else {
        this.$Modal.warning({
          title: this.$t('teachermgmt.model.warning.title'),
          content: this.$t('teachermgmt.model.warning.text1')
        })
      }
    },
    setTeachers: function(val) {
      // 多選暫存
      this.teachers = val

      // 給發派空間使用勾選的id
      console.log('勾選的老師')
      console.log(this.teachers)
      let teachersIdArray = []
      this.teachers.forEach(element => {
        teachersIdArray.push(element.id)
      })
      this.setCurrentSelectedTeacherId(teachersIdArray)
    },
    closeAuthSeting: function() {
      this.multiSetMode = false
      this.authMulti = false
      this.ids = []
      this.authSelected = []
      this.$store.dispatch('user/resetAuthStatusMulti')
    },
    // ASC 代表結果會以由小往大的順序列出，而 DESC 代表結果會以由大往小的順序列出。
    changeSort({ column, key, order }) {
      if (column.slot === 'mobile' || column.slot === 'email' || column.slot === 'loginStatus') {
        this.data.sort(function(a, b) {
          let nameA = a[column.slot]
          let nameB = b[column.slot]
          if (column.slot === 'mobile' || column.slot === 'email') {
            nameA = a[column.slot] ? 1 : 0
            nameB = b[column.slot] ? 1 : 0
          }
          switch (order) {
            case 'asc':
              return nameA - nameB
            case 'desc':
              return nameB - nameA
          }
        })
      }
    },
    // 權限賦予
    setSchoolUserPermission() {
      //取得ID List
      let idSelected = []
      if (this.ids.length > 0) {
        for (let idInfo of this.ids) {
          idSelected.push(idInfo.id)
        }
      }
      // 加選/移除權限List製作
      let mode = this.multiSetMode ? 'multi' : 'single' //模式  'single':只看add視為ON、其餘均認為OFF      'multi':add有者ON、rmv有者OFF、其餘不操作
      let permissions = { add: [], rmv: [] }
      // 父若未勾選，子勾選不算
      for (let authId of Object.keys(this.authListAll)) {
        let authstatusId = this.authListAll[authId].rowKey
        if (this.multiSetMode) {
          // 多筆設定
          if (typeof this.authstatusMulti['on'][authstatusId] !== 'undefined' && this.authstatusMulti['on'][authstatusId] === '1') {
            // 父開啟 => 子自由操作
            permissions['add'].push(authstatusId)
            if (typeof this.authListAll[authId].subitem !== 'undefined') {
              for (var subitemId of Object.keys(this.authListAll[authId].subitem)) {
                let authstatusSubitemId = this.authListAll[authId].subitem[subitemId].rowKey
                if (typeof this.authstatusMulti['on'][authstatusSubitemId] !== 'undefined' && this.authstatusMulti['on'][authstatusSubitemId] === '1') {
                  permissions['add'].push(authstatusSubitemId)
                } else if (typeof this.authstatusMulti['off'][authstatusSubitemId] !== 'undefined' && this.authstatusMulti['off'][authstatusSubitemId] === '1') {
                  permissions['rmv'].push(authstatusSubitemId)
                }
              }
            }
          } else if (typeof this.authstatusMulti['off'][authstatusId] !== 'undefined' && this.authstatusMulti['off'][authstatusId] === '1') {
            // 父關閉 => 子強制關閉
            permissions['rmv'].push(authstatusId)
            if (typeof this.authListAll[authId].subitem !== 'undefined') {
              for (var subitemId of Object.keys(this.authListAll[authId].subitem)) {
                let authstatusSubitemId = this.authListAll[authId].subitem[subitemId].rowKey
                permissions['rmv'].push(authstatusSubitemId)
              }
            }
          }
        } else {
          // 單人設定
          if (this.authstatus[authstatusId]) {
            permissions['add'].push(authstatusId)
            if (typeof this.authListAll[authId].subitem !== 'undefined') {
              for (var subitemId of Object.keys(this.authListAll[authId].subitem)) {
                let authstatusSubitemId = this.authListAll[authId].subitem[subitemId].rowKey
                if (this.authstatus[authstatusSubitemId]) {
                  permissions['add'].push(authstatusSubitemId)
                }
              }
            }
          }
        }
      }
      //職稱設定(單人才有)
      let job = !this.multiSetMode ? this.jobTitle : null

      // DB寫入
      if (idSelected.length > 0) {
        this.$store
          .dispatch('user/setSchoolUserPermission', {
            ids: idSelected,
            pmAdd: permissions['add'],
            pmRmv: permissions['rmv'],
            job: job,
            mode: mode
          })
          .then(
            res => {
              if (!this.multiSetMode) {
                //單人=>更新前端個人職稱
                let idUpd = idSelected[0]
                this.$store.dispatch('user/updSchoolUserInfo', {
                  id: idUpd,
                  param: { job: job }
                })
              }
              this.$Message.info(this.$t('teachermgmt.message.info4'))
              this.closeAuthSeting()
            },
            err => {
              this.$Message.error('user/setSchoolUser API error: ' + err)
            }
          )
      } else {
        this.$Modal.warning({
          title: this.$t('teachermgmt.model.warning.title'),
          content: this.$t('teachermgmt.model.warning.text1')
        })
      }

      this.jobModal = false
      this.jobTitle = null
    },
    // 單人權限設置 點選後動做
    singleCheckPermission(event, rootkey) {
      let authdisableDummy = this.authdisable
      authdisableDummy[rootkey] = event
      // this.authdisable = {};
      this.authdisable = authdisableDummy
    },
    // 多人權限設置 開啟、關閉 擇一勾選
    multiCheckPermissionPickOne: function(value, key, status) {
      //開啟、關閉 擇一勾選
      if (status === 'on' && value === '1') {
        this.authstatusMulti['off'][key] = '0'
      } else if (status === 'off' && value === '1') {
        this.authstatusMulti['on'][key] = '0'
      }
    },
    // 多人權限設置 父子diable控制
    multiCheckDisable: function(value, key, parentKey, rootkey, status, role) {
      if (role === 'parent' && value === '0') {
        //父不選 => 子不選 && disable移除
        this.authdisableMulti[rootkey] = false
        if (typeof this.authListAll[rootkey].subitem !== 'undefined') {
          for (var subitemId of Object.keys(this.authListAll[rootkey].subitem)) {
            let authstatusSubitemId = this.authListAll[rootkey].subitem[subitemId].rowKey
            this.authstatusMulti['on'][authstatusSubitemId] = '0'
            this.authstatusMulti['off'][authstatusSubitemId] = '0'
          }
        }
      } else if (role === 'parent' && status === 'off' && value === '1') {
        //父關閉 => 子關閉 && disable
        this.authdisableMulti[rootkey] = true
        if (typeof this.authListAll[rootkey].subitem !== 'undefined') {
          for (var subitemId of Object.keys(this.authListAll[rootkey].subitem)) {
            let authstatusSubitemId = this.authListAll[rootkey].subitem[subitemId].rowKey
            this.authstatusMulti['on'][authstatusSubitemId] = '0'
            this.authstatusMulti['off'][authstatusSubitemId] = '1'
          }
        }
      } else if (role === 'parent' && status === 'on' && value === '1') {
        //父開啟 => 子 disable移除
        this.authdisableMulti[rootkey] = false
      } else if (role === 'child' && status === 'on' && value === '1') {
        //子開啟 => 父自動勾選
        this.authstatusMulti['on'][parentKey] = '1'
        this.authstatusMulti['off'][parentKey] = '0'
      }
    },
    // 清除權限
    clearAuth: function() {
      if (this.multiSetMode) {
        // 多筆設定
        for (let a in this.authstatusMulti['on']) {
          this.authstatusMulti['on'][a] = '0'
        }
        for (let b in this.authstatusMulti['off']) {
          this.authstatusMulti['off'][b] = '0'
        }
      } // 單人設定
      else {
        for (let a in this.authstatus) {
          this.authstatus[a] = false
        }

        for (let b in this.authdisableComputed) {
          this.authdisableComputed[b] = false
        }
      }
    },
    checkJobtitleChanged: function() {
      let basicJobTitle = this.$t('teachermgmt.job.teacher')

      if (this.isAuthChanged && !this.isJobTitleChg && !this.multiSetMode) {
        this.jobModal = true
      } else {
        this.setSchoolUserPermission()
      }
    },
    ...mapMutations({
      setTeacherSpaceUIData: 'spaceAuth/setTeacherSpaceUIData',
      setIsLoading: 'spaceAuth/setIsLoading',
      setCurrentSelectedTeacherId: 'spaceAuth/setCurrentSelectedTeacherId',
      updatePieNumData: 'spaceAuth/updatePieNumData',
      setTeacherUsedSpaceNum: 'spaceAuth/setTeacherUsedSpaceNum',
      setIsKeyInSpace: 'spaceAuth/setIsKeyInSpace'
    }),
    //打開空間管理
    openSpaceAuth() {
      this.setIsLoading(true)
      setTimeout(() => {
        this.isOpenSpaceAuth = true
        let params = {
          schoolCode: this.schoolCode,
          originalTeachers: this.data
        }
        //讀取初始值
        this.getInitialSpace(params)
        this.setTeacherSpaceUIData(this.data)
      }, 2000)

      this.closefromBtn = false
    },
    //關閉空間管理
    closeSpaceAuth() {
      this.isOpenSpaceAuth = false
      this.closefromBtn = true
    },

    reload() {
      this.isMockReloadAlive = false
      this.$nextTick(function() {
        this.isMockReloadAlive = true
      })
    },
    setSingleMockTeacherSpace(id) {
      this.setIsKeyInSpace(true)
      let targetSpace = this.teacherSpaceData[this.findIndex(id)].size
      //console.log('調整ID空間為' + id + ':' + targetSpace + 'G')

      //input初步過濾負數與英文
      if (targetSpace == '') {
        this.$Message.warning('請手動輸入數字!')
        this.teacherSpaceData[this.findIndex(id)].size = '-'
        this.reload()
      }
      //輸入大於剩餘值
      let totalNow = 0
      this.teacherSpaceData.forEach(element => {
        if(element.size!='-')
        totalNow += parseInt(element.size)
        else{
          totalNow +=0
        }
      })
      totalNow = totalNow - parseInt(targetSpace)

      if (parseInt(targetSpace) > this.maxFixedAssignedValue - totalNow) {
        this.$Message.warning('超出剩餘可分配空間，請重新輸入!')
        this.teacherSpaceData[this.findIndex(id)].size ='-'
        this.reload()
      }

      //輸入的數字開頭為0
       if (this.isFloat(parseFloat(targetSpace)) == false && targetSpace.length > 1 && targetSpace[0] == 0) {
        this.$Message.warning('輸入了開頭為0的數字')
          this.teacherSpaceData[this.findIndex(id)].size = '-'
        this.reload()
      }


      //前端先做圖表的改變，此時還沒有寫到後端
      this.setTeacherUsedSpaceNum(this.teacherSpaceData)
      this.updatePieNumData()
    },
    isFloat(n) {
      return n === +n && n !== (n | 0)
    },
    preventDot(e) {
      if (e.keyCode == 190 || e.charCode == 46) {
        //console.log(true)
        e.preventDefault()
      }
    },
    getInitialSpace(params) {
      this.$store.dispatch('spaceAuth/getInitialSpace', params)
    },
    findIndex(id) {
      let targetIndex = this.data.findIndex(item => item.id == id)
      return targetIndex
    }
  },
  created() {
    // this.$api.teachMgmt.GetTeacherList().then(res => {
    //    this.data = res.data
    // })
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.selection.$el.offsetTop - 133 // 預設表格初始高度
    var _this = this
    window.onresize = function() {
      // 定義視窗大小變更通知事件
      _this.screenHeight = document.documentElement.clientHeight // 視窗高度
    }
    //this.$store.dispatch("fetchService");

    this.reload()
  },

  components: {
    PersonalPhoto,
    SpaceAuth,
    Loading
  }
}
</script>
