<template>
    <div class="create">
        <van-form @submit="submit">
            <van-cell-group :border="false">
                <van-field name="游戏区" label="游戏区" :border="false">
                    <template #input>
                        <div class="tabs">
                            <div class="tab" :class="{ prim: form.zone === 'QQ' }" @click="form.zone = 'QQ'">QQ区</div>
                            <div class="tab" :class="{ prim: form.zone === '微信' }" @click="wait">微信区</div>
                        </div>
                    </template>
                </van-field>
            </van-cell-group>
            <van-cell-group :border="false">
                <van-field
                    v-model="form.mode"
                    is-link
                    readonly
                    :border="false"
                    name="对战模式"
                    label="对战模式"
                    placeholder="点击选择对战模式"
                    @click="picker('modeId')"
                >
                </van-field>
                <van-field
                    v-model="form.requireTicketLabel"
                    is-link
                    readonly
                    :border="false"
                    name="通行证类型"
                    label="通行证类型"
                    placeholder="点击选择通行证类型"
                    @click="picker('requireTicket')"
                >
                </van-field>
            </van-cell-group>
            <van-cell-group :border="false">
                <van-field
                    v-model="form.gameMap"
                    is-link
                    readonly
                    :border="false"
                    name="赛事地图"
                    label="赛事地图"
                    placeholder="点击选择赛事地图"
                    @click="picker('gameMapId')"
                />
                <van-field :border="false" name="是否使用密码" label="是否使用密码">
                    <template #input>
                        <van-radio-group v-model="form.usedPsd" direction="horizontal">
                            <van-radio :name="true">是</van-radio>
                            <van-radio :name="false">否</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
                <van-field
                    v-model="form.password"
                    :border="false"
                    v-if="form.usedPsd"
                    name="房间密码"
                    label="房间密码"
                    placeholder="请输入房间密码"
                />
            </van-cell-group>

            <van-cell-group :border="false">
                <van-cell
                    title="填写游戏地址"
                    :border="false"
                    is-link
                    value="查看建房说明"
                    :to="{ path: '/roomDes' }"
                />
                <van-field
                    v-model="form.url"
                    name="游戏地址"
                    rows="4"
                    autosize
                    :border="false"
                    label-width="0"
                    type="textarea"
                    placeholder="请输入游戏中创建的游戏地址"
                />
            </van-cell-group>

            <div class="tips">
                <div>注意事项</div>
                <div>游戏地址必须填写，这样才能开始游戏～</div>
            </div>
            <div class="bottom">
                <van-button round block type="primary" native-type="submit">确认创建</van-button>
            </div>
        </van-form>
        <van-overlay :show="showPicker" z-index="99" @click="showPicker = false">
            <div class="picker" @click.stop>
                <div class="picker-title">{{ pickerTitle }}</div>
                <div class="selects" :class="{ selectOnly: pickerOptions.length === 1 }">
                    <div
                        class="select"
                        :class="{ prim: pickerValue === item.value, not: item.needAudit }"
                        v-for="(item, index) in pickerOptions"
                        :key="index"
                        @click="choosePicker(item.value, item.needAudit)"
                    >
                        {{ item.label }}

                        <img src="@assets/ong-weikaiqi.png" v-if="item.needAudit" class="not-img" alt="" />
                    </div>
                </div>
            </div>
        </van-overlay>
    </div>
</template>

<script>
import room from '../mixins/room.js';
export default {
    name: 'roomCreate',
    inject: ['setKeeps', 'scrollWrapper', 'changeScroll'],
    data() {
        return {
            form: {
                type: 'USER',
                zone: 'QQ',
                usedPsd: false,
                url: '',
                modeId: '',
                mode: '',
                requireTicket: '',
                requireTicketLabel: '',
                gameId: '',
                gameMapId: '',
                gameMap: '',
                password: '',
                maxPlayerNum: '',
                minPlayerNum: ''
            },
            showPicker: false,
            pickerType: 'modeId',
            modeIdOptions: [],
            gameMapIdOptions: [],
            scrollTop: 0
        };
    },
    mixins: [room],
    computed: {
        pickerOptions() {
            if (this.pickerType === 'modeId') {
                return [...this.modeIdOptions];
            }
            if (this.pickerType === 'requireTicket') {
                return [...this.requireTicketOptions];
            }
            if (this.pickerType === 'gameMapId') {
                return [...this.gameMapIdOptions];
            }
            return [];
        },
        pickerValue() {
            if (this.pickerType === 'gameMapId') {
                return Number(this.form.gameMapId || 0);
            }
            if (this.pickerType === 'requireTicket') {
                return this.form.requireTicket;
            }
            return Number(this.form.modeId || 0);
        },
        pickerTitle() {
            if (this.pickerType === 'gameMapId') {
                return '选择赛事地图';
            }
            if (this.pickerType === 'requireTicket') {
                return '选择通行证类型';
            }
            return '选择对战模式';
        }
    },
    mounted() {
        this.$http.get('/sysConfig/get/can_audit');
        this.$http
            .post('/gameMode/all', { size: 1000, query: { del: false } }, { body: 'json' })
            .then(res => {
                this.modeIdOptions = res.content.map(item => {
                    return {
                        label: item.name,
                        value: item.id,
                        minPlayerNum: item.minPlayerNum,
                        maxPlayerNum: item.maxPlayerNum,
                        gameId: item.gameId,
                        needAudit: item.needAudit
                    };
                });
            })
            .catch(e => {
                console.log(e);
                this.$toast(e.error);
            });
    },
    methods: {
        submit() {
            if (!this.form.url) {
                this.$toast('游戏地址必须填写，这样才能开始游戏');
                return;
            }
            if (!this.form.modeId) {
                this.$toast('请选择对战模式');
                return;
            }
            if (!this.form.requireTicket) {
                this.$toast('请选择通行证类型');
                return;
            }
            if (!this.form.gameMapId) {
                this.$toast('请选择赛事地图');
                return;
            }

            this.checkTicket().then(ticketId => {
                this.$toast.loading({
                    message: '加载中...',
                    forbidClick: true
                });
                let form = { ...this.form };
                form.userId = this.$store.state.userInfo.id;
                delete form.usedPsd;
                delete form.mode;
                delete form.gameMap;
                delete form.requireTicketLabel;
                console.log(form);

                this.$http
                    .post('/room/createRoom', {
                        gameId: this.form.gameId,
                        modeId: this.form.modeId,
                        mapId: this.form.gameMapId,
                        ticketId: ticketId,
                        url: this.form.url,
                        password: this.form.password,
                        zone: this.form.zone
                    })
                    .then(res => {
                        this.$toast.clear();
                        this.$toast.success('创建成功');
                        setTimeout(() => {
                            this.$router.replace({
                                path: '/room',
                                query: {
                                    id: res.id
                                }
                            });
                        }, 1000);
                    })
                    .catch(e => {
                        console.log(e);
                        this.$toast(e.error);
                    });
            });
        },
        checkTicket() {
            this.$toast.loading({
                message: '加载中...',
                forbidClick: true
            });
            return this.$http
                .post(
                    '/userTicket/my',
                    {
                        query: {
                            type: this.form.requireTicket,
                            used: false,
                            expired: false
                        },
                        sort: 'id,asc'
                    },
                    { body: 'json' }
                )
                .then(res => {
                    let info = res;
                    this.$toast.clear();
                    if (res.empty) {
                        return this.$dialog
                            .confirm({
                                title: '提示',
                                message: '您没有可用的' + this.form.requireTicketLabel,
                                confirmButtonText: '立即购买'
                            })
                            .then(res => {
                                this.$router.push('/shop?type=buy');
                                return Promise.reject();
                            });
                    } else {
                        return this.$dialog
                            .confirm({
                                title: '门票确认',
                                message: '此操作将扣除您【' + this.form.requireTicketLabel + '】门票一张'
                            })
                            .then(() => {
                                return Promise.resolve(info.content[0].id);
                            });
                    }
                });
        },
        picker(type = 'modeId') {
            if (type === 'gameMapId') {
                if (!this.form.modeId) {
                    this.$toast('请先选择对战模式');
                    return;
                }
            }
            this.pickerType = type;
            this.showPicker = true;
        },
        getMap() {
            this.$http
                .post('/gameMap/all', { size: 1000, query: { del: false, modeId: this.form.modeId } }, { body: 'json' })
                .then(res => {
                    this.gameMapIdOptions = res.content.map(item => {
                        return {
                            label: item.name,
                            value: item.id
                        };
                    });
                })
                .catch(e => {
                    console.log(e);
                    this.$toast(e.error);
                });
        },
        choosePicker(id, needAudit = false) {
            if (needAudit) {
                this.wait();
                return;
            }
            if (this.pickerType == 'modeId') {
                let info = [...this.modeIdOptions].find(item => {
                    return item.value === id;
                });
                this.form.modeId = id;
                this.form.mode = info.label;
                this.form.minPlayerNum = info.minPlayerNum;
                this.form.maxPlayerNum = info.maxPlayerNum;
                this.form.gameId = info.gameId;
                this.form.gameMapId = '';
                this.form.gameMap = '';
                this.getMap();
            }
            if (this.pickerType == 'requireTicket') {
                this.form.requireTicket = id;
                this.form.requireTicketLabel = this.getLabelName(this.form.requireTicket, this.requireTicketOptions);
            }
            if (this.pickerType == 'gameMapId') {
                this.form.gameMapId = id;
                this.form.gameMap = this.getLabelName(this.form.gameMapId, this.gameMapIdOptions);
            }
            this.showPicker = false;
        }
    },
    activated() {
        this.$nextTick(() => {
            this.changeScroll(this.scrollTop || 0);
        });
    },
    beforeRouteLeave(to, from, next) {
        if (to.path === '/shop' || to.path === '/roomDes') {
            this.scrollTop = this.scrollWrapper.scrollTop;
            this.setKeeps(['roomCreate']);
        } else {
            this.scrollTop = 0;
            this.setKeeps(['roomCreate'], false);
        }
        next();
    }
};
</script>

<style lang="less" scoped>
.create {
    .bottom(56px);
}
@bg: #08080d;
.picker {
    width: 272px;
    background-color: @bg;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -136px;
    margin-top: -97px;
    .flex-col();
    justify-content: center;
    z-index: 20;
    &::after {
        content: '';
        background: linear-gradient(-225deg, #f6abf0 0%, #10f7ee 100%);
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 0;
        border-radius: 2px;
    }
    &::before {
        content: '';
        background-color: @bg;
        z-index: 1;
        position: absolute;
        left: 1px;
        top: 1px;
        right: 1px;
        bottom: 1px;
        border-radius: 2px;
    }

    & > div {
        position: relative;
        z-index: 2;
    }

    .picker-title {
        font-size: 20px;
        color: #fff;
        font-weight: bold;
        text-align: center;
        padding-top: 20px;
    }
    .selects {
        .flex();
        flex-wrap: wrap;
        padding: 15px;
        .select {
            width: calc(50% - 30px);
            height: 32px;
            background-color: @bg2;
            margin: 8px 15px;
            text-align: center;
            line-height: 32px;
            border-radius: 4px;
            color: #6a6d83;
            &.prim {
                background: linear-gradient(225deg, #f6abf0 0%, #10f7ee 100%);
                color: #1a1c2b;
            }

            &.not {
                position: relative;
                color: #6a6d8366;
                .not-img {
                    width: 42px;
                    height: 28px;
                    position: absolute;
                    right: 4px;
                    top: 0;
                }
            }
        }
        &.selectOnly {
            justify-content: center;
        }
    }
}
.van-form {
    padding: 16px;
}
.van-cell-group {
    background: #25283d;
    border-radius: 4px;
    overflow: hidden;
    padding: 8px 0;
}
.van-cell-group + .van-cell-group {
    margin-top: 16px;
}

/deep/.van-field__label,
/deep/.van-cell__title {
    color: #ffffff;
    margin-right: 22px;
}

.tabs {
    .flex();
    background: rgba(255, 255, 255, 0.1);
    border-radius: 2px;
    font-size: 12px;
    color: #6a6d83;
    line-height: 18px;
    overflow: hidden;
    .tab {
        width: 52px;
        text-align: center;
        &.prim {
            background: linear-gradient(-225deg, #f6abf0 0%, #10f7ee 100%);
            color: #1a1c2b;
        }
    }
}
/deep/.van-radio__label {
    color: #fff;
}
/deep/.van-radio__icon--checked .van-icon {
    border-width: 0;
    background: linear-gradient(-225deg, #f6abf0 0%, #10f7ee 100%);
    color: #1a1c2b;
}

.tips {
    font-size: 12px;
    color: #6a6d83;
    line-height: 17px;
    margin-top: 20px;
    div + div {
        margin-top: 6px;
    }
}
.van-cell {
    padding: 8px 16px;
}
.bottom {
    position: fixed;
    z-index: 20;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 9px 28px;
    .bottom(9px);
}
</style>
