<template>
    <view class="Locations">

        <map style="width: 100%;height: 60vh" :layer-style='5' :show-location='true' :latitude="position.latitude"
            :longitude="position.longitude" :markers="spotGuideMarkers" :scale="scale" @markertap="markertap" id="mapId"
            @callouttap="callouttap">
        </map>


        <!-- <view class="tabs">
			<view class=""
			v-for="(item, index) in tabs"
			:key="index"
			@click="setSpotGuideIndex(index)"
			:class="{act : spotGuideIndex == index}">
				{{ item }}
			</view>
		</view> -->

        <uv-tabs :list="houseTypeList" :activeStyle="{ color: '#1EC77A', fontWeight: 600 }" lineColor="#1EC77A"
            lineHeight="8rpx" lineWidth="50rpx" keyName="title" :current="currentHouseType"
            @click="onClickHouseType"></uv-tabs>


        <view class="Locations-list">
            <!-- 房源列表 -->
            <view v-if="list.length > 0">
                <view @click="onDetail(item)" class="se-my-10 se-mx-20 se-px-20 se-py-20 se-br-20 se-bgc-white se-flex"
                    v-for="(item, index) in list" :key="index">
                    <view class="se-pos se-w-260 se-h-180">
                        <image v-if="item.iconImage" class="se-a-80 se-pos-lt" :src="item.iconImage" mode=""></image>
                        <image class="se-w-260 se-h-180 se-br-10" :src="item.images[0]" mode=""></image>
                    </view>
                    <view class="se-pl-10 se-w-p-100">
                        <view class="se-c-black se-fs-28">
                            {{ item.title }}
                        </view>
                        <view class="se-flex se-flex-h-sb se-flex-ai-c se-fs-24 se-mt-10 se-c-66">
                            <text>{{ item.homeType }}</text>
                            <text>{{ item.timeGo }}年</text>
                        </view>
                        <view class="se-flex se-flex-h-sb se-flex-ai-c se-mt-10">
                            <template v-if="item.iconTitles.length > 0">
                                <view class="se-flex">
                                    <view
                                        class="se-display-ib se-c-white se-bgc-orange se-fs-22 se-br-8 se-px-10 se-py-5 se-mr-10"
                                        v-for="(items, indexs) in item.iconTitles" :key="indexs">
                                        {{ items }}
                                    </view>
                                </view>
                            </template>
                            <template v-else>
                                <view></view>
                            </template>
                            <view class="se-c-66 se-flex se-flex-ai-c">
                                <uv-icon name="eye"></uv-icon>
                                <text class="se-ml-5 se-fs-18">{{ item.num }}</text>
                            </view>
                        </view>
                        <view class="se-flex se-flex-h-sb se-flex-ai-c se-mt-10">
                            <text class="se-c-red se-fs-24 se-fw-6 se-toe-1">￥{{ item.price }}元/{{ item.unit }}</text>
                            <text class="se-c-66 se-fs-22 se-toe-1">{{ item.address }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <uv-empty v-else text="没有哦" textSize="30rpx" iconSize="200rpx" icon="list"></uv-empty>
        </view>


    </view>
</template>

<script>
import { housePageList, houseType } from "@/common/api.js"
import { getInfo } from "@/common/api.js"
export default {
    data() {
        return {
            scale: 12, //缩放级别
            show: true,
            tabs: [],
            spotGuideIndex: 0, // 当前选中的菜单索引
            position: {
                latitude: 23.106574,
                longitude: 113.324587
            },
            areaId: null, // 当前选中的区域ID
            // 房源列表相关数据
            list: [],
            classId: null,
            pageNo: 1,
            pageSize: 10,
            houseTypeList: [], // 房源类型列表
            currentHouseType: 0 ,// 当前选中的房源类型索引
        }
    },
    computed: {
        spotGuideMarkers() {
            let markers = [];
            this.list.forEach((item, index) => {
                if (item.latitude && item.longitude) {
                    markers.push({
                        id: index,
                        latitude: item.latitude,
                        longitude: item.longitude,
                        iconPath: '/static/image/tourGuide/marker.png',
                        width: 30,
                        height: 30,
                        callout: {
                            content: item.spotName,
                            color: '#000000',
                            fontSize: 14,
                            borderRadius: 5,
                            bgColor: '#ffffff',
                            padding: 5,
                            display: 'BYCLICK'
                        }
                    });
                }
            });
            return markers;
        },
    },
    mounted() {
        this.getCurrentLocation()
        this.onHouseType() // 获取房源类型
		this.onHousePageList() // 加载房源列表
		this.getUserInfo() // 加载房源列表
    },
    onPullDownRefresh() {
		if(!uni.getStorageSync('token') || this.userInfo.isPay != 1){
			return
		}
        let that = this
        that.pageNo = 1
        that.list = []
        that.onHousePageList()
    },
    onReachBottom() {
		if(!uni.getStorageSync('token') || this.userInfo.isPay != 1){
			return
		}
        let that = this
        that.pageNo = that.pageNo + 1
        that.onHousePageList()
    },
    methods: {
		getUserInfo(state){
			this.$store.commit('getUserInfo', userInfo => {
				if(userInfo.isPay != 1){
					
					uni.showModal({
						title: '开通会员可查看租房地图',
						success : res => {
							if(res.confirm){
								this.getUserInfo()
							}
						}
					})
				}
			})
		},
        // 获取当前位置
        getCurrentLocation() {
            const that = this;
            uni.getLocation({
                type: 'wgs84',
                success: function (res) {
                    console.log('当前位置的经度：' + res.longitude);
                    console.log('当前位置的纬度：' + res.latitude);
                    that.position.latitude = res.latitude;
                    that.position.longitude = res.longitude;
                    // 更新地图位置
                    that.onHousePageList();
                },
                fail: function (err) {
                    console.error('获取位置失败：', err);
                    uni.showToast({
                        title: '获取位置失败',
                        icon: 'none'
                    });
                }
            });
        },

        //点击tab栏
        clickTabs({ index, name }) {
            this.currentArea = index
            if (this.areaList[index]) {
                this.areaId = this.areaList[index].id
            }
            this.onHousePageList()
            this.$nextTick(() => {
                this.selectArea()
            })
        },
        setSpotGuideIndex(index) {
            this.spotGuideIndex = index
            this.onHousePageList()
        },
        textToSpeech() {
            console.log('textToSpeech');

            let self = this

            // self.context.src = this.$config.baseUrl + '/info/textToAudio?text=' + "你好"
            // self.context.play()

            // return

            plugin.textToSpeech({
                lang: "zh_CN",
                tts: true,
                content: "景德镇市陶阳里御窑景区位于景德镇的城市中心地带，北起瓷都大桥、昌江大道，南至昌江大桥、西至沿江西路，东至莲社路、胜利路。 自宋以来，景德镇先民“沿河建窑，因窑成市”，渐呈“码头—民窑—老街—里弄—御窑”聚落的历史空间和瓷业肌理，形成了世界建筑史上绝无仅有的老城格局，成就了中国“东方瓷国”的盛誉，陶瓷成为了中国走向世界，世界认识中国的文化符号。这里是景德镇历史上制瓷业的中心、原点和高峰，是“一带一路”海上陶瓷之路的零公里起点，是研究皇家御窑制瓷历史文化和景德镇陶瓷技艺，讲好景德镇故事，传播中国声音的“窗口”和“名片”。",
                success: function (res) {
                    self.context.src = res.filename;
                    self.context.play()
                },
                fail: function (res) {
                    console.log("fail tts", res)
                }
            })
        },
        //地图点击事件
        markertap(e) {
            console.log("markertap===你点击了标记点===", e)

            let event = this.list[e.markerId]

            this.onDetail(event)

            // uni.openLocation({
            // 	latitude: spot.latitude,
            // 	longitude: spot.longitude,
            // })

            // BYCLICK隐藏
            // ALWAYS显示

            // this.$store.commit('setDisplay', 
            // this.spotGuideMarkers[e.markerId].id)


            // this.$forceUpdate()

            // this.spotGuideMarkers.forEach((n, i) => {
            // 	if(i == e.markerId){
            // 		// 显示气泡
            // 		n.callout.display = 'ALWAYS'
            // 	}else{
            // 		// 隐藏气泡
            // 		n.callout.display = 'BYCLICK'
            // 	}
            // })
        },
        openLocation(n) {
            uni.openLocation({
                latitude: n.spotLatitude,
                longitude: n.spotLongitude,
            })
        },
        //地图点击事件
        callouttap(e) {
            console.log('callouttap地图点击事件', e)
            let spot = this.spotGuideMarkers[e.markerId]
            uni.openLocation({
                latitude: spot.latitude,
                longitude: spot.longitude,
            })
        },
        toUrl(item) {
            console.log(item);
            if (item.categoryId == 0) {
                this.$utils.navigateTo(`/pages_order/service/articleDetail?id=${item.id}&type=Inheritance`)
            }
        },
        // 点击按钮将地图中心移动到指定定位点
        moveTolocation(latitude, longitude) {
            let mapObjs = uni.createMapContext('mapId', this)
            mapObjs.moveToLocation(
                {
                    latitude,
                    longitude
                },
                {
                    complete: res => {
                        console.log('移动完成:', res)
                    }
                })
            // this.onRegionChange('',true)
        },
        // 点击景区，选择最近的一个景点
        selectArea() {
            let item = this.spotGuide[0]
            if (item && item.spotLatitude && item.spotLongitude) {
                this.moveTolocation(item.spotLatitude, item.spotLongitude)
            }
        },
        clickAreaDetail(id) {
            uni.navigateTo({
                url: '/pages_order/service/areaDetail?id=' + id
            })
        },

        // 获取房源类型列表
        onHouseType() {
            houseType({}).then(response => {
                console.info('houseType', response)
                this.houseTypeList = response.result
            }).catch(error => {

            })
        },
        // 点击房源类型
        onClickHouseType(event) {
            console.info(event)
            let that = this
            that.pageNo = 1
            that.classId = event.id
            that.currentHouseType = event.index
            that.list = []
            that.onHousePageList()
        },
        // 获取房源列表
        onHousePageList() {
			
			if(!uni.getStorageSync('token') || this.userInfo.isPay != 1){
				return
			}
			
            let that = this
            let params = {
                classId: that.classId,
                pageNo: that.pageNo,
                pageSize: that.pageSize
            }

            // 如果有位置信息，添加到参数中
            if (that.position.latitude && that.position.longitude) {
                params.latitude = that.position.latitude
                params.longitude = that.position.longitude
            }

            housePageList(params).then((response) => {
                console.info("房源列表数据", response.result.records)
                response.result.records.forEach((items, indexs) => {
                    if (items.image) {
                        items.images = items.image.split(',')
                    } else {
                        items.images = []
                    }
                    if (items.homeImage) {
                        items.homeImages = items.homeImage.split(',')
                    } else {
                        items.homeImages = []
                    }
                    if (items.iconTitle) {
                        items.iconTitles = items.iconTitle.split(',')
                    } else {
                        items.iconTitles = []
                    }
                })
                that.list = that.list.concat(response.result.records)
            }).catch((error) => {

            })
        },
        // 点击房源详情
        onDetail(event) {
            uni.navigateTo({
                url: "/pages_subpack/detail/index?id=" + event.id
            })
        },

    }
}
</script>

<style scoped lang="scss">
.Locations {

    .tabs {
        display: flex;

        &>view {
            flex: 1;
            margin: 20rpx 10rpx;
            padding: 20rpx 10rpx;
            background-color: #e8f7f0;
            color: #1EC77A;
            border-radius: 40rpx;
            font-size: 24rpx;
            text-align: center;
        }

        .act {
            background-color: #1EC77A;
            color: #fff;
        }
    }

    .Locations-list {
        .main {
            display: flex;
            margin: 20rpx;

            .main-image {
                width: 150rpx;
                height: 150rpx;
                border-radius: 20rpx;
            }

            .info {
                margin-left: 20rpx;

                .title {
                    font-size: 30rpx;
                    font-weight: 900;
                }

                .tips {
                    font-size: 24rpx;
                    color: #999999;
                    margin-top: 10rpx;
                }
            }

            .controls {
                margin-left: auto;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;

                .f {
                    image {
                        width: 50rpx;
                        height: 50rpx;
                    }
                }
            }

            .btn {
                padding: 10rpx;
                font-size: 22rpx;
                color: #1EC77A;
                border: 1rpx solid #1EC77A;
                background-color: #e8f7f0;
                display: flex;
                justify-content: center;
                align-items: center;
                margin-top: 10rpx;
                border-radius: 15rpx;

                image {
                    width: 25rpx;
                    height: 25rpx;
                }

                text {
                    margin: 0 10rpx;
                }
            }
        }

        .list {
            padding-left: 40rpx;

            .main {
                align-items: center;

                .main-image {
                    width: 140rpx;
                    height: 140rpx;
                }

                .controls {
                    flex-direction: row;

                    .f {
                        margin: 30rpx;

                        image {
                            width: 40rpx;
                            height: 40rpx;
                        }
                    }
                }
            }
        }
    }
}
</style>
