<template>
    <div class="app-container">
        <div class="tab">
            <div v-for="(item,$index) in survey.stageList" :key="item.name" :style="'background-color:'+stageColor[$index]" :class="'stage '+ (tabId == $index?'stage_select':'')"  @click="changeTab($index,item.id)" > {{ item.name }} </div>                 
        </div>
        <div class="tab">
            <div v-for="(item,$index) in teamList" :key="item.name" :style="'background-color:'+teamColor[$index]" :class="'stage '+ (teamTabId == item.id?'stage_select':'') "  @click="changeTeamTab(item.id)"  > {{ item.name }} </div>
        </div>
        <div v-if="teamTabId == 1" class="tbPanel">
            <div class="filter-container">
                
                <el-input v-model="teamQuery.teamName" placeholder="团队名称" />
                <el-button @click="loadData">搜索</el-button>
                <el-button @click="dialogVisable = true">添加团队</el-button>
                <el-button @click="batchImport">批量导入<input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx" @change="handleClick"></el-button>
                <el-input v-model="toTeamId" placeholder="请输入新的大赛ID" />
                <el-button @click="copyTeam">复制团队及队员</el-button>
            </div>
            <el-table :data.sync="tableData">
                <el-table-column label="团队名称">
                    <template slot-scope="scope">
                        {{ scope.row.teamName}}<i class="el-icon-edit" @click="handleEditTeamInfo(scope.row,1)"  />
                    </template>
                </el-table-column>
                 <el-table-column label="院校" prop="school">

                </el-table-column>
                <el-table-column v-for="item in columnList" :key="item.id" :label="item.lable">
                    <template slot-scope="scope">
                        {{ scope.row[item.name].name }} <i v-if="scope.row[item.name].name" @click="deleteMember(scope.row,item.name)" class="el-icon-delete" />
                    </template>
                </el-table-column>
                 <el-table-column label="指导老师">
                     <template slot-scope="scope">
                         {{ scope.row.teacher}}<i class="el-icon-edit" @click="handleEditTeamInfo(scope.row,2)" />
                     </template>
                 </el-table-column>

                <el-table-column label="操作">
                     <template slot-scope="scope">
                       <el-button class="small" @click="addMember(scope.row)" >添加成员</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                :current-page.sync="teamQuery.pageNo"
                :page-sizes="[10,15,20]"
                :page-size.sync="teamQuery.pageSize"
                layout="total,prev,pager,next,jumper,sizes"
                :total="teamQuery.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                
                />
        </div>
        <div v-if="teamTabId == 2">
            <div class="filter-container">
                <el-input v-model="memberQuery2.name" placeholder="姓名/学号" /> 
                <el-button @click="listMember2">搜索</el-button> 
                <el-button v-if="this.survey.type == 2" @click="addMemberVisable2 = true" >添加成员</el-button>
                <el-button v-if="this.survey.type == 2" @click="importMember" >
                    批量导入
                    <input ref="member-upload-input" type="file" accept=".xlsx" style="display:none;" @change="handleClick2">
                </el-button>
            </div>
            <el-table :data="memberList2">
                <el-table-column label="姓名">
                    <template slot-scope="scope">
                        {{ scope.row.name }}
                    </template>
                </el-table-column>
                <el-table-column label="学号">
                    <template slot-scope="scope">
                        {{ scope.row.studentNo }}
                    </template>
                </el-table-column>
                <el-table-column v-if="survey.type==1" label="团队" >
                    <template slot-scope="scope">
                        {{ scope.row.teamName }}
                    </template>
                </el-table-column>
                <el-table-column label="学校">
                     <template slot-scope="scope">
                        {{ scope.row.school }}
                    </template>
                </el-table-column>
                <el-table-column label="指导教师">
                     <template slot-scope="scope">
                        {{ scope.row.teacher }}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="danger" @click="deleteMember2(scope.row)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                :current-page.sync="memberQuery2.pageNo"
                :page-sizes="[10,15,20]"
                :page-size.sync="memberQuery2.pageSize"
                layout="total,prev,pager,next,jumper,sizes"
                :total="memberQuery2.total"
                @size-change="listMember2"
                @current-change="listMember2"
                
                />

        </div>
        <el-dialog title="添加团队" :visible.sync="dialogVisable">
            <div class="filter-container">
                <el-input v-model="createTeam.teamName" placeholder="输入团队名" class="small" />
                <el-input v-model="createTeam.teacher" placeholder="输入指导老师" class="small"/>
                <el-input v-model="memberQuery.name" placeholder="输入学号/姓名检索"/>
                <el-button @click="searchMemberForTeam">查询</el-button>
            </div>
            <div class="app-container">
                <select-panel :list="userList" :selectedList.sync='userSelectList' :loading="memberLoading" @pageDown="pageDown" />
            </div>
            <div>
                <el-button @click="addTeam">添加团队</el-button>
                <el-button @click="dialogVisable = false">取消</el-button>
            </div>
        </el-dialog>
        <el-dialog ref="editTeam" :title="editTeamInfo.title" :visible.sync="editTeamNameVisable" >
            <el-form>
                <el-form-item>
                    <el-input v-model="editTeamInfo.name" />
                </el-form-item>
            </el-form>
            <el-button class="small" @click="confirmEditTeam" >确定</el-button>
            <el-button class="small">取消</el-button>
        </el-dialog>
        <el-dialog title="添加成员" :visible.sync="addMemberVisable">
            <div class="filter-container">
                <el-input v-model="memberQuery.name" placeholder="输入学号或姓名"/>
                <el-button @click="searchMember">查询</el-button>
            </div>
            <el-table :data="addMemberList"
             @selection-change="onSelect"
            >
                <el-table-column type="selection" />
                <el-table-column label="学号">
                    <template slot-scope="scope">
                        {{ scope.row.studentNo}}
                    </template>
                </el-table-column>
                <el-table-column label="姓名">
                    <template slot-scope="scope">
                        {{ scope.row.name}}
                    </template>
                </el-table-column>
                <el-table-column label="层次">
                    <template slot-scope="scope">
                        {{ idToLevelName(scope.row.levelId)}}
                    </template>
                </el-table-column>
            </el-table>
            <el-button @click="addTeamMember">添加队员</el-button>
            <el-button @click="addMemberVisable = false">取消</el-button>
        </el-dialog>
        <el-dialog title="添加个人赛成员" :visible.sync="addMemberVisable2">
            <div class="filter-container">
                <el-input v-model="createMember.teacher" placeholder="请输入指导老师"/>
                <el-input v-model="userQuery2.name" placeholder="输入学号或姓名"/>
                <el-select v-model="userQuery2.levelId">
                    <el-option v-for="item in levelOptions" :key="item.id" :value="item.id" :label="item.name"></el-option>
                </el-select> 
                <el-button @click="searchUser">查询</el-button>
            </div>
            <el-table :data="userList2"
             @selection-change="onSelect"
            >
                <el-table-column type="selection" />
                <el-table-column label="学号">
                    <template slot-scope="scope">
                        {{ scope.row.studentNo}}
                    </template>
                </el-table-column>
                <el-table-column label="姓名">
                    <template slot-scope="scope">
                        {{  idToLevelName(scope.row.levelId)}}
                    </template>
                </el-table-column>
                <el-table-column label="层次">
                    <template slot-scope="scope">
                        {{ scope.row.level}}
                    </template>
                </el-table-column>
            </el-table>
             <el-pagination
                :current-page.sync="userQuery2.pageNo"
                :page-sizes="[10,15,20]"
                :page-size.sync="userQuery2.pageSize"
                layout="total,prev,pager,next,jumper,sizes"
                :total="userQuery2.total"
                @size-change="searchUser"
                @current-change="searchUser"
                
                />
            <el-button @click="addTeamMember2">添加队员</el-button>
            <el-button @click="addMemberVisable2 = false">取消</el-button>
        </el-dialog>
    </div>
</template>
<script>
import SelectPanel from './selectPanel.vue'
import * as userApi from '@/api/user'
import * as teamApi from '@/api/team'
import * as levelApi from '@/api/level'
import * as teamMemberApi from '@/api/teammember'
export default {
    components: {
        'select-panel': SelectPanel
    },
    props: {
        survey: {
            type: Object,
            default: {}
        },
        team: {
            type: Array
        },
        competitionType:{
            type: Number,
            default: 1
        },
        teamMinCount: {
            type: Number,
            default: 2
        },
        teamMaxCount: {
            type: Number,
            default: 5
        },
        cmpId: {
            type: Number
        }
    },
    data(){
        return {
            toTeamId: 0,
            dialogVisable: false,
            stageColor: [
                '#1490ce',
                '#ff8e8e',
                '#8e00c6',
            ],
            teamColor: [
                "#fec52e",
                "#1490ce"
            ],
            editTeamInfo: {
                dv:true,
                item: {},
                title: '编辑团队名称',
                name: '',
                type:1
            },
            editTeamNameVisable: false,
            addMemberVisable: false,
            addMemberVisable2: false,
            teamList: [],
            tabId: 0,
            teamTabId: 0,
            stageId: null,
            columnList: [],
            tableData:[],
            teamTab: 0,
            userQuery: {
                pageNo: 0
            },
            createTeam:{
                teamName: '',
                teacher: '',
                ids:[]
            },
            createMember: {
                teacher:'',
                ids: [],
                competitionId: this.cmpId,
                stageId: this.stageId
            },
            teamQuery: {
                competitionId: this.cmpId,
                stageId: this.stageId,
                pageNo: 0,
                pageSize: 20,
                total: 0,
                teamName: null,
            },
            userList: [],
            userSelectList:[],
            addMemberList:[],
            userList2: [],
            willAddMemberList:[],
            levelOptions: [],
            memberQuery: {
                name: ''
            },
            memberQuery2: {
                competitionId: this.cmpId,
                stageId: this.stageId,
                pageNo: 1,
                pageSize: 20,
                total: 0,
                name: ''
            },
            userQuery2: {
                pageNo: 1,
                pageSize: 20,
                total: 0,
                userType: 1,
                levelId: null,
                name: ''
            },
            tempTeamInfo:{},
            memberLoading: false,
            memberList2: []
        }
    },
    created(){
        if(this.competitionType){
            if(this.survey.type == 1){
                this.teamList = [{id: 1,name: '参赛团队'},{id: 2,name: '参赛人员'}]
                this.teamTabId =1
            }else{
                this.teamList = [{id: 2,name: '参赛人员'}]
                this.teamTabId =2
            }
            
        }
        userApi.getList(this.userQuery).then(res=>{
            if(res.code == 200){
                this.userList = res.data.userPage.content
            }
        })
         
         this.stageId = this.survey.stageList[0].id
         this.teamQuery.stageId = this.stageId
         for(var i = 0 ;i< this.teamMaxCount;i++){
            let tmp = {
                id: i,
                lable: '组员'+(i+1),
                name: 'member_'+(i+1)
            } 
            this.columnList.push(tmp)           
         }

         levelApi.getList().then(res=>{
             if(res.code == 200){
                 this.levelOptions = res.data.list
             }
         })

         this.loadData()
         this.listMember2()
    },
    methods: {
        copyTeam(){
            if(this.toTeamId>0){
                teamApi.copyTeam(this.memberQuery2.competitionId, this.toTeamId).then(res=>{
                    this.$notify({
                        title: '提示信息',
                        message: res.msg,
                        type: 'warning',
                        duration: 2000
                    })
                })

            }else{
                this.$notify({
                        title: '提示信息',
                        message: "请先设置新大赛ID",
                        type: 'warning',
                        duration: 2000
                    })
            }
        },
        changeTab(index,id){
            this.tabId = index
            this.stageId = id
            this.teamQuery.stageId = this.stageId
            
            if(this.survey.type == 1){
                this.loadData()
            }else{
                this.listMember2()
            }
            
        },
        changeTeamTab(index){            
            this.teamTabId = index            
            if(this.teamTabId == 2){
                this.listMember2()
            }
        },
        listMember2(){
            this.memberQuery2.stageId = this.stageId
            teamApi.listTeamMember(this.memberQuery2).then(res=>{
                    if(res.code == 200){
                        this.memberList2 = res.data.page.content
                        this.memberQuery2.total = res.data.page.totalElements   
                    }                                   
            })
        },
        deleteMember2(item){
            console.log(item)
            teamApi.deleteMember({id: item.id}).then(res=>{
                if(res.code == 200){
                   this.listMember2()
                }
            })
        },
        addMember(item){
            this.tempTeamInfo = item
            this.addMemberList = []
            this.addMemberVisable=true
        },
        addTeamMember2(){
            let ids = []           
             this.willAddMemberList.forEach(item=> ids.push(item.id) )
             this.createMember.stageId =this.stageId
             this.createMember.ids = ids
            teamMemberApi.add(this.createMember).then(res=> {
                if(res.code == 200){
                    this.$notify({
                        title: '操作成功',
                        message: "success",
                        type: 'success',
                        duration: 2000
                    })
                    this.listMember2()
                }
            })
        },
        idToLevelName(id){
            let items =  this.levelOptions.filter((item)=>{ return item.id == id})
            if(items&&items.length>0){
                return items[0].name
            }
        },
        batchImport(){
            this.$refs['excel-upload-input'].click()
        },
        handleClick(e) {           
            const files = e.target.files
            const rawFile = files[0] // only use files[0]
             teamApi.uploadExcel({
                 file: rawFile,
                 competitionId: this.cmpId,
                 stageId: this.stageId
             }).then(res=>{
                 if(res.code == 200){
                     this.loadData()
                 }
             })
        },
        importMember(){
            this.$refs["member-upload-input"].click()
        },
        handleClick2(e) {           
            const files = e.target.files
            const rawFile = files[0] // only use files[0]
             teamMemberApi.uploadExcel({
                 file: rawFile,
                 competitionId: this.cmpId,
                 stageId: this.stageId
             }).then(res=>{
                 if(res.code == 200){
                     this.listMember2()
                 }
             })
        },
        handleSizeChange(){
            this.loadData()
        },
        handleCurrentChange(){
            this.loadData()
        },
        deleteMember(row,name){
            let item = row[name]
            teamApi.deleteMember({id: item.id}).then(res=>{
                if(res.code == 200){
                    this.loadData()
                }
            })
        },
        handleEditTeamInfo(item,type){
            this.editTeamNameVisable = true
            this.editTeamInfo.item = item
            this.editTeamInfo.type=type
            if(type==1){
                this.editTeamInfo.name = item.teamName
            }else{
                this.editTeamInfo.name = item.teacher
            }
        },
        confirmEditTeam(){
            teamApi.editTeamInfo({
                type: this.editTeamInfo.type,
                name: this.editTeamInfo.name,
                id: this.editTeamInfo.item.id
            }).then(res=>{
                if(res.code == 200){
                    this.loadData()
                    this.editTeamNameVisable =false
                }
            })
        },
        loadData(){
            teamApi.getList(this.teamQuery).then(res=>{
            if(res.code == 200){
                const teamArray = res.data.page.content
                this.teamQuery.total = res.data.page.totalElements
                const memberList = res.data.list
                this.tableData =[]
                teamArray.forEach(team =>{
                        const teamMembers = memberList.filter(m => m.teamId == team.id)
                        let teamInfo = {
                                id: 0,
                                teamName: '',
                                school: '',
                                member_1: "",
                                member_2: "",
                                member_3: "",
                                member_4: '',
                                member_5: '',
                                teacher: ''
                        }
                        teamInfo.teamName = team.teamName
                        teamInfo.school = team.school
                        teamInfo.teacher = team.teacherName
                        teamInfo.id = team.id
                        for(var i = 0 ;i< teamMembers.length;i++){
                            const m = teamMembers[i]
                            teamInfo["member_"+(i+1)] = m
                            teamInfo.school = m.school
    
                        }
                        this.tableData.push(teamInfo)
                    })
                }
            })
        },
        onSelect(val){
            console.log(val)
            this.willAddMemberList =val
        },
        searchMember(){
           userApi.listByKey(this.memberQuery).then(res=>{
               if(res.code == 200){
                   this.addMemberList = res.data.list
                //    const tmp = this.addMemberList.find(item=>item.id == res.data.id)
                //    if(!tmp){
                //         this.addMemberList.push(res.data)
                //    }
                   
               }else{
                   this.$notify({
                        title: '操作失败',
                        message: res.msg,
                        type: 'warning',
                        duration: 2000
                    })
               }
           })
        },
        searchMemberForTeam(){
             userApi.listByKey(this.memberQuery).then(res=>{
               if(res.code == 200){
                   this.userList = []
                   this.userList = res.data.list
                   
               }else{
                   this.$notify({
                        title: '操作失败',
                        message: res.msg,
                        type: 'warning',
                        duration: 2000
                    })
               }
           })
        },
        searchUser(){
           userApi.getList(this.userQuery2).then(res=>{
               if(res.code == 200){
                 this.userList2 = res.data.userPage.content
                 this.userQuery2.total = res.data.userPage.totalElements
               }
              
           })
        },
        addTeamMember(){
            if(this.willAddMemberList.length == 0){
                this.$notify({
                        title: '操作失败',
                        message: "请选择需要添加的成员",
                        type: 'warning',
                        duration: 2000
                    })
                return
            }
            let ids = []
            this.willAddMemberList.forEach(item=> ids.push(item.id) )
            console.log(this.cmpId,this.stageId,this.tempTeamInfo.id)
            teamApi.addMember({
                teamId: this.tempTeamInfo.id,
                competitionId: this.compId,
                stageId: this.stageId,
                ids: ids
            }).then(res=>{
                if(res.code == 200){
                    this.addMemberVisable=false
                    this.loadData()
                }
            })
        },
        addTeam(){
     
            if(this.userSelectList.length>0){
                let ids = []
                this.userSelectList.forEach(user => ids.push(user.id))
                 teamApi.addTeam({
                    competitionId: this.cmpId,
                    stageId: this.stageId,
                    ids:ids,
                    teamName: this.createTeam.teamName,
                    teacher: this.createTeam.teacher
                }).then(res=>{
                    if(res.code == 200 ){
                        this.$notify({
                        title: '操作成功',
                        message: "添加成功",
                        type: 'success',
                        duration: 2000
                    })
                    this.loadData()
                    this.dialogVisable =false
                    }
                })
            }
           
        },
        pageDown(){
            this.memberLoading = true;
            console.log("pageDown")     
            this.userQuery.pageNo += 1
            userApi.getList(this.userQuery).then(res=>{
            if(res.code == 200){
                if(res.data.userPage.content.length>0){
                    this.userList = this.userList.concat(res.data.userPage.content)
                }                
                this.memberLoading = false
            }
        })       
        }
    }
}
</script>
<style scoped>
 .tab {
        display: flex;
        line-height: 40px;
    }
.tab div{
    margin-right: 20px;
}
.stage{
    padding: 3px;
    color: white;
    border-radius: 5px;
    padding-left: 80px;
    padding-right: 80px;
    margin-bottom: 10px;
}
.stage:hover{
    color: black;
}
.stage_select{
    color: black;
}
.excel-upload-input{
    display: none;
    z-index: -9999;
}
</style>