<template>
    <uv-popup ref="popup" :round="30">
        <view class="comment-publish">
            <view class="content-input">
                <uv-textarea v-model="form.userValue" :maxlength="200" autoHeight count focus
                    :placeholder="placeholder"></uv-textarea>
            </view>

            <view class="images box">
                <uv-upload :fileList="fileList" :maxCount="imageMax" multiple width="150rpx" height="150rpx"
                    @delete="deleteImage" @afterRead="afterRead" :previewFullImage="true"></uv-upload>
            </view>

            <view class="uni-color-btn" @click="submit">
                发布
            </view>
        </view>
    </uv-popup>
</template>

<script>
export default {
    name: 'CommentPublish',
    props: {
        // 评论参数
        params: {
            type: Object,
            default: () => ({})
        },
        // 输入框占位符
        placeholder: {
            type: String,
            default: '说点什么吧...'
        }
    },
    data() {
        return {
            form: {
                userValue: ''
            },
            imageMax: 9,
            fileList: [],
        }
    },
    methods: {
        // 打开弹窗
        open() {
            this.$refs.popup.open('bottom')
        },

        // 关闭弹窗
        close() {
            this.$refs.popup.close()
        },

        async submit() {
            await this.onSubscribeMessageTap()

            let data = {
                ...this.form,
                ...this.params,
            }

            if (this.$utils.verificationAll(data, {
                userValue: '说点什么吧',
                type: '缺少type',
                orderId: '缺少orderId',
            })) {
                return
            }

            data.userImage = this.fileList.map((item) => item.url).join(",")

            this.$api('addComment', data, res => {
                if (res.code == 200) {
                    this.close()
                    this.resetForm()
                    uni.showToast({
                        title: '发布成功!',
                        icon: 'none'
                    })
                    this.$emit('success')
                }
            })
        },

        // 重置表单
        resetForm() {
            this.form.userValue = ''
            this.fileList = []
        },

        deleteImage(e) {
            this.fileList.splice(e.index, 1)
        },

        afterRead(e) {
            let self = this
            e.file.forEach(file => {
                self.$Oss.ossUpload(file.url).then(url => {
                    self.fileList.push({
                        url
                    })
                })
            })
        },

        //订阅模版消息
        onSubscribeMessageTap() {
            return new Promise((resolve, reject) => {
                let templateIds = [
                    'uXZnHWrjtcX9JHlnMpdlWmzgJp71sKxCRiMn3TrE-EE',
                    'gTzGpOfJcYxtbvPG9OHnhbureKz5XLG8NPyECUGb2lw',
                ];
                wx.requestSubscribeMessage({
                    tmplIds: templateIds, // 需要订阅的模板ID列表
                    success(res) {
                        resolve(res)
                        console.log('订阅消息调用成功', res);
                        // res[tmplId] 表示用户是否同意订阅该模板ID对应的消息
                        // 例如：res['your_template_id_1'] === 'accept' 表示用户同意订阅
                        templateIds.forEach(tmplId => {
                            if (res[tmplId] === 'accept') {
                                console.log(`用户同意订阅模板ID：${tmplId}`);
                                // 这里可以添加用户同意后的逻辑，比如发送消息等（注意：发送消息需要在后端进行）
                            } else if (res[tmplId] === 'reject') {
                                console.log(`用户拒绝订阅模板ID：${tmplId}`);
                            } else {
                                console.log(`用户对该模板ID的订阅请求：${res[tmplId]}`); // 'ban' 表示用户被禁止订阅该模板
                            }
                        });
                    },
                    fail(err) {
                        resolve(res)
                        console.error('订阅消息调用失败', err);
                    }
                });
            })
        },
    }
}
</script>

<style scoped lang="scss">
.comment-publish {
    .content-input {
        min-height: 400rpx;
    }

    .box {
        padding: 0 20rpx;
    }

    .images {
        display: flex;
        flex-wrap: wrap;
        padding: 20rpx;
    }

    .uni-color-btn {
        background-color: $uni-color-primary;
        color: #fff;
        text-align: center;
        padding: 20rpx;
        margin: 20rpx;
        border-radius: 10rpx;
        font-size: 32rpx;
    }
}
</style>