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

<style lang="less">
.sort-dropdown{
    .ivu-select-dropdown{
        background-color: #2d2d2d;
        border-radius: 2px;
        border: 1px #464646 solid;
        .ivu-dropdown-menu{
            li {
                color: #ccc;
                font-size: 12px!important;
            }
        }
    }
}
#searchForm{
    .searchFormBox{
        .searchIpt{
            input{
                background-color: transparent;
                border-radius: 15px;
                border-color: #464646;
                color: #fff;
            }
        }
        .searchBtn{
            width: 200px;
            background-color: #4e4e4e;
            color: #909090;
            border: none;
            font-weight: 900;
            &:hover{
                border: 1px solid  #fefefe;
                color: #fefefe;
            }
        }
    }
}
#serchUserResult{
    .serchInfo-btns{
        .serchInfoBtn{
            width: 200px;
            display: block;
            margin:0 auto;
            margin-bottom: 10px;
            background-color: #48d2b0;
            color: #fefefe;
            border: none;
            font-weight: 900;
        }
    }
}
#excelResult{
    .ground{
        &Box{
            .ivu-btn{
                margin:0 auto;
                margin-bottom: 10px;
                background-color: #48d2b0;
                color: #fefefe;
                border: none;
                font-weight: 900;
                height: 40px;
                line-height: 40px;
            }
        }
    }
}
</style>

<template>
    <div class="personnel">
        <div class="users">
            <div class="sort-box">
                <div class="title">{{ $t('teachermgmt.users.title') }}</div>
                <div class="sort">
                    <Dropdown class="sort-dropdown" trigger="click" placement="bottom-start" @on-click="function(e){sortCode = e }">
                        <span style="cursor: pointer;">
                            {{ sortCodeText }}
                            <Icon type="ios-arrow-down"></Icon>
                        </span>
                        <DropdownMenu slot="list">
                            <DropdownItem name="time">{{ $t('teachermgmt.users.sortOption1') }}</DropdownItem>
                            <DropdownItem name="apply">{{ $t('teachermgmt.users.sortOption2') }}</DropdownItem>
                            <DropdownItem name="invite">{{ $t('teachermgmt.users.sortOption3') }}</DropdownItem>
                        </DropdownMenu>
                    </Dropdown>
                </div>                
            </div>
            <div class="details">
                <div class="details-box scrollstyle">

                    <div class="detail" v-for="(item, key) in personnels" :key="key">
                        <div class="detail-info">
                            <div class="title ellipsis">
                                {{ item.name }}
                            </div>
                            <span class="sub-title">
                                {{ item.id }}
                                <div class="typeInfo">
                                    <template v-if="item.status == 'invite'">
                                        <icon class="icon" icon="file-alt" /> {{ $t('teachermgmt.users.detail.status.invite') }}
                                    </template>
                                    <template v-else-if="item.status == 'request'">
                                        <icon class="icon" icon="file-alt" /> {{ $t('teachermgmt.users.detail.status.request') }}
                                    </template>

                                </div>
                            </span>
                        </div>
                        <div class="detail-ctr">
                            <div class="time">
                                {{ item.createTime | converTime }}
                            </div>
                            <div class="btns">
                                <template v-if="item.status == 'invite'">
                                    <!--
                                    <i-circle :style="{'cursor': isOver24hr(item.remindDate) == 100 ? 'pointer' : 'auto', marginRight: '20px'}" :percent="isOver24hr(item.remindDate)" :trail-width="9" :stroke-width="10" :size="32" stroke-color="#adadad" trail-color="#545454">
                                        <span @click="remindUser(item, isOver24hr(item.remindDate))">
                                            <Icon size="20" :color="isOver24hr(item.remindDate, 'color')"  type="md-notifications" />
                                        </span>
                                    </i-circle>
                                    -->
                                    <div class="icon-box icon-reject" @click="removeUser(item)">
                                        <v-icon class="icon-reject" iconClass="trash" />
                                    </div>
                                </template>
                                <template v-else-if="item.status == 'request'">
                                    <div class="icon-box icon-check" style="margin-right: 20px;" @click="updUserStatus(item, 'join')">
                                        <icon class="icon-check" icon="check" />
                                    </div>
                                    <div class="icon-box icon-reject" @click="removeUser(item)">
                                        <icon class="icon-reject" icon="times" />
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
        <div class="addTeacher">
            <div class="addTeacher-box">
                <div class="title-box">
                    <span class="title">{{ $t('teachermgmt.addTeacher.title') }}</span>
                    <span class="batch">
                        <div class="download" @click="downloadExample()">
                            <icon class="Icon" icon="download" />{{ $t('teachermgmt.addTeacher.btn.download') }}
                        </div>
                        <div class="upload" @click="$refs.uploadIDs.click()">
                            <icon class="Icon" icon="upload" />{{ $t('teachermgmt.addTeacher.btn.upload') }}
                            <input ref="uploadIDs" type="file" style="display: none;" @change="handleChange" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
                        </div>
                    </span>
                </div>
            </div>
            <div class="search-box">
                <transition name="component-fade" mode="out-in">
                    <div id="searchForm" v-if="!serchModel" key="1">
                        <div class="searchFormBox">
                            <div class="caption" v-html="$t('teachermgmt.addTeacher.content')"></div>
                            <Input class="searchIpt" prefix="ios-search" v-model="serchText" />
                            <p class="errorMsg">{{searchIdErrorMsg}}</p>
                            <Button :loading="serchTHLoading" class="searchBtn" @click="searchTeacher()">{{ $t('teachermgmt.addTeacher.btn.search') }}</Button>
                        </div>
                    </div>
                    <div id="serchUserResult" v-if="serchModel == 'user'" key="2">
                        <div class="resultBox">
                            <div class="avatar-div">
                                <img v-if="searchInfo.picture" :src="searchInfo.picture" />
                                <img v-else src="@/assets/image/touxiang.png" />
                            </div>
                            <div class="basicInfo">
                                <h3>{{searchInfo.name}}</h3>
                                <p>{{searchInfo.email}}</p>
                            </div>
                            <div class="serchInfo-btns">
                                <Button class="serchInfoBtn" @click="sendInvite()">{{ $t('teachermgmt.addTeacher.btn.sendInvite') }}</Button>
                                <Button class="serchInfoBtn" @click="backHome()">{{ $t('teachermgmt.addTeacher.btn.backHome') }}</Button>
                            </div>
                        </div>
                    </div>
                    <div id="excelResult" v-else-if="serchModel == 'excel'" key="3" >

                        <!-- 天 -->
                        <div class="sky">
                            <div class="skyBox">
                                <span class="text1">{{  $t('teachermgmt.addTeacher.skyBox.text1') }}:</span>
                                <span class="text2">{{  $t('teachermgmt.addTeacher.skyBox.text2') }} {{ userListImport.length }} {{ $t('teachermgmt.addTeacher.skyBox.unit') }}</span>，
                                <span class="text3">{{  $t('teachermgmt.addTeacher.skyBox.text3') }} {{ userListImportSuccess.length }} {{ $t('teachermgmt.addTeacher.skyBox.unit') }}</span>，
                                <span class="text4">{{  $t('teachermgmt.addTeacher.skyBox.text4') }} {{ userListImportDuplicate.length }} {{ $t('teachermgmt.addTeacher.skyBox.unit') }}</span>
                                <tooltip v-if="userListImportDuplicate.length"  placement="bottom-start" max-width="200" :transfer="true">
                                    <Icon style="margin-left:5px;" size="15" color="#736036"  type="md-alert" />
                                    <div slot="content">
                                        <p style="border-bottom: 1px solid #fff;">{{ $t('teachermgmt.addTeacher.skyBox.error1') }}</p>
                                        <!-- excelVal 預計是給excel內部的資料 -->
                                        <p v-for="(item, key) in userListImportDuplicate" :key="key"><i>{{ item }}</i></p>
                                    </div>
                                </Tooltip>，
                                <span class="text5">{{  $t('teachermgmt.addTeacher.skyBox.text5') }} {{ userListImportInvalid.length }} {{ $t('teachermgmt.addTeacher.skyBox.unit') }}</span>
                                <tooltip v-if="userListImportInvalid.length" placement="bottom-start" max-width="200" :transfer="true">
                                    <Icon style="margin-left:5px;" size="15" color="#8d3231"  type="md-alert"  />
                                    <div slot="content">
                                        <p style="border-bottom: 1px solid #fff;">{{ $t('teachermgmt.addTeacher.skyBox.error2') }}</p>
                                        <!-- excelVal 預計是給excel內部的資料 -->
                                        <p v-for="(item, key) in userListImportInvalid" :key="key"><i>{{ item }}</i></p>
                                    </div>
                                </Tooltip>
                            </div>
                        </div>

                        <div class="impUsers scrollstyle">
                            <div class="impUsersBox">
                                <transition-group name="fade" tag="ul">
                                    <li class="user" v-for="(item, key) in userListImportSuccess" :key="key">
                                        <div class="avatar">
                                            <img v-if="item.avatar" :src="item.avatar"/>
                                            <img v-else src="@/assets/image/touxiang.png"/>
                                        </div>
                                        <div class="cont">
                                            <h2>{{ item.name }}</h2>
                                            <p class="ellipsis"><i>{{ item.excelVal }}</i></p>
                                        </div>
                                        <div class="btn" @click="removeImpUser(item)">
                                            <span>{{ $t('teachermgmt.addTeacher.impUsersBox.removeUser') }}</span>
                                        </div>
                                    </li>
                                </transition-group>
                            </div>
                        </div>
                        
                        <!-- 地 -->
                        <div  class="ground">
                            <div class="groundBox">
                                <Button v-if="userListImportSuccess.length > 0" @click="sendInvite()" style="width: 300px;margin-right: 40px;">{{ $t('teachermgmt.addTeacher.groundBox.inviteAll') }}</Button>
                                <Button @click="backHome()" style="width: 200px">{{ $t('teachermgmt.addTeacher.btn.backHome') }}</Button>
                            </div>
                        </div>
                    </div>
                </transition>
            </div>
        </div>
    </div>
</template>

<script>
import excel from '@/utils/excel.js'
import { mapGetters, mapMutations } from 'vuex'
import '@/icons/svg/trash.svg'

export default {
    name:'personnel',
    data() {
        return {
            serchModel: '', // excel, user
            sortCode: 'time',
            userListFromCoreID: [], //從CoreID取得的使用者
            userListImport: [], //匯入的使用者
            userListImportClear: [], //匯入的使用者-排除重複資料
            userListImportSuccess: [], //匯入的使用者 -> 成功
            userListImportDuplicate: [], //匯入的使用者 -> 重複邀請
            userListImportInvalid: [], //匯入的使用者 -> 查無此人
            serchText: '',
            serchTHLoading: false,
            searchInfo: {
                picture: '',
                id: '',
                email: '',
                name: ''
            },
            searchIdErrorMsg: '',
        }
    },
    created(){
        // this.dataList = this.$Mock.data.personnelList
    },
    filters:{
        converTime: function (time) { //time: Unix timestamp(秒)
            let datetime = new Date()
            //let timerecount = time * 1000 - datetime.getTimezoneOffset() * 60 * 1000;
            let timerecount = time * 1000;
            datetime.setTime(timerecount);
            let year = datetime.getFullYear();
            let month = datetime.getMonth() + 1;
            let date = datetime.getDate();
            let hour = datetime.getHours();
            let ampm = hour >= 12 ? 'PM' : 'AM';
            hour %= 12
            hour = hour || 12 // the hour '0' should be '12'
            let minute = datetime.getMinutes();            
            return year + '.' + month + '.' + date + ' ' + ampm + ' ' + hour + ':' + minute
        }
    },
    computed:{
        ...mapGetters({
            dataList: 'user/getSchoolUserInvitedOrRequested', // 取得被邀請或申請加入此學校的使用者
            srvAdr: 'config/getSrvAdr'      // 取得現在的站台位置
        }),
        sortCodeText: function(){
            switch (this.sortCode) {
                case 'time':
                    return this.$t('teachermgmt.users.sortOption1')
                break;
                case 'apply':
                    return this.$t('teachermgmt.users.sortOption2')
                break;
                case 'invite':
                    return this.$t('teachermgmt.users.sortOption3')
                break;
            }
        },
        personnels: function(){
            let _this = this;
            switch (this.sortCode) {
                case 'time': 
                    this.dataList.sort(function(a, b){
                        return b.createTime - a.createTime;
                    })
                    return this.dataList
                break;
                default:
                    let a = this.dataList.filter(function(item){
                        return item.type == _this.sortCode
                    })
                    return a
                break;                
            }
        },
    },
    methods: {
        isOver24hr: function (timestamp, type) {
            let datetime = new Date()
            let nowTime = datetime.getTime();
            let equals = nowTime - timestamp*1000
            equals = equals/(1000 * 60 * 60)
            let percent = (equals / 24) * 100
            percent = percent >= 100 ? 100 :  Math.floor(percent)
            if(type == 'color') {
                return percent ==100 ?  '#adadad' : '#545454';
            } else {
                return percent;
            }            
        },
        //取消/拒絕教師邀請
        removeUser: function (val) { //val:使用者的資料(object)
            let removeTitle = '';
            let removecontent = '';
            if(val.status == 'invite') { //被動邀請
                removeTitle = this.$t('teachermgmt.message.info5');
                removecontent = '<p>' + this.$t('teachermgmt.message.info6') + ' ' + val.name + '(' + val.id + ') ' + this.$t('teachermgmt.message.info7') + ' ?</p>';
            } else if(val.status == 'request') { //主動申請
                removeTitle = this.$t('teachermgmt.message.info8');
                removecontent = '<p>' + this.$t('teachermgmt.message.info9') + ' ' + val.name + '(' + val.id + ') ' + this.$t('teachermgmt.message.info10') + ' ?</p>';
            }
            this.$Modal.confirm({
                title: removeTitle,
                content: removecontent,
                onOk: () => {
                    this.$store.dispatch('user/rmvFromSchoolUserByID', { id: val.id }).then(
                        (res) => {
                            if (res.code == 1) {
                                this.$Message.info(this.$t('teachermgmt.message.info1'));
                            }
                            else {
                                alert('Can not set Auth.')
                            }
                        },
                        (err) => {
                            this.$Message.error('user/setSchoolUser API error!')
                        }
                    )
                },
                // onCancel: () => {
                //     this.$Message.info('Clicked cancel');
                // }
            });
        },
        // 比對資料 1.excel資料重複驗證 2.向CoreID取得ID資料 3.比對 CoreID使用者
        importUser: function () {
            // 初始化
            this.userListFromCoreID = [];
            this.userListImportClear = [];
            this.userListImportInvalid = [];
            this.userListImportDuplicate = [];
            this.userListImportSuccess = [];
            let userListImportPreMatchSuccess = []; //第一階段比對成功者資料
            let userListImportPreMatchSuccessIDList = []; //第一階段比對成功者的ID List
            //匯入資料重複
            this.userListImport.forEach((userI) => {
                if (this.userListImportClear.indexOf(userI.toString()) === -1) {
                    this.userListImportClear.push(userI);
                } else {
                    this.userListImportDuplicate.push(userI);
                }
            });

            // 向CoreID取得使用者
            this.$store.dispatch('user/getUserFromCoreId', this.userListImportClear).then(
                (res) => {
                    if (res.code == 1) {
                        this.userListFromCoreID = res.data;
                        // 第一階段資料比對：匯入的使用者 比對 CoreID使用者
                        this.userListImportClear.forEach((userI) => {
                            let userMatchFlg = false;
                            this.userListFromCoreID.forEach((userC) => {
                                if (userI == userC.searchKey) {
                                    userMatchFlg = true;
                                    if (userListImportPreMatchSuccessIDList.indexOf(userC.id.toString()) === -1) { //資料未重複
                                        userListImportPreMatchSuccessIDList.push(userC.id);
                                        userC.excelVal = userC.searchKey; //畫面顯示用欄位
                                        userListImportPreMatchSuccess.push(userC);
                                    } else { //重複資料(不同行的excel資料取到同一位使用者)
                                        this.userListImportDuplicate.push(userI);
                                    }
                                }
                            })
                            if (!userMatchFlg) {
                                this.userListImportInvalid.push(userI)
                            }
                        });
                        // 第一階段資料比對通過，與學校使用者比對
                        let selectUserList = this.$store.getters['user/getSchoolUserAll'];
                        if (userListImportPreMatchSuccess.length > 0) {
                            userListImportPreMatchSuccess.forEach((userM) => {
                                let userAlreadyInSchoolFlg = false;
                                selectUserList.forEach((userSc) => {
                                    if (userM.id == userSc.id) {
                                        this.userListImportClear.forEach((userI) => {
                                            if (userI == userM.searchKey) {
                                                this.userListImportInvalid.push(userM.searchKey);
                                            }
                                        });
                                        userAlreadyInSchoolFlg = true;
                                    }
                                })
                                if (!userAlreadyInSchoolFlg) {
                                    this.userListImportSuccess.push(userM);
                                }
                            })
                        }
                        //結果顯示
                        this.serchModel = 'excel';
                    } else {
                        this.$Message.error('user/getUserFromCoreId API error!')
                    }
                },
                (err) => {
                    this.$Message.error('user/getUserFromCoreId API error!')
                }
            )
        },
        removeImpUser: function(user){
             this.userListImportSuccess.splice(this.userListImportSuccess.indexOf(user),1)
        },
        searchTeacher() {
            this.searchIdErrorMsg = '';
            if (this.serchText) {
                if (this.serchText.indexOf(0) == 0) this.serchText = this.serchText.substr(1) //開頭有0要去0
                // 向CoreID取得使用者
                this.$store.dispatch('user/getUserFromCoreId', [this.serchText]).then(
                    (res) => {
                        if (res.code == 1 && res.data.length > 0) {
                            this.userListImportSuccess = res.data;
                            this.searchInfo = res.data[0];
                            this.searchInfo.status = 'invite'; //學校邀請
                            this.serchModel = 'user';
                        }
                        else {
                            this.searchIdErrorMsg = this.$t('teachermgmt.message.info19');
                        }
                    },
                    (err) => {
                        this.$Message.error('user/getUserFromCoreId API error!')
                    }
                );
            } else {
                this.$Message.warning({
                    content: this.$t('teachermgmt.message.info11'),
                    duration: 5
                });
            }
        },
        //將搜尋成功/匯入成功資料加入DB
        sendInvite() {
            if(this.userListImportSuccess.length > 0) {
                this.$store.dispatch('user/addSchoolUserToInvite', this.userListImportSuccess).then(
                (res) => {
                    if (res.code == 1) {
                        if(this.userListImportSuccess.length > 1) {
                            this.$Message.info({
                                content: this.$t('teachermgmt.message.info12') +'。',
                                duration: 5
                            });
                        }
                        else {
                            this.$Message.info({
                                content: this.$t('teachermgmt.message.info13') +' ' + this.userListImportSuccess[0].name + ' ' + this.$t('teachermgmt.message.info14')+ '。',
                                duration: 5
                            });
                        }
                        this.backHome()
                    }
                    else {
                        alert('Can not add user.')
                    }
                },
                (err) => {
                    this.$Message.error('user/addSchoolUser API error!')
                })
            }
        },
        backHome() {
            this.serchText= ''
            this.searchInfo = {}
            this.serchModel = ''
        },
        handleChange(e) {
            const files = e.target.files;

            if (!files) {
                return;
            }

            this.readExcel(files[0], this.analyzeExcel)
            this.$refs.uploadIDs.value = null;
        },
        readExcel(file, callback) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var data = e.target.result;
                var workbook = excel.read(data, 'binary');                
                if (callback) callback(workbook);
            };
            reader.readAsBinaryString(file);
        },
        // 解析Excel Data
        analyzeExcel(data) {
            if (data.results.length == 0) {
                this.$Message.warning(this.$t('teachermgmt.message.info15') + '!!');
                return false
            }

            this.userListImport = [];
            let title = data.header[0];
            data.results.forEach(row => {
                this.userListImport.push(row[title].toString());
            });

            //比對資料
            if(this.userListImport.length > 0) {
                this.importUser();
            }
        },
        //提醒使用者
        remindUser(val, remindPercentage) { //val:使用者的資料(object)
            if(remindPercentage == 100) {
                //[未定]寄發提醒資料
                //變更提醒時間
                let datetime = new Date();
                let nowTime = datetime.getTime();
                let remindDateNow = Math.floor(nowTime / 1000);
                this.$store.dispatch('user/updSchoolUserByParam', { id: val.id, param: { remindDate : remindDateNow } }).then(
                    (res) => {
                        if (res.code == 1) {
                            this.$Message.info(this.$t('teachermgmt.message.info2'));
                        }
                        else {
                            alert('Can not set Auth.')
                        }
                    },
                    (err) => {
                        this.$Message.error('user/setSchoolUser API error!')
                    }
                )
            }
        },
        //變更加入狀態 (join:已加入 invite:被邀請 request:申請中)
        updUserStatus(val, updStatus) { //val:使用者的資料(object)
            let statusTitle = '';
            let statusContent = '';
            if(val.status == 'request' && updStatus == 'join') {
                statusTitle = this.$t('teachermgmt.message.info16');
                statusContent = '<p>' + this.$t('teachermgmt.message.info17') + ' ' + val.name + '(' + val.id + ') '+ this.$t('teachermgmt.message.info18') +' ?</p>';
            }
            this.$Modal.confirm({
                title: statusTitle,
                content: statusContent,
                onOk: () => {
                    this.$store.dispatch('user/updSchoolUserStatus', { id: val.id, status: updStatus }).then(
                        (res) => {
                            if (res.code == 1) {
                                this.$Message.info(this.$t('teachermgmt.message.info3'));
                            }
                            else {
                                alert('Can not update param.')
                            }
                            //清空vuex教师列表，保证其他页面获取最新数据
                            this.$store.commit('teachers/setTeacherList', [])
                        },
                        (err) => {
                            this.$Message.error('user/updSchoolUserStatus API error!')
                        }
                    )
                }
            });
        },
        downloadExample: function() {
            // 暫時寫死 日後需要變動再更改
            switch (this.srvAdr) {
                case 'China':
                    window.location.href = 'https://teammodelstorage.blob.core.chinacloudapi.cn/example/teachermgmt_example.xlsx'
                    break;
                case 'Global':
                    window.location.href = 'https://teammodelstorage.blob.core.windows.net/example/teachermgmt_example.xlsx'
                    break;
                default:
                    window.location.href = 'https://teammodelstorage.blob.core.windows.net/example/teachermgmt_example.xlsx'
                    break;
            }
        },
    }
}
</script>