// nova-werun/components/circle-card/index.js
const Parse = getApp().Parse;
const company = getApp().globalData.company;
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        objectId: '',
        type: '',
        permission: ''
    },

    /**
     * 组件的初始数据
     */
    data: {
        //图片
        images: [],
        imageclass: '',
        //是否展示点赞评论按钮
        isgood: false,
        isclick: false,
        //朋友圈
        cicleList: [],
        time: '',
        //点赞人
        chickList: '',

        show: false,
        //
        inputValue: '', // 用于存储输入的内容
        textareaHeight: 52, // 初始高度，单位为 rpx
        bottomNavHeight: 0,
        //
        commentList: [],
        //
        poptype: '',
        userobject: '',
        //评论
        commenttext: "评论",
        focusedCommentId: null,
        isCommentFocused: false,
        noCommentCount: 0,
        //
        showconfirm: false,
        //
        maxLength: 110, // 设置最大长度
        showFull: false, // 控制是否显示完整内容

        //
        imgList:[],
        currentImg:'',
        previewHideStatus:false
    },
    lifetimes: {

        detached: function () {
            // 在组件实例被从页面节点树移除时执行
        },
        attached: async function () {
            // 在组件实例进入页面节点树时执行
            this.getcircle()
            this.showischick()
            this.getbottomheight()
            this.getComment()
        },


    },


    /**
     * 组件的方法列表
     */
    methods: {
        onImageLoad: function (e) {
            const {
                width,
                height
            } = e.detail; // 获取图片的宽高
            const imageClass = width > height ? 'image-landscape' : 'image-portrait'; // 判断横竖屏

            this.setData({
                imageclass: imageClass // 动态设置图片的类名
            });
        },
        previewImage: function (e) {
            const index = e.currentTarget.dataset.index; // 获取当前点击图片的索引
            const images = this.data.images; // 获取所有图片的链接

            wx.previewImage({
                current: images[index], // 当前显示图片的链接
                urls: images // 需要预览的图片链接列表
            });
        },
        gourl(e) {
            const url = e.currentTarget.dataset.url
            const objectId = e.currentTarget.dataset.id
            wx.navigateTo({
                url: `${url}?id=` + objectId // 目标页面的路径
            });
        },
        showgood() {
            this.setData({
                isgood: !this.data.isgood
            })
        },
        isclick() {

            this.chickin()
            setTimeout(() => {
                this.showchick()
                this.showgood()
            }, 400)
        },
        async getcircle() {
            let AIMomentquery = new Parse.Query('AIMoment');
            AIMomentquery.equalTo('company', company);
            AIMomentquery.equalTo('objectId', this.data.objectId);
            AIMomentquery.equalTo('isVisible', true);
            AIMomentquery.include('profile.user');
            AIMomentquery.include('profile');
            AIMomentquery.notEqualTo('isDeleted', true)
            let P = await AIMomentquery.find();
            let AIMoment1List = P.map(item => item.toJSON());
            this.setData({
                cicleList: AIMoment1List,
            })
            this.setData({
                images: this.data.cicleList[0].images
            })
            // 将 ISO 字符串转换为时间戳并传递给 formatTime
            const createdAt = new Date(this.data.cicleList[0].createdAt).getTime();
            const time = this.formatTime(createdAt);
            this.setData({
                time
            })
            console.log('时间', time);
            this.showchick()
        },
        formatTime(timestamp) {
            const now = Date.now();
            const diff = now - timestamp;
            if (diff < 60000) { // 小于1分钟
                return '刚刚';
            } else if (diff < 3600000) { // 小于1小时
                return Math.floor(diff / 60000) + '分钟前';
            } else if (diff < 86400000) { // 小于24小时
                return Math.floor(diff / 3600000) + '小时前';
            } else if (diff < 172800000) { // 小于48小时
                return '昨天';
            } else {
                const date = new Date(timestamp);
                return this.formatDate2(date); // 显示具体日期
            }
        },
        formatDate2(date1) {
            date1 = new Date(date1);

            // 获取年份、月份和日期
            const year1 = date1.getFullYear();
            const month1 = date1.getMonth() + 1; // 月份从0开始，所以要加1
            const day1 = date1.getDate();

            // 返回格式化的字符串
            return `${year1}/${month1}/${day1}`;
        },
        //点击点赞按钮
        async chickin() {
            this.setData({
                isclick: !this.data.isclick
            })
            let AIMomentquery = new Parse.Query('AIMoment');
            AIMomentquery.equalTo('company', company);
            AIMomentquery.equalTo('objectId', this.data.objectId);
            AIMomentquery.equalTo('isVisible', true);
            AIMomentquery.include('profile.user');
            AIMomentquery.include('profile');
            AIMomentquery.notEqualTo('isDeleted', true)
            let P = await AIMomentquery.first();


            const currentUser = Parse.User.current();
            let AIMomentCommentquery = new Parse.Query('AIMomentLike');
            AIMomentCommentquery.equalTo('company', company);
            AIMomentCommentquery.equalTo('type', 'chickin');
            AIMomentCommentquery.equalTo('moment', P.toPointer());
            AIMomentCommentquery.equalTo('user', currentUser.id);
            let moment = await AIMomentCommentquery.first()
            if (moment) {
                moment.set('isLiked', this.data.isclick)
                try {
                    let saveDate = await moment.save();
                    this.showchick()
                    console.log(saveDate);
                    console.log("新数据保存成功");
                } catch (error) {
                    console.error("保存数据时出现错误:", error);
                }
            } else {
                const currentUser = Parse.User.current();
                let userquery = new Parse.Query('_User');
                userquery.equalTo('company', company);
                userquery.equalTo('objectId', currentUser.id);
                userquery.notEqualTo('isDeleted', true)
                let user = await userquery.first();

                let companyPointer = Parse.Object.extend('Company').createWithoutData(company);
                let Comment = new Parse.Object('AIMomentLike');
                Comment.set('moment', P.toPointer())
                Comment.set('company', companyPointer);
                Comment.set('type', 'chickin');
                Comment.set('user', user.toPointer());
                Comment.set('isLiked', true);
                try {
                    let saveDate2 = await Comment.save();
                    this.showchick()
                    console.log(saveDate2);
                    console.log("新数据保存成功");
                } catch (error) {
                    console.error("保存数据时出现错误:", error);
                }

            }
        },
        //显示是否点过赞
        async showischick() {
            const currentUser = Parse.User.current();
            let AIMomentCommentquery2 = new Parse.Query('AIMomentLike');
            AIMomentCommentquery2.equalTo('company', company);
            AIMomentCommentquery2.equalTo('type', 'chickin');
            AIMomentCommentquery2.equalTo('moment', this.data.objectId);
            AIMomentCommentquery2.equalTo('user', currentUser.id);
            let moment2 = await AIMomentCommentquery2.find()
            let AIMoment1List2 = moment2.map(item => item.toJSON());
            if (AIMoment1List2.length != 0) {
                this.setData({
                    isclick: AIMoment1List2[0].isLiked
                })
            } else {
                this.setData({
                    isclick: false
                })
            }
            console.log('isclick', AIMoment1List2);
        },
        //显示点赞人
        async showchick() {


            let Momentquery = new Parse.Query('AIMomentLike');
            Momentquery.equalTo('company', company);
            Momentquery.equalTo('type', 'chickin');
            Momentquery.equalTo('moment', this.data.objectId);
            Momentquery.notEqualTo('isDeleted', true)
            Momentquery.include('user')
            Momentquery.equalTo('isLiked', true);
            let r = await Momentquery.find();
            let chickList = r.map(item => item.toJSON());
            console.log('chickList', chickList);
            this.setData({
                chickList
            })
        },
        //显示弹出层
        showPopup() {
            this.setData({
                show: true,
                poptype: 'one', //直接回复
                commenttext: '评论'
            });
            this.showgood()
        },

        onClose() {
            this.setData({
                show: false
            });
        },
        //输入框高度随字体增多而变大
        onInput: function (event) {
            const value = event.detail.value; // 获取当前输入的值
            this.setData({
                inputValue: value,
                textareaHeight: this.calculateHeight(value) // 动态计算高度
            });
        },

        calculateHeight: function (value) {
            // 计算文本高度的逻辑，返回合适的高度
            // 这里可以根据实际情况调整
            const lineHeight = 40; // 设置行高
            const lines = Math.ceil(value.length / 30); // 假设每行30个字符
            return Math.max(52, lines * lineHeight); // 确保最小高度为52rpx
        },
        //  发送评论
        async sendComment() {
            //单独发送评论
            if (this.data.poptype == 'one') {
                let AIMomentquery = new Parse.Query('AIMoment');
                AIMomentquery.equalTo('company', company);
                AIMomentquery.equalTo('objectId', this.data.objectId);
                AIMomentquery.equalTo('isVisible', true);
                AIMomentquery.notEqualTo('isDeleted', true)
                let P = await AIMomentquery.first();

                const currentUser = Parse.User.current();
                let userquery = new Parse.Query('_User');
                userquery.equalTo('company', company);
                userquery.equalTo('objectId', currentUser.id);
                userquery.notEqualTo('isDeleted', true)
                let user = await userquery.first();

                let companyPointer = Parse.Object.extend('Company').createWithoutData(company);
                let Comment = new Parse.Object('AIMomentComment');
                Comment.set('moment', P.toPointer())
                Comment.set('company', companyPointer);
                Comment.set('type', 'coment');
                Comment.set('isDeleted', false);
                Comment.set('content', this.data.inputValue);
                Comment.set('user', user.toPointer());
                try {
                    let saveDate2 = await Comment.save();
                    console.log(saveDate2);
                    console.log("新数据保存成功");
                    this.getComment()
                } catch (error) {
                    console.error("保存数据时出现错误:", error);
                }
                // 处理发送评论的逻辑
                console.log(this.data.inputValue);
                // 清空输入框
                this.setData({
                    inputValue: '',
                    textareaHeight: 52 // 重置高度
                });
            }
            //回复别人评论
            if (this.data.poptype == 'two') {
                console.log('id', this.data.userobject);
                this.rebackmoment()
            }

        },
        // 获取评论
        async getComment() {
            let Momentquery = new Parse.Query('AIMomentComment');
            Momentquery.equalTo('company', company);
            Momentquery.equalTo('type', 'coment');
            Momentquery.equalTo('moment', this.data.objectId);
            Momentquery.notEqualTo('isDeleted', true);
            Momentquery.include('user');
            Momentquery.include('comment');
            Momentquery.include('comment.user');

            // 按照创建时间升序排列（从旧到新）
            Momentquery.ascending('createdAt'); // 或者使用 Momentquery.descending('createdAt') 以降序排列

            let r = await Momentquery.find();
            let commentList = r.map(item => {
                let comment = item.toJSON();
                // 初始化 showdeletid 属性为 false
                comment.showdeletid = false;
                return comment;
            });
            const filteredCommentList = commentList.filter(item => !item.comment || (item.comment && !item.comment.isDeleted));
            const noCommentCount = commentList.filter(item => !item.comment).length;
            console.log('评论', filteredCommentList);
            this.setData({
                commentList: filteredCommentList,
                noCommentCount,
            });
        },

        // 点击评论
        async showpop(e) {
            const objectId = e.currentTarget.dataset.id;
            let AIMomentCommentquery = new Parse.Query('AIMomentComment');
            AIMomentCommentquery.equalTo('company', company);
            AIMomentCommentquery.equalTo('objectId', objectId);
            AIMomentCommentquery.notEqualTo('isDeleted', true);
            AIMomentCommentquery.include('user');
            let r = await AIMomentCommentquery.find();
            let commentList = r.map(item => item.toJSON());

            const currentUser = Parse.User.current();
            let userquery = new Parse.Query('_User');
            userquery.equalTo('company', company);
            userquery.equalTo('objectId', currentUser.id);
            userquery.notEqualTo('isDeleted', true);
            let R = await userquery.find();
            let user = R.map(item => item.toJSON());

            // 检查是否点击了自己的评论
            if (user[0].objectId != commentList[0].user.objectId) {
                this.setData({
                    show: true,
                    poptype: 'two',
                    userobject: objectId,
                    commenttext: `回复${commentList[0].user.nickname}`
                });
            } else {
                // 点击了自己的评论，设置对应评论的 showdeletid 为 true
                const updatedCommentList = this.data.commentList.map(comment => {
                    if (comment.objectId === objectId) {
                        return {
                            ...comment,
                            showdeletid: true // 更新当前评论项
                        };

                    }
                    return comment; // 保持其他评论项不变

                });
                this.setData({
                    commentList: updatedCommentList // 更新 commentList 的状态
                });
                console.log('点击了自己');
            }
            console.log(this.data.commentList);
        },

        // 点击其他地方重置所有评论的 showdeletid
        onTapOutside() {
            if (!this.data.isCommentFocused) { // 只有在没有评论聚焦时才重置
                const updatedCommentList = this.data.commentList.map(comment => ({
                    ...comment,
                    showdeletid: false, // 重置所有评论的 showdeletid
                }));

                this.setData({
                    commentList: updatedCommentList,
                    focusedCommentId: null // 清除聚焦状态
                });
            }
        },
        // 添加页面的触摸事件
        onTouchStart() {
            this.onTapOutside(); // 页面触摸时重置评论状态
        },

        //回复评论
        async rebackmoment() {
            //所属评论

            let AIMomentCommentquery = new Parse.Query('AIMomentComment');
            AIMomentCommentquery.equalTo('company', company);
            AIMomentCommentquery.equalTo('objectId', this.data.userobject);
            AIMomentCommentquery.notEqualTo('isDeleted', true)
            let Puser = await AIMomentCommentquery.first();
            //所属动态
            let AIMomentquery = new Parse.Query('AIMoment');
            AIMomentquery.equalTo('company', company);
            AIMomentquery.equalTo('objectId', this.data.objectId);
            AIMomentquery.equalTo('isVisible', true);
            AIMomentquery.notEqualTo('isDeleted', true)
            let P = await AIMomentquery.first();
            //获取用户
            const currentUser = Parse.User.current();
            let userquery = new Parse.Query('_User');
            userquery.equalTo('company', company);
            userquery.equalTo('objectId', currentUser.id);
            userquery.notEqualTo('isDeleted', true)
            let user = await userquery.first();

            let companyPointer = Parse.Object.extend('Company').createWithoutData(company);
            let Comment = new Parse.Object('AIMomentComment');
            Comment.set('moment', P.toPointer())
            Comment.set('company', companyPointer);
            Comment.set('comment', Puser.toPointer());
            Comment.set('type', 'coment');
            Comment.set('isDeleted', false);
            Comment.set('content', this.data.inputValue);
            Comment.set('user', user.toPointer());
            try {
                let saveDate2 = await Comment.save();
                console.log(saveDate2);
                console.log("新数据保存成功");
                this.getComment()
            } catch (error) {
                console.error("保存数据时出现错误:", error);
            }
            // 处理发送评论的逻辑
            console.log(this.data.inputValue);
            // 清空输入框
            this.setData({
                inputValue: '',
                textareaHeight: 52 // 重置高度
            });
        },
        //计算底部高度
        getbottomheight() {
            const systemInfo = wx.getSystemInfoSync();
            const bottomNavHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom || 0;
            this.setData({
                bottomNavHeight,
            });
        },
        //删除评论
        async deletecomment(e) {
            const objectId = e.currentTarget.dataset.id
            let Momentquery = new Parse.Query('AIMomentComment');
            Momentquery.equalTo('company', company);
            Momentquery.equalTo('objectId', objectId);
            Momentquery.notEqualTo('isDeleted', true);
            let d = await Momentquery.first();
            d.set('isDeleted', true)
            try {
                let saveDate2 = await d.save();
                console.log(saveDate2);
                console.log("删除成功");
                this.getComment()
            } catch (error) {
                console.error("保存数据时出现错误:", error);
            }
            console.log(objectId);
        },
        //删除动态
        async deletecircle() {
            let Profilequery = new Parse.Query('AIMoment');
            Profilequery.equalTo('company', company);
            Profilequery.equalTo('isVisible', true);
            Profilequery.notEqualTo('isDeleted', true)
            Profilequery.equalTo('objectId', this.data.objectId);

            let P = await Profilequery.first();

            P.set('isDeleted', true)
            try {
                let saveDate2 = await P.save();
                console.log(saveDate2);
                this.setData({
                    objectId: ''
                })
                console.log("删除数据成功");
            } catch (error) {
                console.error("保存数据时出现错误:", error);
            }


        },
        //显示确认框
        showconfirm() {
            this.setData({
                showconfirm: true
            })
        },
        //取消确认框
        cancleconfirm() {
            this.setData({
                showconfirm: false
            })
        },
        //点击确认
        clickconfirm() {
            console.log('删除了');
            this.deletecircle()
        },
        // 显示完整内容
        showFullContent() {
            this.setData({
                showFull: true
            });
        },

        // 收起内容
        showLessContent() {
            this.setData({
                showFull: false
            });
        },

        //
        // 点击预览大图
        openpreviewImg(e){
            const index = e.currentTarget.dataset.index
            this.selectComponent("#previewComponent").showPreview();
            this.setData({
                //imgList 图片地址数组
                imgList:this.data.images,
                currentImg:this.data.images[index],
                // previewHideStatus:true
            })
          },

    }
})