<template>
    <div class="room">
        <div class="bg">
            <img src="@assets/roomBg.png" alt="" />
        </div>

        <!-- <div class="back">
            <img src="@assets/back.png" @click="back" alt="" />
        </div> -->
        <van-pull-refresh
            class="home"
            success-text="加载成功"
            success-duration="500"
            v-model="isLoading"
            :head-height="80"
            @refresh="onRefresh"
            pageType="light"
        >
            <div class="content">
                <div class="content-top">
                    <div class="text1">{{ getLabelName(info.status, statusOptions) }}</div>
                    <div class="text2">
                        <span>房间号 {{ info.id }}</span>
                        <img src="@assets/png-copy.png" @click="copy(info.id)" alt="" />
                    </div>
                </div>
                <div class="content-box">
                    <div class="tabs">
                        <div class="tab">{{ info.zone }}</div>
                        <div class="tab">{{ gameMode.name }}</div>
                        <div class="tab">{{ getLabelName(info.requireTicket, requireTicketOptions) }}</div>
                        <div class="tab">{{ gameMap.name }}</div>
                    </div>

                    <div class="player-content">
                        <div class="players">
                            <div class="player-item">
                                <div class="title">主队</div>
                                <div class="list1" v-if="info.maxPlayerNum === 2">
                                    <van-image
                                        width="58"
                                        height="58"
                                        radius="4"
                                        :src="host.avatar || require('@assets/img_default_photo.png')"
                                        fit="cover"
                                    />
                                    <div class="name">{{ host.nickname }}</div>
                                </div>
                                <div class="list" v-else>
                                    <div class="person" v-for="(item, index) in hosts" :key="index">
                                        <van-image
                                            width="24"
                                            height="24"
                                            radius="4"
                                            :src="item.avatar || require('@assets/img_default_photo.png')"
                                            fit="cover"
                                        />
                                        <div class="name">{{ item.nickname }}</div>
                                    </div>
                                </div>
                            </div>
                            <div class="player-item">
                                <div class="title">客队</div>
                                <template v-if="info.maxPlayerNum === 2">
                                    <div class="list1 not" v-for="(item, index) in guests" :key="index">
                                        <van-image
                                            width="58"
                                            height="58"
                                            radius="4"
                                            :src="item.avatar || require('@assets/img_default_photo.png')"
                                            fit="cover"
                                        />
                                        <div class="name">{{ item.nickname }}</div>
                                    </div>
                                </template>
                                <div class="list" v-else>
                                    <div class="person" v-for="(item, index) in guests" :key="index">
                                        <van-image
                                            width="24"
                                            height="24"
                                            radius="4"
                                            :src="item.avatar || require('@assets/img_default_photo.png')"
                                            fit="cover"
                                        />
                                        <div class="name">{{ item.nickname }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="bg-icon" :class="{ bgOne: info.maxPlayerNum === 2 }">
                        <img src="@assets/png-1v1-bg.png" v-if="info.maxPlayerNum === 2" class="img1" alt="" />
                        <img
                            src="@assets/png-2v2～5v5-bg.png"
                            :style="{ height: teamHeight + 'px' }"
                            v-else
                            class="img3"
                            alt=""
                        />
                        <img src="@assets/png-vs.png" alt="" class="img2" />
                    </div>
                </div>
            </div>

            <div class="help">
                <div class="help-btn" v-if="isJoin && !isHost && info.status == 'GAMING'" @click="quit">
                    <img src="@assets/png-tuichu.png" alt="" />
                    <span>退出</span>
                </div>
                <div class="help-btn" v-if="isHost && info.status == 'GAMING'" @click="$refs.failed.init()">
                    <img src="@assets/png-liuju.png" alt="" />
                    <span>流局</span>
                </div>
                <div class="help-btn" @click="$refs.description.init()">
                    <img src="@assets/png-shuoming.png" alt="" />
                    <span>说明</span>
                </div>
            </div>

            <div class="bottom" v-if="isJoin">
                <div
                    class="join-btn"
                    v-if="isFull && ((info.status == 'WAITING' && isHost) || info.status == 'GAMING')"
                >
                    <van-button type="primary" v-if="info.status == 'WAITING' && isHost" block @click="start"
                        >开始比赛</van-button
                    >
                    <van-button type="primary" v-else-if="info.status == 'GAMING'" block @click="goGame"
                        >进入比赛</van-button
                    >
                </div>
                <div class="btns">
                    <div class="btn" v-if="!isHost && info.status == 'WAITING'" @click="quit">
                        <img src="@assets/png-quxiaobaoming.png" alt="" />
                        <span>取消报名</span>
                    </div>
                    <div
                        class="btn"
                        @click="changeUrl"
                        v-if="isHost && (info.status == 'WAITING' || info.status == 'GAMING')"
                    >
                        <img src="@assets/png-xiugaidizhi.png" alt="" />
                        <span>修改地址</span>
                    </div>
                    <div
                        class="btn"
                        v-if="info.status == 'FINISH'"
                        @click="$router.push('/roomResult?roomId=' + roomId)"
                    >
                        <img src="@assets/png-xiugaidizhi.png" alt="" />
                        <span>查看战绩</span>
                    </div>
                    <div class="btn" @click="$router.push('/reportAdd?roomId=' + roomId)">
                        <img src="@assets/png-yicangshenbao.png" alt="" />
                        <span>异常申报</span>
                    </div>
                    <div
                        class="btn"
                        v-if="isHost && (info.status == 'WAITING' || info.status == 'GAMING')"
                        @click="cancel"
                    >
                        <img src="@assets/png-quxiaosaishi.png" alt="" />
                        <span>取消赛事</span>
                    </div>
                    <div
                        class="btn"
                        v-if="info.status == 'GAMING' || info.status == 'AUDIT'"
                        @click="$refs.result.init()"
                    >
                        <img src="@assets/png-jieshubisai.png" alt="" />
                        <span>结束比赛</span>
                    </div>
                </div>
            </div>
        </van-pull-refresh>
        <change-url ref="url" :roomId="roomId"></change-url>
        <join-room ref="join" :roomInfo="info" @update="getInfo"></join-room>
        <description ref="description"></description>
        <failed ref="failed"></failed>
        <player-info ref="player" :roomInfo="info"></player-info>
        <join-game ref="joinGame" :roomInfo="info"></join-game>
        <result ref="result" :roomId="roomId" @update="getInfo"></result>
    </div>
</template>

<script>
import room from '../mixins/room.js';
import changeUrl from '../components/room/changeUrl.vue';
import joinRoom from '../components/room/joinRoom.vue';
import joinGame from '../components/room/joinGame.vue';
import description from '../components/room/description.vue';
import failed from '../components/room/failed.vue';
import playerInfo from '../components/room/playerInfo.vue';
import result from '../components/room/result.vue';
export default {
    data() {
        return {
            info: {},
            roomId: 0,
            timer: null
        };
    },
    computed: {
        gameMap() {
            return this.info.gameMap || {};
        },
        gameMode() {
            return this.info.gameMode || {};
        },
        host() {
            return this.info.host || {};
        },
        players() {
            return this.info.players || [];
        },
        hosts() {
            let list = [...this.players].filter(item => {
                return item.team === 'host' && !item.host;
            });

            list.splice(0, 0, this.host);

            for (let i = list.length; i < this.info.maxPlayerNum / 2; i++) {
                list.push({
                    nickname: '匹配中...',
                    avatar: require('@assets/png-pipeizhong.png')
                });
            }
            return list;
        },
        guests() {
            let list = [...this.players].filter(item => {
                return item.team === 'guest';
            });
            for (let i = list.length; i < this.info.maxPlayerNum / 2; i++) {
                list.push({
                    nickname: '匹配中...',
                    avatar: require('@assets/png-pipeizhong.png')
                });
            }
            return list;
        },
        isHost() {
            return this.host.userId === this.$store.state.userInfo.id;
        },
        isJoin() {
            if (this.isHost) {
                return true;
            }
            let info = [...this.players].find(item => {
                return item.userId === this.$store.state.userInfo.id;
            });
            return !!info;
        },
        isFull() {
            return this.players.length === this.info.maxPlayerNum;
        },
        teamHeight() {
            return (this.info.maxPlayerNum / 2) * 43 + 12;
        }
    },
    mixins: [room],
    components: { changeUrl, joinRoom, description, failed, playerInfo, joinGame, result },
    mounted() {
        if (this.$route.query.id) {
            this.roomId = this.$route.query.id;
        }
        this.$toast.loading({
            message: '加载中...',
            forbidClick: true
        });
        this.getInfo();
    },
    methods: {
        copy(text) {
            this.$copyText(JSON.stringify(text)).then(
                e => {
                    this.$toast.success('复制成功');
                    console.log(e);
                },
                e => {
                    this.$toast('复制失败');
                    console.log(e);
                }
            );
        },
        getInfo() {
            return this.$http
                .get('/room/detail/' + this.roomId)
                .then(res => {
                    this.$toast.clear();
                    this.info = res;
                    if (!this.isFull && !this.isJoin && res.status === 'WAITING') {
                        this.$refs.join.init();
                    } else if (!this.isJoin && this.isFull) {
                        this.$dialog
                            .alert({ title: '匹配成功', message: '房间已经满员啦，选择其他房间加入吧！' })
                            .then(() => {
                                this.$router.go(-1);
                            });
                    } else if (!this.isJoin && res.status !== 'WAITING') {
                        this.$dialog
                            .alert({ title: '提示', message: '比赛已经开始了，选择其他房间加入吧！' })
                            .then(() => {
                                this.$router.go(-1);
                            });
                    } else {
                        this.loop();
                    }
                })
                .catch(e => {
                    if (e && e.error) {
                        this.$toast(e.error);
                    }
                });
        },
        loop() {
            if (this.timer) {
                clearTimeout(this.timer);
                this.timer = null;
            }

            this.timer = setTimeout(() => {
                if (this.info.status === 'WAITING' || this.info.status === 'GAMING') {
                    this.getInfo().then(() => {
                        this.loop();
                    });
                }
            }, 2000);
        },
        changeUrl() {
            this.$refs.url.init(this.info.url);
        },
        back() {
            this.$router.back();
        },
        choosePerson(info) {
            if (this.isHost) {
                this.$refs.player.init();
            }
        },
        quit() {
            this.$dialog
                .confirm({
                    title: '提示',
                    message: '确认要取消报名吗？',
                    confirmButtonText: '立即取消'
                })
                .then(() => {
                    this.$toast.loading({
                        message: '加载中...',
                        forbidClick: true
                    });
                    return this.$http.post('/room/quit', {
                        roomId: this.roomId
                    });
                })
                .then(() => {
                    this.$toast.success('取消成功');
                    setTimeout(() => {
                        this.back();
                    }, 1000);
                })
                .catch(e => {
                    if (e && e.error) {
                        this.$toast(e.error);
                    }
                });
        },
        cancel() {
            this.$dialog
                .confirm({
                    title: '提示',
                    message: '确认要取消赛事吗?',
                    confirmButtonText: '立即取消'
                })
                .then(() => {
                    this.$toast.loading({
                        message: '加载中...',
                        forbidClick: true
                    });
                    return this.$http.post('/room/cancel', {
                        roomId: this.roomId
                    });
                })
                .then(() => {
                    this.$toast.success('取消成功');
                    setTimeout(() => {
                        this.back();
                    }, 1000);
                })
                .catch(e => {
                    if (e && e.error) {
                        this.$toast(e.error);
                    }
                });
        },
        start() {
            this.$dialog
                .confirm({
                    title: '提示',
                    message: '确认要开始比赛吗？',
                    confirmButtonText: '立即开始'
                })
                .then(() => {
                    this.$toast.loading({
                        message: '加载中...',
                        forbidClick: true
                    });
                    return this.$http.post('/room/startGame', {
                        roomId: this.roomId
                    });
                })
                .then(() => {
                    this.getInfo();
                })
                .catch(e => {
                    if (e && e.error) {
                        this.$toast(e.error);
                    }
                });
        },
        goGame() {
            window.location.href = this.info.url;
            // this.$refs.joinGame.init()
        },
        onRefresh() {
            this.getInfo().then(() => {
                this.isLoading = false;
            });
        }
    },
    unmounted() {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
    },
    beforeRouteLeave(to, from, next) {
        if (this && this.emitter) {
            this.emitter.emit('updateList', this.info);
        }
        next();
    }
};
</script>

<style lang="less" scoped>
.room {
    position: relative;
    padding: 100px 16px 0;
    min-height: var(--app-height) !important;
    background: linear-gradient(180deg, #570ea5 0%, #300d77 100%);
    & > div {
        position: relative;
        z-index: 2;
    }

    .bg {
        position: absolute;
        z-index: 0;
    }

    .back {
        position: fixed;
        z-index: 20;
    }
    .bottom {
        position: fixed;
        z-index: 20;
    }
    .help {
        position: fixed;
        z-index: 20;
    }
}
.bg {
    position: absolute;
    z-index: 0;
    top: 0;
    left: 0;
    right: 0;
    img {
        width: 100%;
        display: block;
    }
    &::after {
        position: absolute;
        content: '';
        left: 0;
        right: 0;
        bottom: 0;
        height: 98px;
        background: linear-gradient(180deg, rgba(87, 14, 165, 0) 0%, #4d0e99 100%);
        z-index: 2;
    }
}

.back {
    position: fixed;
    top: var(--safe-top);
    z-index: 20;
    padding: 16px;
    left: 0;
    img {
        width: 24px;
        height: 24px;
    }
}

.content {
    background: linear-gradient(180deg, #541ec1, #1e0470);
    min-height: calc(var(--app-height) - 100px);
    border-radius: 10px;
    .flex-col();
    .content-top {
        padding: 8px 0;
        .flex-col();
        align-items: center;
        .text1 {
            font-size: 18px;
            font-weight: bold;
            color: #ffffff;
            line-height: 24px;
            letter-spacing: 1px;
            text-shadow: 1px 1px 0px #7a24ff;
        }

        .text2 {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.6);
            line-height: 17px;
            margin-top: 2px;
            .flex();
            img {
                width: 16px;
                height: 16px;
                margin-left: 6px;
            }
        }
    }
}
@colorList: #ff988c, #c787ff, #ff87c3, #9587ff;

.content-box {
    .flex-col();
    position: relative;
    padding: 16px 10px;
    flex-grow: 1;
    background: linear-gradient(180deg, #6310b0 0%, #09005c 100%);
    .tabs {
        .flex();
        justify-content: center;
        padding-bottom: 14px;
        flex-shrink: 0;

        .tab {
            height: 18px;
            background: #ff988c;
            border-radius: 2px;
            font-size: 12px;
            color: #ffffff;
            line-height: 18px;
            padding: 0 10px;

            each(range(4), {
                &:nth-child(4n + @{value}) {
                    background:extract(@colorList, @value);
                }
            });
        }
        .tab + .tab {
            margin-left: 12px;
        }
    }

    .bg-icon {
        position: absolute;
        left: 0;
        right: 0;
        top: 104px;
        z-index: 1;
        .img1 {
            width: 100%;
            display: block;
            margin-top: 26px;
        }
        .img2 {
            width: 74px;
            display: block;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        .img3 {
            width: 100%;
            display: block;
        }
        &.bgOne {
            .img2 {
                top: calc(50% + 13px);
            }
        }
    }
}
.player-content {
    flex-grow: 1;
    border-radius: 8px;
    position: relative;
    padding: 16px;
    &::after {
        content: '';
        position: absolute;
        background: linear-gradient(180deg, #6310b0 0%, #09005c 100%);
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        border-radius: 8px;
        z-index: 0;
    }
}
.players {
    .flex();
    justify-content: space-between;
    align-items: stretch;
    position: relative;
    z-index: 2;
    .player-item {
        width: 29vw;
        .title {
            font-size: 14px;
            font-weight: bold;
            color: #ffffff;
            line-height: 18px;
            text-align: center;
            padding: 4px 0 16px;
        }

        .list1 {
            .flex-col();
            align-items: center;
            padding: 4px 0;
            .name {
                margin-top: 6px;
            }
            &.not {
                .name {
                    color: rgba(255, 255, 255, 0.6);
                }
            }
        }
    }
}
.bottom {
    background-color: #0e0042;
    bottom: 0;
    left: 0;
    right: 0;
    .bottom(0px);
    .btns {
        .flex();
        height: 56px;
        padding: 0 16px;
    }

    .btn {
        .flex();
        justify-content: center;
        flex-grow: 1;
        img {
            width: 24px;
            height: 24px;
        }
        span {
            font-size: 14px;
            font-weight: bold;
            color: #ffffff;
            line-height: 24px;
            margin-left: 4px;
        }
    }
    .join-btn {
        padding: 16px 32px 0;
    }
}

.help {
    position: fixed;
    right: 10px;
    bottom: 30vh;
    .flex-col();
    .help-btn {
        width: 44px;
        height: 44px;
        background: #0e0042;
        box-shadow: 0px 2px 6px 0px #421292;
        border-radius: 44px;
        .flex-col();
        align-items: center;
        justify-content: center;
        img {
            width: 24px;
            height: 24px;
        }
        span {
            font-size: 10px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: rgba(255, 255, 255, 0.6);
            line-height: 10px;
        }
    }
    .help-btn + .help-btn {
        margin-top: 24px;
    }
}

.person {
    .flex();
    padding: 10px 0;
    overflow: hidden;
    .van-image {
        flex-shrink: 0;
    }
    .name {
        font-size: 14px;
        font-weight: bold;
        color: #ffffff;
        line-height: 24px;
        margin-left: 6px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    &:first-child {
        padding-top: 16px;
    }

    &:last-child {
        padding-bottom: 16px;
    }
}
</style>
