let Parse = getApp().Parse;
const company = getApp().globalData.company
const {
    getStores
} = require(".././../service/request")
Component({
    /**
     * 组件的属性列表
     */
    properties: {},

    /**
     * 组件的初始数据
     */
    data: {
        statusBarHeight: 0,
        screenHeight: 0,
        customHeight: 0,
        bottomNavHeight: 0,
        contentHeight: 0,
        topheight:0,

        date_start: '',
        date_end: '',
        date_start1: '',
        date_end1: '',
        istoday: true,
        daysBetween: 1,
        show: false,
        //店铺数据
        storeList: [],
        //价格
        price: 211,
        //搜索
        value: '',
        start: '',
        end: '',

        //触底加载
        loadedItems: 0,
        pageSize: 5,
        noMoreItems: false,
        scrollTop:0
    },
    lifetimes: {
        detached: function () {},
        attached: async function () {
            const systemInfo = wx.getSystemInfoSync();
            const statusBarHeight = systemInfo.statusBarHeight || 0;
            const screenHeight = systemInfo.screenHeight || 0;
            const custom = wx.getMenuButtonBoundingClientRect();
            const customHeight = custom.height + 10 + 2 || 0;
            const bottomNavHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom || 0;

            const contentHeight = (screenHeight - bottomNavHeight - 50 - statusBarHeight - customHeight) * 750 / systemInfo.windowWidth;
            const topheight = (statusBarHeight + customHeight )* 750 / systemInfo.windowWidth
            this.setData({
                statusBarHeight,
                screenHeight,
                customHeight,
                bottomNavHeight,
                contentHeight,
                topheight
            });
            console.log(topheight);
            this.getcurrentdate();
            this.gethomestar()
        },
    },
    /**
     * 组件的方法列表
     */
    methods: {
        //获取今日明日日期
        getcurrentdate() {
            const today = new Date();
            const tomorrow = new Date();
            tomorrow.setDate(today.getDate() + 1);

            this.setData({
                date_start: this.formatDate(today),
                date_end: this.formatDate(tomorrow),
                date_start1: this.formatDate(today),
                date_end1: this.formatDate(tomorrow),
                start: today,
                end: tomorrow
            });
            console.log(this.data.start, this.data.end);
        },
        // 计算两个日期之间的天数
        calculateDaysBetween(startDate, endDate) {
            const start = new Date(startDate);
            const end = new Date(endDate);
            const timeDifference = end - start; // 计算时间差（毫秒）
            const daysDifference = timeDifference / (1000 * 3600 * 24); // 转换为天数
            return daysDifference; // 返回天数差
        },
        //开日历
        onDisplay() {
            this.setData({
                show: true
            });
        },
        //关日历
        onClose() {
            this.setData({
                show: false
            });
        },
        //转换日期
        formatDate(date) {
            date = new Date(date);
            return `${date.getMonth() + 1}月${date.getDate()}日`;
        },
        //选好日期点击完成后
        async onConfirm(event) {
            const [start, end] = event.detail;
            const daysBetween = this.calculateDaysBetween(start, end); // 计算天数差
            this.setData({
                show: false,
                start,
                end,
                date_start: `${this.formatDate(start)} `,
                date_end: `${this.formatDate(end)}`,
                daysBetween
            });
            if (this.data.date_start.trim() == this.data.date_start1.trim() && this.data.date_end.trim() == this.data.date_end1.trim()) {
                this.setData({
                    istoday: true
                })
                console.log(this.data.istoday);
            } else {
                this.setData({
                    istoday: false
                })
                console.log(this.data.istoday);
            }
            console.log(`入住日期: ${this.data.date_start}, 离店日期: ${this.data.date_end}, 天数差: ${daysBetween}天`);
        },
        gourl(e) {
            const url = e.currentTarget.dataset.url;
            const id = e.currentTarget.dataset.id;

            // 构造要传递的信息
            const info = {
                objectId: id,
                date_start: this.data.date_start,
                date_end: this.data.date_end,
                daysBetween: this.data.daysBetween,
                istoday: this.data.istoday,
                start: this.data.start,
                end: this.data.end
            };

            // 将信息转为查询字符串
            const queryString = Object.keys(info)
                .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(info[key])}`)
                .join('&');

            // 使用查询字符串跳转
            wx.navigateTo({
                url: `${url}?${queryString}`,
            });
        },
        //获取店铺消息
        async gethomestar() {
            let _data = await getStores({
                val: this.data.value,
                uid: Parse.User.current().id,
                skip: this.data.loadedItems,
                limit: this.data.pageSize
            });
            // let ShopStore = new Parse.Query('ShopStore');
            // ShopStore.equalTo('company', company);
            // ShopStore.equalTo('type', "stay");
            // ShopStore.equalTo('isShow', true);
            // ShopStore.notEqualTo('isDeleted', "true");
            // ShopStore.limit(this.data.pageSize);
            // ShopStore.skip(this.data.loadedItems);
            // let store = await ShopStore.find();

            // let storeListPromises = store.map(async item => {
            //     let storeItem = item.toJSON();
            //     // 为每一项添加价格属性
            //     storeItem.price = storeItem.perCapita * this.data.daysBetween;
            //     storeItem.iscollect = await this.iscollect(storeItem.objectId); // 等待iscollect的结果
            //     return storeItem;
            // });

            // let storeList = await Promise.all(storeListPromises); // 等待所有的Promise完成

            // 合并新加载的商店和已存在的商店列表
            // let updatedStoreList = this.data.storeList.concat(storeList);

            if (_data.length < this.data.pageSize) {
                this.setData({
                    noMoreItems: true
                });
            } else {
                this.setData({
                    noMoreItems: false
                });
            }

            this.setData({
                storeList: this.data.storeList.concat(_data),
                loadedItems: this.data.loadedItems + _data.length,
            });

            console.log('店铺数据=====>', this.data.storeList);
        },
        //点击收藏
        async submit(e) {
            const object = e.currentTarget.dataset.id
            console.log(object);
            const currentUser = Parse.User.current();
            let Collect = new Parse.Query('DramaShopCollect');
            Collect.equalTo('company', company);
            Collect.equalTo('user', currentUser.id);
            Collect.equalTo('homestayStore', object);
            Collect.notEqualTo('isDeleted', "true");
            let collect = await Collect.first();

            await this.changeiscollect(object)

            if (collect) {
                collect.set('isCollect', true)
                try {
                    let saveDate = await collect.save();
                    console.log(saveDate);
                    console.log("收藏成功1");
                } catch (error) {
                    console.error("保存数据时出现错误:", error);
                }
            } else {
                //user
                const currentUser = Parse.User.current();
                let userquery2 = new Parse.Query('_User');
                userquery2.equalTo('company', company);
                userquery2.equalTo('objectId', currentUser.id);
                userquery2.notEqualTo('isDeleted', true)
                let user2 = await userquery2.first();
                //店铺
                let Collect3 = new Parse.Query('ShopStore');
                Collect3.equalTo('company', company);
                Collect3.equalTo('objectId', object);
                Collect3.notEqualTo('isDeleted', "true");
                let collect3 = await Collect3.first();

                let companyPointer = Parse.Object.extend('Company').createWithoutData(company);
                let Comment = new Parse.Object('DramaShopCollect');
                Comment.set('company', companyPointer);
                Comment.set('homestayStore', collect3.toPointer());
                Comment.set('user', user2.toPointer());
                Comment.set('isCollect', true);
                try {
                    let saveDate2 = await Comment.save();
                    console.log(saveDate2);
                    console.log("收藏成功");
                } catch (error) {
                    console.error("保存数据时出现错误:", error);
                }
            }

        },
        // 点击收藏后把storeList中对应的isCollect变成true
        changeiscollect(objectId) {
            // 创建一个新的 storeList 数组，以确保视图更新
            const updatedStoreList = this.data.storeList.map(item => {
                if (item.objectId === objectId) {
                    return {
                        ...item,
                        iscollect: !item.iscollect // 切换 iscollect 的值
                    };
                }
                return item; // 返回未修改的项
            });

            // 更新 storeList
            this.setData({
                storeList: updatedStoreList
            });

            console.log('修改成功', objectId);
        },
        //点击取消
        async cancle(e) {
            const object = e.currentTarget.dataset.id
            const currentUser = Parse.User.current();
            let Collect = new Parse.Query('DramaShopCollect');
            Collect.equalTo('company', company);
            Collect.equalTo('user', currentUser.id);
            Collect.equalTo('isCollect', true);
            Collect.equalTo('homestayStore', object);
            Collect.notEqualTo('isDeleted', "true");
            let collect = await Collect.first();

            await this.changeiscollect(object)
            if (collect) {
                collect.set('isCollect', false)
                try {
                    let saveDate = await collect.save();
                    console.log(saveDate);
                    console.log("取消成功");
                } catch (error) {
                    console.error("保存数据时出现错误:", error);
                }
            }
        },

        //搜索功能
        search(e) {
            const value = e.detail.value;
            console.log(this.data.value);
            this.getRooms(value)
        },
        //清零后
        change(e) {
            const value = e.detail.value;
            if (!value) {
                console.log('运行');
                this.clear()
            }
        },
        clear() {
            this.setData({
                loadedItems: 0,
                noMoreItems: false,
                storeList: [],
                value:''
            })
            this.gethomestar()
        },
        // 搜索函数
        async getRooms(value) {
            // 确保 value 不为空
            if (!value) {
                console.log('搜索值为空');
                return; // 如果没有输入值，直接返回
            }
            this.setData({
                loadedItems: 0,
                noMoreItems: false,
                storeList: []
            })
            this.gethomestar()
        },
        //触底加载
        async loadMoreData() {
            if (!this.data.noMoreItems) {
                await this.gethomestar()
            }
        },
        onScroll(event) {
            wx.createSelectorQuery()
              .select('#scroller')
              .boundingClientRect((res) => {
                this.setData({
                  scrollTop: event.detail.scrollTop,
                });
              })
              .exec();
          },
    }
});