<template>
    <view class="apply">
        <u-avatar :src="group.cover" size="128" shape="square"></u-avatar>
        <view class="name">
            {{ group.name }}
        </view>

        <u-button v-if="group.can_join" @click="applyGroup" text="申请加群" :disabled="disabled" color="#34CE98" />
        <view class="" v-else>
            <view class="" v-if="group.is_full">群已满员</view>
            <view class="" v-if="group.deny_apply">禁止申请</view>
            <u-button v-if="group.state === 'accepted'" color="#34CE98" text="进入群聊" @click="toGroupChat" />
        </view>

        <u-modal negativeTop="300" :show="modalShow" title="申请原因" showCancelButton @cancel="onHideModal"
            @confirm="onJoinGroup">
            <view class="slot-content">
                <u--input placeholder="申请原因" border="surround" focus v-model="message"></u--input>
            </view>
        </u-modal>
    </view>
</template>

<script>
    import {
        joinGroupPre,
        joinGroup
    } from '@/apis/interfaces/im.js'

    export default {
        data() {
            return {
                targetId: '',
                group: {},
                modalShow: false,
                message: '',
                disabled: false
            }
        },
        onLoad(e) {
            this.targetId = e.targetId
            joinGroupPre(this.targetId).then(res => {
                console.log(res);
                this.group = res
            })
        },
        methods: {
            toGroupChat() {
                uni.redirectTo({
                    url: '/pages/im/group/chat?targetId=' + this.targetId
                })
            },
            applyGroup() {
                this.modalShow = true
            },
            onHideModal() {
                this.message = ''
                this.modalShow = false
            },
            onJoinGroup() {
                joinGroup(this.targetId, this.message).then(res => {
                    console.log('申请结果', res);
                    uni.showToast({
                        icon: 'none',
                        title: '申请成功'
                    })
                }).catch(err => {
                    uni.showToast({
                        icon: 'none',
                        title: err.message
                    })
                })
                this.disabled = true
                this.onHideModal()
            }
        }
    }
</script>

<style lang="scss" scoped>
    .apply {
        display: flex;
        flex-direction: column;
        align-items: center;

        .u-avatar {
            width: 200rpx;
            height: 200rpx;
        }
    }
</style>
