<template>
  <div class="room">
    <div class="room__head">
      <div class="room__head--title">
        {{ $t('trainRoom.comprehensiveDrillRoom') }}
      </div>
      <div class="room__head--notes">
        {{ $t('trainRoom.comprehensiveTrainingManager') + room.creator.nickName }}
      </div>
    </div>
    <div class="room__container">
      <e-members
        class="room__container--members"
        :room="room"
        :members="members"
        :height="height"
        @message="messageInfo"
      />
      <e-roles
        class="room__container--roles"
        :room="room"
        :members="members"
        :height="height"
        :station-list="stationList"
        :stand-list="standList"
        :door-list="doorList"
        @message="messageInfo"
        @joinTraining="jumpInSimulation"
      />
      <e-chat
        class="room__container--chat"
        :room="room"
        :members="members"
        :height="height"
        @message="messageInfo"
      />
    </div>
    <div class="room__footer" />
  </div>
</template>

<script>
import eMembers from './e-members';
import eChat from './e-chat';
import eRoles from './e-roles';
import { postRoomDetail, getJointTrainRoomUserList, getRealDevices, putJointTrainingSimulationEntrance } from '@/api/chat';
import { getPublishMapInfo, hasDoorStationList } from '@/api/jmap/map';
import { launchFullscreen } from '@/utils/screen';
import { getStationList } from '@/api/runplan';
import { checkLoginLine } from '@/api/login';

export default {
    components: {
        eMembers,
        eChat,
        eRoles
    },
    data() {
        return {
            room: {
                totalNum: 0,
                group: '',
                mapId: '',
                creatorId: '',
                creator: {
                    nickName: ''
                },
                permissionRest: 0,
                permissionNum: 0,
                state: ''
            },
            userMap: [],
            members: [],
            stationList: [],
            standList: [],
            doorList: [],
            timer: null
        };
    },
    computed: {
        height() {
            return this.$store.state.app.height - 100;
        },
        group() {
            return this.$route.query.group;
        },
        userId() {
            return this.$store.state.user ? this.$store.state.user.id : '';
        }
    },
    watch: {
        members: {
            deep: true,
            handler() {
                this.room.permissionRest = this.members.filter(elem => ['Audience'].includes(elem.userRole)).length;
            }
        },
        // 用户信息
        '$store.state.socket.roleList': async function (val) {
            if (val.length) {
                await this.dispatchUsers(val);
            }
        },
        // 房间消息
        '$store.state.socket.jointRoomInfo': async function (val) {
            if (val.creatorId) {
                await this.dispatchRoomInfo(val);
            }
        },
        // 设备信息
        '$store.state.socket.realDeviceInfo': async function (val) {
            await this.getStandList();
        },
        // 路由切换
        '$route': async function() {
            await this.loadInit();
        }
    },
    async created() {
        await this.loadInit();
    },
    methods: {
        async loadInit() {
            await this.getRoomInfo();
            await this.getUserList();
            await this.getStandList();
            await this.getStaionList(this.room.mapId);
            await this.getDoorList(this.room.mapId, this.stationList);
            if (this.timer) { clearInterval(this.timer); }
            this.timer = setInterval(() => {
                checkLoginLine();
            }, 5000 * 60);
        },
        async getRoomInfo() {
            const resp = await postRoomDetail(this.group);
            this.room = {
                permissionRest: 0,
                totalNum: Number(resp.data.permissionNum) + Number(resp.data.audiencePermissionNum),
                ...resp.data || {}
            };
        },
        async getStandList() {
            const resp = await getRealDevices(this.group);
            this.standList = resp.data || [];
        },
        async getStaionList(mapId) {
            const resp = await getStationList(mapId);
            this.stationList = resp.data || [];
        },
        async getDoorList(mapId, stationList) {
            const doorList = [];
            hasDoorStationList(mapId).then(res =>{
                stationList.forEach(item => {
                    res.data.forEach(it =>{
                        if (item.code === it.stationCode) {
                            const direction = parseInt(it.doorLocationType) % 2 === 0 ? this.$t('trainRoom.uplinkPlatform') : this.$t('trainRoom.downlinkPlatform');
                            doorList.push({code: it.code, name: item.name + direction});
                        }
                    });
                });
                this.doorList = doorList;
            }).catch(() => {
                this.$messageBox(this.$t('error.getScreenDoorsListFailed'));
            });
        },
        async getUserList() {
            const res = await getJointTrainRoomUserList(this.group);
            this.members = (res.data || []).map(elem => { return this.transformUser(elem); });
        },
        async dispatchUsers(users) {
            users.forEach(user => {
                const index = this.members.findIndex(elem => { return user.id == elem.id; });
                if (user.userRole) {
                    if (index >= 0) {
                        this.checkUserState(user, this.members[index]);
                        this.members.splice(index, 1, this.transformUser(user));
                    } else {
                        this.checkUserState(user, null);
                        this.members.push(this.transformUser(user));
                    }
                } else {
                    this.checkUserState(user, this.members[index]);
                    this.members.splice(index, 1);
                }
            });
        },
        async dispatchRoomInfo(room) {
            Object.assign(this.room, room);
            switch (room.state) {
            case '03': // 房间销毁
                this.$router.go(-1);
                break;
            case '02': // 开始仿真
                await this.jumpInSimulation();
                break;
            }

            // 清空房间信息
            this.$store.dispatch('socket/setJointRoomInfo');
        },
        async checkUserState(user, old) {
            const message = {
                join: true,
                id: user.id,
                userName: user.nickName,
                userRole: user.userRole,
                name: user.name,
                roomTip: '',
                chatInfo: true,
                inSimulation: user.inSimulation,
                inRoom: user.inRoom,
                session: 'session',
                oneself: user.id === this.$store.state.user.id
            };

            if (old) {
                if (!user.userRole) {
                    this.$store.dispatch('socket/setChatContent', {...message, roomTip: `${user.nickName}被提出房间`});
                    if (this.userId == user.id) {
                        await this.jumpOutRoom();
                    }
                } else if (old.userRole) {
                    if (old.inRoom && !user.inRoom) {
                        this.$store.dispatch('socket/setChatContent', {...message, roomTip: `${user.nickName}离线`});
                        if (this.userId == user.id) {
                            await this.jumpOutRoom();
                        }
                    }

                    if (!old.inRoom && user.inRoom) {
                        this.$store.dispatch('socket/setChatContent', {...message, roomTip: `${user.nickName}在线`});
                    }

                    if (!old.inSimulation && user.inSimulation) {
                        this.$store.dispatch('socket/setChatContent', {...message, roomTip: `${user.nickName}进入仿真`});
                        if (this.userId == user.id) {
                            await this.jumpInSimulation();
                        }
                    }
                }
            } else {
                this.$store.dispatch('socket/setChatContent', {...message, roomTip: `${user.nickName}进入房间`});
            }
        },
        async jumpInSimulation() {
            const room = this.room;
            await putJointTrainingSimulationEntrance(room.group);
            const rest = await getPublishMapInfo(room.mapId);
            const query = { lineCode: rest.data.lineCode, mapId: room.mapId, group: room.group, roomId: room.id };
            if (this.$route.query.drawWay) {
                this.$router.replace({ path: `/jointTrainingNew`, query: query});
            } else {
                this.$router.replace({ path: `/jointTraining`, query: query });
            }
            // 清空房间信息
            this.$store.dispatch('socket/setJointRoomInfo');
            launchFullscreen();
        },
        async jumpOutRoom() {
            this.$router.go(-1);
            this.messageInfo({error: 'warning', message: this.$t('tip.beKickedOut')});
        },
        transformUser(user) {
            // 根据用户角色专用数据数据
            switch (user.userRole) {
            case 'IBP':
                user.deviceCode = [user.deviceCode || '', user.ibpPart || ''];
                break;
            }

            return user;
        },
        messageInfo(info) {
            this.$message({ showClose: true, ...info });
        }
    }
};
</script>

<style scoped lang="scss">
	.room {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background: #f0f0f0;

		&__head {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			background: #000;
			color: #fff;
			padding: 10px;
			position: relative;

			&--title {
				font-size: 22px;
				font-weight: bold;
			}

			&--notes {
				position: absolute;
				left: 10px;
				bottom: 5px;
			}
		}

		&__container {
			display: flex;
			flex-grow: 1;
			padding: 10px;

			&--members {
				flex-shrink: 1;
				flex-grow: 1;
			}

			&--roles {
				flex-grow: 5;
				flex-shrink: 5;
			}

			&--chat {
				flex-basis: 360px;
			}
		}

		&__footer {
			height: 20px;
		}

	}
</style>
