<template>
    <div>
        <scroll-view ref="scrollview" :scroll-y="true" class="scroll" :scroll-into-view="scrollIntoID"
            :scroll-with-animation="false">
            <view v-for="(item,index) in messages" :id="'chatId_'+index">
                <div :class="item.messageDirection == 1 ? 'right' : 'left'">
                    <div class="avatar" v-if="item.messageDirection == 2">
                        <u-avatar :src="userInfo.portraitUrl" @click="showFriend" shape="square" />
                    </div>
                    <div class="msg">
                        {{ item.content.content }}
                        <div class="status" v-if="item.messageDirection == 1">
                            <u-icon v-if="item.sentStatus == 50" name="checkbox-mark" />
                            <span v-else>未读</span>
                        </div>
                    </div>
                    <div class="avatar" v-if="item.messageDirection == 1">
                        <u-avatar text="Me" @click="showMine" shape="square" />
                    </div>
                </div>

                <div class="time">{{ item.sentTime|timeCustomCN }}</div>
            </view>
        </scroll-view>

        <div class="footer">
            <div class="left">
                <u-icon name="volume" />
            </div>
            <div class="middle">
                <u--input autoBlur confirmHold confirmType="send" @confirm="send" v-model="inputTxt" />
            </div>
            <div class="right">
                <u-button type="primary" v-if="showSendButton" class="custom-style" text="发送" @click="send"></u-button>
                <u-icon v-else name="plus" />
            </div>
        </div>
    </div>
</template>

<script>
    import * as RongIMLib from '@rongcloud/imlib-uni'
    import im from '@/utils/im/index.js'

    export default {
        data() {
            return {
                targetId: '',
                scrollIntoID: 'chatID_0',
                inputTxt: '',
                messages: [],
                conversationType: 1,
                totalCount: 0,
                userInfo: {
                    name: '',
                    userId: '',
                    portraitUrl: ''
                }
            }
        },
        onLoad(e) {
            this.targetId = e.targetId
            this.conversationType = e.conversationType // 会话类型
            // 消息总数量
            RongIMLib.getMessageCount(this.conversationType, this.targetId, ({
                code,
                count
            }) => {
                if (code == 0) {
                    this.totalCount = count
                }
            })
            this.userInfo = this.$store.getters.userInfo(this.targetId)
            uni.setNavigationBarTitle({
                title: this.$store.getters.userInfo(this.targetId).name
            })

            RongIMLib.clearMessagesUnreadStatus(this.conversationType, this.targetId, new Date().getTime())
            im.setNotifyBadge()
            RongIMLib.sendReadReceiptMessage(this.conversationType, this.targetId, new Date().getTime())

            this.getMessageList()

            // 监听消息回执
            RongIMLib.addReadReceiptReceivedListener((result) => {
                const res = result.data.message
                if (res.targetId == this.targetId) {
                    this.getMessageList()
                }
            })
        },
        onUnload() {
            RongIMLib.clearReadReceiptReceivedListener()
        },
        computed: {
            showSendButton() {
                return this.inputTxt.length > 0
            }
        },
        onNavigationBarButtonTap(e) {
            if (e.index == 0) {
                uni.navigateTo({
                    url: '/pages/im/private/setting?targetId=' + this.targetId +
                        '&conversationType=' + this.conversationType
                })
            }
        },
        watch: {
            '$store.getters.newMessage': function(msg) {
                if (msg.targetId == this.targetId) {
                    RongIMLib.clearMessagesUnreadStatus(msg.conversationType, msg.targetId, msg.sentTime)
                    RongIMLib.sendReadReceiptMessage(msg.conversationType, msg.targetId, msg.sentTime)
                    this.getMessageList()
                    im.setNotifyBadge()
                }
            }
        },
        methods: {
            getMessageList() {
                // 获取消息列表
                const objectNames = [
                    'RC:TxtMsg',
                    'RC:VcMsg',
                    'RC:HQVCMsg',
                    'RC:ImgMsg',
                    'RC:GIFMsg',
                    'RC:ImgTextMsg',
                    'RC:FileMsg',
                    'RC:LBSMsg',
                    'RC:SightMsg',
                    'RC:ReferenceMsg',
                    'RC:CombineMsg'
                ]
                const timeStamp = new Date().getTime()
                const count = 20 // 获取的消息数量
                const isForward = true // 是否向前获取
                RongIMLib.getHistoryMessagesByTimestamp(this.conversationType, this.targetId, objectNames, timeStamp,
                    count,
                    isForward,
                    ({
                        code,
                        messages
                    }) => {
                        if (code === 0) {
                            this.messages = messages.reverse()
                            this.scrollBottom()
                        }
                    }
                )
            },
            send() {
                im.sendMsg(this.conversationType, this.targetId, this.inputTxt, () => {
                    this.getMessageList()
                    this.inputTxt = ''
                })
            },
            showFriend() {
                uni.navigateTo({
                    url: '/pages/im/friends/info?targetId=' + this.targetId
                })
            },
            showMine() {
                uni.navigateTo({
                    url: '/pages/im/friends/mine'
                })
            },
            scrollBottom() {
                this.$nextTick(function() {
                    setTimeout(() => {
                        let len = this.messages.length
                        if (len) {
                            if (this.scrollIntoID == "chatId_" + (len - 1)) {
                                this.scrollIntoID = "chatId_" + (len - 2)
                                this.scrollBottom()
                            } else if (this.scrollIntoID == "chatId_" + (len - 2)) {
                                this.scrollIntoID = "chatId_" + (len - 1)
                            } else {
                                this.scrollIntoID = "chatId_" + (len - 1)
                            }
                        } else {
                            this.scrollIntoID = "chatId_0";
                        }
                    }, 50)
                })
            }
        }
    }
</script>

<style lang="scss" scoped>
    $footer-height: 55px;

    .scroll {
        height: calc(100vh - 55px);
        width: 100vw;
        padding: 0 $uni-spacing-col-lg;
    }

    .footer {
        width: 100%;
        display: flex;
        position: fixed;
        bottom: 0;
        left: 0;
        align-items: center;
        height: $footer-height;
        background-color: $uni-bg-color-grey;

        .u-icon {
            padding: $uni-spacing-col-sm;
            border: 1px solid $u-content-color;
            border-radius: $uni-border-radius-circle;
        }

        .left {
            padding: 0 $uni-spacing-col-lg;
            justify-content: center;
        }

        .middle {
            flex: 1;

            .u-input {
                background-color: $uni-bg-color;
            }
        }

        .right {
            padding: 0 $uni-spacing-col-lg;
            justify-content: center;
        }
    }

    .custom-style {
        height: 36px;
    }

    .time {
        text-align: center;
        font-size: $uni-font-size-sm;
        color: $u-light-color;
    }

    .left,
    .right {
        display: flex;
        align-items: top;

        .avatar {
            margin-top: $uni-spacing-col-base;
        }

        .msg {
            font-size: $uni-font-size-base;
            margin: $uni-spacing-col-base;
            padding: $uni-spacing-col-base;
            word-wrap: break-word;
            width: 60%;
            border-radius: $uni-border-radius-base;
            position: relative;

            .status {
                position: absolute;
                right: 8rpx;
                bottom: 5rpx;
                font-size: $uni-font-size-base / 1.5;
                color: $uni-text-color-grey;
            }
        }
    }

    .left {
        .msg {
            background-color: $uni-bg-color-grey;
        }
    }

    .right {
        justify-content: flex-end;

        .msg {
            background-color: $u-primary-disabled;
        }
    }
</style>
