<template>
    <div>
        <div class="chat-header d-flex">
            <img :src="user.attachments?
            '/files?uid='+user.attachments.uid+'&width=64&height=64':
            '/uploads/img/karshenas.png'" />
            <h5>{{user.fname}} {{user.lname}}</h5>
        </div>
        <div class="chatMain">
            <div v-for="chat in chats">
                <div class="margin-top-10" v-if="id != chat.from">
                    <div class="myChat">
                        <p>{{chat.text}}</p>
                    </div>
                </div>
                <div class="text-left margin-top-10" v-else>
                    <div class="otherChat">
                        <p>{{chat.text}}</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="message-footer">
            <input type="text" class="form-control" placeholder="متن پیام" v-model="message" />
            <button @click="sendMessage">ارسال</button>
        </div>
    </div>
</template>

<script>
    export default {
        props:['id'],
        data(){
            return{
                chats:[],
                userId:null,
                user:{},
                message:'',
            }
        },
        beforeMount(){
            axios.get('/message/show?user_id='+this.id).then(res=>{
                this.chats=res.data.data.message
                this.userId=res.data.data.userId
            })
            axios.get('/core/get-user?id='+this.id).then(res=>{
                this.user=res.data.data.user
            })
        },
        methods:{
            sendMessage:function () {
                axios.post('/message/store',{to:this.id,text:this.message}).then(res=>{
                    this.chats.reverse()
                    this.chats.push(res.data.data)
                    this.chats.reverse()
                    this.message=''
                    this.forceUpdate()
                })
            }
        }
    }
</script>

