import houseApi from '../../apis/house'
import loginFn from '../../utils/login'
import {
    encryption
} from '../../utils/encryption'
import {
    changeDateFormat
} from '../../utils/date'
import {
    isPhoneX
} from './../../utils/tools'
import {
    removeUserInfo,
    removeToken
} from '../../utils/storage'
import EventEmitter from '../../utils/eventEmitter'
const app = getApp();
Page({
    /**
     * 组件的属性列表
     */
    data: {
        token: app.globalData.token,
        tabList: [],
        show_empty: false,
        houses: [],
        //todo 4个 icon栏位，可后台配置, 调用IconClick函数。
        icon_list: [{
                name: '推荐',
                icon: 'edit',
                type: 0
            },
            {
                name: '二手房',
                icon: 'edit',
                type: 2
            },
            {
                name: '新房',
                icon: 'write',
                type: 1
            },
            // {name: '租房',icon:'edit',type: 3},
        ],
        fetcherData: {
            page_num: 1,
            city: '',
            saleType: 0,
            page_size: 15,
            saleState: 1
        },
        has_next: true,
        navbarInitTop: 80
    },
    CitySelect(res) {
        // 城市选择
        wx.navigateTo({
            url: '/pages/city/city'
        })
    },
    onReachBottomDistance: 50,
    onReachBottom: function () {
        if (this.data.has_next) {
            let page = this.data.fetcherData.page_num++
            this.setData({
                'fetcherData.page_num': this.data.fetcherData.page_num++
            })
            this.getHouseList()
        }
        return
    },
    onPageScroll: function (e) { // 调用showImg函数
        var top = e.scrollTop;
        try {
            //判断'滚动条'滚动的距离 和 '元素在初始时'距顶部的距离进行判断
            var isSatisfy = top > this.data.navbarInitTop ? true : false;
            if (this.data.isFixedTop === isSatisfy) {
                return false;
            }
            this.setData({
                isFixedTop: isSatisfy
            });
        } catch (e) {
            console.log(e)
        }
    },
    onShow: function () {

        var that = this;
        var city = app.globalData.city;
        if (city !== this.data.fetcherData.city) {
            this.setData({
                'fetcherData.city': app.globalData.city,
                'fetcherData.page_num': 1,
                houses: []
            })
            this.getHouseList()
        }
    },
    getHouseList: function () {
        app.wxshowloading('拼命加载中...');
        if (!this.data.fetcherData.saleType) {
            delete this.data.fetcherData.saleType
        }
        houseApi.houseList(this.data.fetcherData).then(res => {
            this.setData({
                houses: [...this.data.houses, ...res.data.list.map(item => {
                    item.cover_image += '?x-oss-process=image/resize,w_210,limit_0'
                    return item
                })],
                has_next: res.data.list.length === 0 ? false : true
            })
        }).finally(() => {
            wx.hideLoading()
        })
    },
    onLoad: function (options) {
        isPhoneX().then(res => {
            this.setData({
                isIphoneX: res
            })
        })
        // app.SetProvinceCity('广东省', '珠海');
        // this.setData({
        //     'fetcherData.city': '珠海'
        // })
        // this.getHouseList(0);
        wx.getSetting({
            success: (res) => {
                var statu = res.authSetting;
                console.log(res)
                // this.getPermission()
            },
            fail: (err) => {
                console.log(err, 'err')
                this.setData({
                    'fetcherData.city': '定位失败'
                })
                this.getHouseList(0);
            }
        })
        if (getApp().globalData.userinfo.name === getApp().globalData.userinfo.phone) {
            removeUserInfo()
            removeToken()
            getApp().globalData.token = ''
            getApp().globalData.userinfo = {}
            EventEmitter.emit('logout')
        }

    },
    getPermission: function () {
        var that = this;
        return new Promise((resolve, reject) => {
            wx.getLocation({
                type: 'wgs84',
                success: function (res) {
                    var latitude = res.latitude;
                    var longitude = res.longitude;
                    app.globalData.qqmapsdk.reverseGeocoder({
                        location: {
                            latitude: latitude,
                            longitude: longitude
                        },
                        success: function (res) {
                            var ad_info = res.result.ad_info;
                            let province = ad_info.province;
                            // let city = ad_info.city.replace('市', '');
                            let district = ad_info.district;
                            // app.SetProvinceCity('广东省', '洛杉矶');
                            // app.SetProvinceCity('广东省', city);
                            that.setData({
                                // 'fetcherData.city': '洛杉矶'
                                // 'fetcherData.city': city
                            })
                            that.getHouseList(0);
                            // app.ShowToast('定位城市：' + city)
                        },
                        fail: function (res) {
                            // wx.showModal({
                            //     title: '定位失败，请手动选择城市',
                            // });
                            that.getHouseList(0);
                        }
                    });
                },
                fail(err) {
                    wx.showModal({
                        title: '定位失败，请手动选择城市',
                    });
                    that.getHouseList(0);
                }
            })
        })
    },
    changeListType(e) {
        const {
            type
        } = e.currentTarget.dataset
        wx.showLoading({
            title: '正在加载中...',
        })
        this.setData({
            'fetcherData.saleType': type,
            'fetcherData.page_num': 1,
            houses: []
        })
        this.getHouseList()
    },
    bindconfirm(e) {
        this.setData({
            'fetcherData.title': e.detail.value,
            'fetcherData.page_num': 1,
            // houses: []
        })
        // this.getHouseList()
    },
    searchHouse(e) {
        clearTimeout(this.timer)
        const {
            value
        } = e.detail
        this.timer = setTimeout(() => {
            this.setData({
                'fetcherData.title': value,
                'fetcherData.page_num': 1,
                houses: []
            })
            this.getHouseList()
        }, 300)
    },
    onShareAppMessage: function (res) {
        var path = '/pages/index/index'
        return {
            title: '美房理，海量复刻真房源',
            path: path,
            imageUrl: 'https://usa-4dkankan-project.oss-us-west-1.aliyuncs.com/4dHouse/share.png', // 分享的封面图
        }
    },
    getPhoneNumber(e) {
        this.triggerEvent('toVrHouse')
        loginFn(e, app.globalData.user_code, this.properties.isAgency ? true : false).then(res => {

          this.setData({
            loginStatus: app.globalData.token ? true : false,
            userinfo: app.globalData.userinfo,
          })
          // this.getHouseFocusStatus().then(res => {
          //   if (!res) {
          //     this.changeFocusStatus()
          //   }
          // })
        })
      
    }

});