// nova-tourism/pages/homestay/homestay-detail/index.js
let Parse = getApp().Parse;
const company = getApp().globalData.company
import dateServ from '../../../service/date';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        //屏幕高度
        statusBarHeight: 0, // 状态栏高度
        screenHeight: 0, // 屏幕高度
        customHeight: 0, // 自定义导航栏高度（如小程序右上角胶囊按钮）
        bottomNavHeight: 0, // 底部导航栏高度
        contentHeight: 0, // 可用内容高度
        //  轮播图数组
        imageUrls: [],
        index: 1,
        //
        decodedDateStart: '',
        decodedDateEnd: '',
        objectId: "",
        daysBetween: 0,
        istoday: null,
        storeList: [],
        roomList: [],

        //地图
        longitude: 0,
        latitude: 0,
        markers: [],

        //
        start: '',
        end: '',

        //
        show: false,
        date_start1: '',
        date_end1: '',

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 计算
        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 - statusBarHeight - customHeight) * 750 / systemInfo.windowWidth;
        if (bottomNavHeight) {
            const padding_bottom = bottomNavHeight * 750 / systemInfo.windowWidth
            this.setData({
                bottomNavHeight: padding_bottom
            })
            console.log(this.data.bottomNavHeight);
        } else {
            this.setData({
                bottomNavHeight: 40
            })
        }

        this.setData({
            statusBarHeight,
            screenHeight,
            customHeight,
            contentHeight
        });

        const {
            objectId,
            date_start,
            date_end,
            daysBetween,
            istoday,
            start,
            end,
        } = options;
        console.log(options);
        // 解码接收到的参数
        const decodedDateStart = decodeURIComponent(date_start);
        const decodedDateEnd = decodeURIComponent(date_end);
        const Start = decodeURIComponent(start);
        const End = decodeURIComponent(end);
        this.setData({
            decodedDateStart,
            decodedDateEnd,
            objectId,
            daysBetween,
            istoday,
            start: Start,
            end: End,
        })
        console.log('istoday', this.data.istoday);
        this.hanshu()
    },
    async hanshu() {
        await this.gethomestay()
        await this.getroom()
        //   await this.getpic()
        await this.getcurrentdate()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    //随轮播图变化而变化
    onSwiperChange: function (event) {
        const currentIndex = event.detail.current; // 获取当前索引
        this.setData({
            index: currentIndex + 1
        })
    },
    //获取名宿信息
    async gethomestay() {
        let ShopStore = new Parse.Query('ShopStore');
        ShopStore.equalTo('company', company);
        ShopStore.equalTo('type', "stay");
        ShopStore.equalTo('objectId', this.data.objectId);
        ShopStore.notEqualTo('isDeleted', "true");
        ShopStore.include('location');

        let store = await ShopStore.find();
        let storeListPromises = store.map(async item => {
            let storeItem = item.toJSON();
            storeItem.iscollect = await this.iscollect(storeItem.objectId); // 等待iscollect的结果
            return storeItem;
        });

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

        this.setData({
            storeList
        });
        this.setData({
            imageUrls: storeList[0].image
        })
        this.Getlocation()
        console.log(this.data.storeList);
    },
    //获取房间信息
    async getroom() {
        let room = new Parse.Query('ShopRoom');
        room.equalTo('company', company);
        room.equalTo('shop', this.data.objectId);
        room.equalTo('isEnabled', 'true');
        room.include('benefitMap');
        room.notEqualTo('isDeleted', 'true');

        let room2 = await room.find();
        // 使用 Promise.all 来处理异步操作
        let roomList = await Promise.all(room2.map(async item => {
            let roomItem = item.toJSON();
            let count = await this.checkOrderCount(roomItem.objectId, this.data.start, this.data.end);
            console.log(count, roomItem.total);
            roomItem.isroom = count < roomItem.total; // 简化判断
            return roomItem;
        }));
        // 对 roomList 进行排序
        roomList.sort(this.compareFunction);

        this.setData({
            roomList
        });
        console.log('房间', this.data.roomList);
    },
    //排序
    compareFunction(a, b) {
        // 先比较 isroom 的值
        if (a.isroom !== b.isroom) {
            return a.isroom ? -1 : 1;
        }
        // 如果 isroom 相同，再比较 index 是否有值
        const hasIndexA = a.index !== undefined;
        const hasIndexB = b.index !== undefined;
        if (hasIndexA !== hasIndexB) {
            return hasIndexA ? -1 : 1;
        }
        // 如果 index 都有值或者都没值，按 index 大小排序（都没值时顺序其实不变）
        return (a.index || 0) - (b.index || 0);
    },
    async checkOrderCount(roomId, start, end) {
        const startTime = new Date(start);
        const endTime = new Date(end);
        let startTime2 = dateServ.changeDateTime(startTime, '14:00:00')
        let endTime2 = dateServ.changeDateTime(endTime, '12:00:00')
        let Order = new Parse.Query("RoomOrder")
        Order.equalTo("room", roomId)
        Order.equalTo("company", company)
        Order.exists("status")
        Order.notContainedIn('status', [400, 601, 700,800])
        Order.lessThan("startTime", endTime2);
        Order.greaterThan("endTime", startTime2); 
        Order.select("startTime", "endTime")
        let count = await Order.count()
        return count
    },
    //收藏功能
    async iscollect(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.equalTo('isCollect', 'true');
        Collect.notEqualTo('isDeleted', "true");
        let collect = await Collect.first();
        if (collect) {
            return true
        } else {
            return false
        }
    },
    //获取轮播图
    // async getpic() {
    //     let Banner = new Parse.Query('Banner');
    //     Banner.equalTo('company', company);
    //     Banner.equalTo('store', this.data.objectId);
    //     Banner.equalTo('isEnabled', 'true');
    //     Banner.notEqualTo('isDeleted', 'true');
    //     Banner.select('image');

    //     let Banner2 = await Banner.find();

    //     // 提取 image 属性并存储到 imageUrls 中
    //     let imageUrls = Banner2.map(item => item.get('image')); // 使用 get() 方法获取 image 属性

    //     this.setData({
    //         imageUrls // 将提取的 imageUrls 存储到组件状态中
    //     });

    //     console.log(this.data.imageUrls); // 输出 imageUrls
    // },


    //获取当前位置信息
    Getlocation() {
        // 假设 this.storeList[0].location 是一个 Parse.GeoPoint 对象
        if (this.data.storeList[0].location) {
            const storeLocation = this.data.storeList[0].location;
            console.log('地址存在');
            // 从 GeoPoint 对象中获取经纬度
            const latitude = storeLocation.latitude; // 纬度
            const longitude = storeLocation.longitude; // 经度

            console.log('获取到的经纬度:', latitude, longitude); // 添加日志

            // 调用 API 解析地址
            wx.request({
                url: 'https://api.map.baidu.com/reverse_geocoding/v3/?ak=sHZTomd7grslfP7sPKB8tRgT49FK9TEu&output=json&coordtype=gcj02&location=' + latitude + ',' + longitude,
                data: {},
                header: {
                    'Content-Type': 'application/json'
                },
                success: (ops) => { // 使用箭头函数
                    console.log(ops);
                    const address = ops.data.result.formatted_address;
                    this.setData({
                        address: address,
                        latitude: latitude, // 保证 latitude 被设置
                        longitude: longitude, // 保证 longitude 被设置
                        markers: [{ // 设置 markers
                            id: 1,
                            latitude: latitude,
                            longitude: longitude,
                            iconPath: 'https://file-cloud.fmode.cn/13WZ0W7u3l/20240724/7ebg0k104325941.png?imageView2/1/w/200/h/200', // 自定义标记图标
                            width: 20,
                            height: 20,
                            // callout: {
                            //     content: this.data.storeList[0].storeName, // 可以显示解析出的地址
                            //     color: '#ffffff',
                            //     bgColor: '#7F56B2',
                            //     padding: 4,
                            //     fontSize: 8,
                            //     borderRadius: 3,
                            //     display: 'ALWAYS'
                            // }
                        }]
                    });
                    // console.log(this.data.address);
                },
                fail: function (resq) {
                    wx.showModal({
                        title: '信息提示',
                        content: '请求失败',
                        showCancel: false,
                        confirmColor: '#f37938'
                    });
                },
                complete: function () {}
            });
        }

    },
    //点击预定
    navigate(e) {
        const objectId = e.currentTarget.dataset.id;
        // let currentUser = Parse.User.current()
        // currentUser = currentUser.toJSON()
        // console.log(currentUser, currentUser.idcard);

        // if (currentUser.idcard) {
        //     // 构造要传递的信息
        //     const info = {
        //         objectId: objectId,
        //         date_start: this.data.start,
        //         date_end: this.data.end,
        //     };
        //     // console.log('info',info);

        //     // 将信息转为查询字符串
        //     var queryString = Object.keys(info)
        //         .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(info[key])}`)
        //         .join('&');
        //     console.log(queryString);
        //     wx.navigateTo({
        //         url: `../homestay-order/index?${queryString}`
        //     })
        // } else {
        // wx.showToast({
        //     title: '请先进行实名认证',
        //     icon: 'none'
        // })
        //实名
        // wx.navigateTo({
        //     url: `/common-page/pages/info/cauth/cauth?themeColor=#FFE300`
        // })

        // 构造要传递的信息
        const info = {
            objectId: objectId,
            date_start: this.data.start,
            date_end: this.data.end,
        };
        console.log('info', info);

        // 将信息转为查询字符串
        var queryString = Object.keys(info)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(info[key])}`)
            .join('&');
        console.log(queryString);
        wx.navigateTo({
            url: `../homestay-order2/index?${queryString}`
        })
        // }

    },


    //获取今日明日日期
    getcurrentdate() {
        const today = new Date();
        const tomorrow = new Date();
        tomorrow.setDate(today.getDate() + 1);

        this.setData({
            date_start1: this.formatDate(today),
            date_end1: this.formatDate(tomorrow),
        });
        console.log(this.data.start, this.data.end);
    },
    //转换日期
    formatDate(date) {
        date = new Date(date);
        return `${date.getMonth() + 1}月${date.getDate()}日`;
    },
    // 计算两个日期之间的天数
    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
        });
    },
    //选好日期点击完成后
    onConfirm(event) {
        const [start, end] = event.detail;
        const daysBetween = this.calculateDaysBetween(start, end); // 计算天数差
        this.setData({
            show: false,
            start,
            end,
            decodedDateStartart: `${this.formatDate(start)} `,
            decodedDateEnd: `${this.formatDate(end)}`,
            daysBetween
        });
        if (this.data.decodedDateStartart.trim() == this.data.date_start1.trim() && this.data.decodedDateEnd.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);
        }
        this.getroom()
        console.log(`入住日期: ${this.data.decodedDateStartart}, 离店日期: ${this.data.decodedDateEnd}, 天数差: ${daysBetween}天`);
    },
    //拨打电话
    phone() {
        let phone = this.data.storeList[0].mobile
        console.log(phone);
        wx.makePhoneCall({
            phoneNumber: phone
        })
    },
    callMap() {
        if (this.data.storeList[0].location) {
            const latitude = this.data.storeList[0].location.latitude
            const longitude = this.data.storeList[0].location.longitude
            wx.openLocation({
                name: this.data.storeList[0].storeName,
                latitude,
                longitude,
                scale: 18
            })
        }

    }
})