<template>
  <div class="container-box">
      <div class="filter-box">
        <el-button-group>
            <el-button size="medium" plain @click="filteredByState('')">{{$i18n.locale=='en'? 'All': '全部'}}</el-button>
            <el-button size="medium" plain @click="filteredByState('2')">{{$i18n.locale=='en'? 'UnderApproval': '审批中'}}</el-button>
            <el-button size="medium" plain @click="filteredByState('4')">{{$i18n.locale=='en'? 'Registration Successful': '审批通过'}}</el-button>
            <el-button size="medium" plain @click="filteredByState('3')">{{$i18n.locale=='en'? 'Registration Failed': '审批不通过'}}</el-button>
        </el-button-group>
        <!-- <el-input
            style="width: 300px"
            size="medium"
            placeholder="请输入内容"
            suffix-icon="el-icon-search"
            v-model="input2">
        </el-input> -->
      </div>
      <el-table
        v-loading="loading"
        element-loading-text=""
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.6)"
        :data="tableData"
        tooltip-effect="dark"
        :border="true"
        size="small"
        :lazy="true"
        height="570"
        :empty-text="$i18n.locale=='en'? 'Sorry no data!':'暂无数据'"
        @selection-change="handleSelectionChange">
        <el-table-column prop="meetingId" :label="$i18n.locale=='en'? 'Events':'会议名称'" header-align="center">
            <template slot-scope="scope">{{ meetingNameMap[scope.row.meetingId] }}</template>
        </el-table-column>
        <el-table-column :label="$i18n.locale=='en'? 'Date':'会议时间'" width="90" header-align="center">
            <template slot-scope="scope">{{ formatDate(meetingStartDateMap[scope.row.meetingId]) }}</template>
        </el-table-column>
        <el-table-column prop="name" label="CH Name" width="100" v-if="$i18n.locale=='en'" header-align="center"></el-table-column>
        <el-table-column prop="name" label="中文姓名" width="100" v-else header-align="center"></el-table-column>
        <el-table-column prop="nameEn" label="EN Name" width="100" v-if="$i18n.locale=='en'" header-align="center"></el-table-column>
        <el-table-column prop="nameEn" label="英文姓名" width="100" v-else header-align="center"></el-table-column>
        <el-table-column prop="auditStatusDict" :label="$i18n.locale=='en'? 'Status':'状态'"  width="84" header-align="center">
            <template slot-scope="scope">{{ approvalStatus[scope.row.auditStatusDict] }}</template>
        </el-table-column>
        <el-table-column prop="comments" :label="$i18n.locale=='en'? 'Opinions':'审批意见'" width="120" header-align="center">
            <template slot-scope="scope">
                <span v-if="scope.row.auditStatusDict=='4'" style="display: block; text-align: center">/</span>
                <div v-else>
                    <el-tooltip v-for="(com,c) in scope.row.comments" :key="c" class="item" effect="dark" :content="com" placement="top">
                        <i class="icon el-icon-tickets"></i>
                    </el-tooltip>
                    <!-- <span v-for="(com,c) in scope.row.comments" :key="c" style="display: block">{{ com }}</span> -->
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="auditStatusDict" :label="$i18n.locale=='en'? 'Operation': '操作'" width="90" header-align="center">
            <template slot-scope="scope">
                <el-tooltip v-if="scope.row.auditStatusDict=='4' && !scope.row.travelArrivalTime" class="item" effect="dark" :content="$i18n.locale=='en'? 'Supplement': '补录信息'" placement="top">
                    <i class="icon el-icon-edit" @click="toView('TravelInformation', scope.row)"></i>
                </el-tooltip>
                <el-tooltip v-if="scope.row.auditStatusDict=='2' && scope.row.comments.length" class="item" effect="dark" :content="$i18n.locale=='en'? 'ReApply': '重新报名'" placement="top">
                    <i class="icon el-icon-refresh-right" @click="toView('MeetingApplyForm', scope.row)"></i>
                </el-tooltip>
                <el-tooltip v-if="scope.row.isSpeak=='Yes'" class="item" effect="dark" :content="$i18n.locale=='en'? 'Upload presentation materials': '上传发言材料'" placement="top">
                    <i class="icon el-icon-upload" @click="toView('SpeechMaterial', scope.row)"></i>
                </el-tooltip>
                <el-tooltip v-if="scope.row.auditStatusDict=='4' && scope.row.isSendAttend=='Yes'" class="item" effect="dark" :content="$i18n.locale=='en'? 'Intention to attend': '参会意向'" placement="top">
                    <i class="icon el-icon-finished" @click="getIntentionAttend(scope.row.id, scope.row)"></i>
                </el-tooltip>
            </template>
        </el-table-column>
        
    </el-table>
      <div style="width: 100%;text-align: center;">
          <el-pagination
                  style="margin-top: 20px"
                  layout="prev, pager, next"
                  @current-change="currentChange"
                  :total="totalNum">
          </el-pagination>
      </div>
    <el-dialog title="感兴趣的会场和活动（多选）Intersted forums and events（Multiple choice）" :visible.sync="dialogTableVisible">
        <el-table :data="gridData" max-height="400" :border="false" :show-header="false" size="small" @selection-change="checkRow" @row-click="setSelect" ref="multipleTable" class="active-grid">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column property="activityName">
                <template slot-scope="scope">
                    <p style="font-weight: bold">{{ momentDate(scope.row.activityStartTime) }} ~ {{ momentDate(scope.row.activityEndTime) }}</p>
                    <p>{{ scope.row.activityName }}</p>
                    <p>{{ scope.row.activityNameEn }}</p>
                </template>
            </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer" style="text-align: center">
            <el-button @click="dialogTableVisible = false" size="small">{{$i18n.locale=='en'? 'Cancel': '取 消'}}</el-button>
            <el-button type="primary" :disabled='unBtn' @click="submitActivityInfo" size="small">{{$i18n.locale=='en'? 'Submit': '确 定'}}</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import {getApplyHistory, getMeetingInfo,getMeetingApproveHistory, getActivityInfo, updateActivityInfo} from '@/api/meeting/meetingApply'
import { getDicts } from "@/api/dict";
import Base from "@/views/base/Base";
import moment from 'moment-timezone';
export default {
    extends: Base,
    data(){
        return {
            input2: '',
            tableData: [],
            multipleSelection: [],
            meetingInfoArray: [],
            statusArray: [],
            statusEnArray:[],
            cureentPage: 1,
            auditStatusDict: '', // 全部:"" 审批中:2 审批不通过:3 审批通过:4
            userId: JSON.parse(localStorage.getItem('user')).userId,
            totalNum: 0,
            loading: true,
            dialogTableVisible: false,
            gridData: [],
            meetingApplyId: '',
            checkedIds: [],
            unBtn:false,
            newChecked:[]
        }
    },
    mounted(){
        this.getApplyHistory();
        getMeetingInfo().then(res =>{
            this.meetingInfoArray = res.data.meetingBasicInfos
            //debugger
        });   
        getDicts('APPROVAL_STATUS').then(res=>{
            this.statusArray = res.data[0];
            this.statusEnArray = [{"label":"UnderApproval","value":"2"},
            {"label":"Registration Failed","value":"3"},
            {"label":"Registration Successful","value":"4"}];
        })
    },
    computed: {
        meetingNameMap: function() {
            if(this.$i18n.locale == "en"){
                return this.meetingInfoArray.array2Obj('id', 'meetingNameEn');
            }else{
                return this.meetingInfoArray.array2Obj('id', 'meetingName');
            }
        },
        meetingStartDateMap: function() {
           return this.meetingInfoArray.array2Obj('id', 'meetingStartDate');
        },
        approvalStatus: function() {
        if(this.$i18n.locale == "en"){
            return this.statusEnArray.array2Obj('value', 'label');       
        }else{
            return this.statusArray.array2Obj('value', 'label');    
        }
           
        }
    },
    methods: {
        momentDate(date){
            if(this.$i18n.locale == 'zh'){
                return moment(date).format('YYYY MM DD, H:mm')
            }else{
                moment.locale('en')
                return moment(date).format('lll')
            }
        },
        checkRow(checkedData){
            this.checkedIds = [];
            this.newChecked = [];
            const date = []
            checkedData.forEach(item=>{
                date.find(i=>{
                    if(i===this.momentDate(item.activityStartTime)){
                        let msgTxt = this.$i18n.locale=='en'? 'Kind Reminder: participants can only register for one parallel session. Hope you enjoy the conference.': '温馨提示：同一时段平行召开的会议仅限选择一场参加，祝您参会愉快！';
                        this.$message({
                            message: msgTxt,
                            type:'error'
                        })
                    }
                })
                date.push(this.momentDate(item.activityStartTime))
                this.checkedIds.push(item.id)
                this.newChecked.push(item.activityStartTime)
            })
        },
        setSelect(row){
            this.$refs.multipleTable.toggleRowSelection(row);
        },
        submitActivityInfo(){
            var arr1=this.newChecked
            var arr2=arr1.sort()
            for(var i=0;i<arr2.length-1;i++){
                if(arr2[i]==arr2[i+1]){
                    let msgTxt = this.$i18n.locale=='en'? 'Kind Reminder: participants can only register for one parallel session. Hope you enjoy the conference.': '温馨提示：同一时段平行召开的会议仅限选择一场参加，祝您参会愉快！';
                    this.$message.error(msgTxt)
                    return false
                }else{
                    console.log('hello');
                }
            }
            this.submitHandler((token) => {
                var meetingApplyId = this.meetingApplyId;
                var travelPointIds = this.checkedIds.join(",");
                updateActivityInfo(this.meetingApplyId,travelPointIds,token).then(res =>{
                    if(res.status=='200'){
                        let msgTxt = this.$i18n.locale=='en'? 'Submitted successfully.': '提交成功';
                        this.$message({
                            message: msgTxt,
                            type: 'success'
                        });
                        this.dialogTableVisible = false;
                        this.resetToken();
                    }
                }).catch(err=>{
                    this.resetToken();
                });
            }); 
        },
        getIntentionAttend(id){
            getActivityInfo(id).then((res)=>{
                console.log(res)
                this.gridData = res.data.activityInfos || [];
                this.dialogTableVisible = true;
                if(res.data.activityInfos.length && res.data.curActivityInfos.length){
                    res.data.activityInfos.forEach((item, i)=>{
                        if(res.data.curActivityInfos.includes(item.id)){
                            setTimeout(()=>{
                                this.$refs.multipleTable.toggleRowSelection(item);
                            })
                        }
                    })
                }
            }).catch(err=>{
                this.gridData = []
            })
            this.meetingApplyId = id;
        },
        currentChange(p){
            this.cureentPage = p;
            this.getApplyHistory();
        },
        getApplyHistory(){
            getApplyHistory({pageNo: this.cureentPage, auditStatusDict: this.auditStatusDict, createBy:this.userId}).then(res=>{
                let that = this;
                if(res.data){
                    if(res.data.page){
                        this.totalNum = Number(res.data.page.totalCount);
                    }
                    if(res.data.meetingApplys){
                        res.data.meetingApplys.forEach(item => {
                            item.comments = []
                            getMeetingApproveHistory(item.id).then(res=>{
                                if(res.data){
                                    if(res.data.tasks){
                                        res.data.tasks.forEach(com => {
                                            if(com.comment){
                                                item.comments.push(com.comment)
                                            }
                                        })
                                    }
                                }
                            }).then(function(){
                                that.tableData = res.data.meetingApplys;
                                console.log('that.tableData', that.tableData)
                            }).catch(()=>{
                                this.loading = false
                            })
                        })
                    }else{
                        that.tableData = []
                    }
                }else{
                    that.tableData = []
                }
                this.loading = false
            })
        },
        filteredByState(state){
            this.auditStatusDict = state;
            this.getApplyHistory();
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        formatDate(t) {
            if(!t){
                return ''
            }else{
                var original = new Date(t);
                var year=original.getFullYear(); 
                var month=original.getMonth()+1;  
                var date=original.getDate();      
                var hour=original.getHours();     
                var minute=original.getMinutes(); 
                var second=original.getSeconds(); 
                // return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 
                return year+"/"+month+"/"+date; 
            }
        },
        toView(router, json) {
            this.$router.push({ name: router, params: { key: json } });
        },
    }
}
</script>

<style scoped>
.container-box{
    padding: 20px;
}
.filter-box{
    display: flex;
    justify-content: space-between;
    padding: 20px 0;
}
.icon{
    font-size: 18px;
    margin: 0 6px;
    cursor: pointer;
}
.icon:hover{
    color: #1f98d0;
}
.active-grid p{
    margin: 0;
}
/deep/ .el-dialog__title{
    font-size: 16px;
}
</style>