import houseApi from '../../apis/house'
import cityApi from '../../apis/city'
import {
    isPhoneX
} from '../../utils/tools'
import {
    bindInput
} from '../../utils/utils'

const app = getApp();
const panelData = {
    'region': [{
            id: 'quyu',
            items: [{
                name: '',
                id: ''
            }]
        },
        {
            id: 'didian',
            items: [{
                name: '不限',
                id: ''
            }]
        },
        {
            id: 'xianshi',
            items: [{
                name: '不限',
                id: ''
            }]
        }
    ],
    'jiage': [{
        id: 'jiage',
        filter: '价格',
        items: [{
            name: '不限',
            id: ''
        }, {
            name: '50万以下',
            id: '0#50'
        }, {
            name: '50万-100万',
            id: '50#100'
        }, {
            name: '100万-150万',
            id: '100#150'
        }, {
            name: '150万-200万',
            id: '150#200'
        }, {
            name: '200万-250万',
            id: '200#250'
        }, {
            name: '250万-300万',
            id: '250#300'
        }]
    }],
    'woshi': [{
        id: 'jushi',
        filter: '卧室',
        items: [{
            name: '不限',
            id: ''
        }, {
            name: '1',
            id: '1'
        }, {
            name: '2',
            id: '2'
        }, {
            name: '3',
            id: '3'
        }, {
            name: '4',
            id: '4'
        }]
    }],
    'yushi': [{
        id: 'yushi',
        filter: '浴室',
        items: [{
            name: '不限',
            id: ''
        }, {
            name: '1',
            id: '1'
        }, {
            name: '2',
            id: '2'
        }, {
            name: '3',
            id: '3'
        }, {
            name: '4',
            id: '4'
        }]
    }]
}


let type_acive = ''

const LD = {
    agencyId: '',
    id: '',
    name: "不限",
    parentId: '',
    type: ''
}
Page({
    /**
     * 组件的属性列表
     */
    bindInput,

    data: {
        houses: [],
        type_acive,
        tab_panel: panelData[type_acive] || [],
        icon_list: [{
                name: '总价',
                icon: 'edit',
                type: "jiage"
            },
            {
                name: '卧室',
                icon: 'write',
                type: "woshi"
            },
            {
                name: '浴室',
                icon: 'write',
                type: "yushi"
            }
        ],
        fetcherData: {
            page_num: 1,
            city: '',
            page_size: 10,
            saleState: 1,
            district: '',
            price_s: '',
            rooms: '',
            bathRooms: '',
        },
        has_next: true,
        navbarInitTop: 80,
        seachKey: '',
        currentCity: '珠海市'
        // currentCity:''
    },

    changeListType(e) {
        let {
            type
        } = e.currentTarget.dataset
        let obj = {
            type_acive: type,
            tab_panel: panelData[type]
        }

        if (type === this.data.type_acive) {
            obj['type_acive'] = ''
        }
        this.setData({
            type_acive: '',
            tab_panel: []
        })
        this.setData(obj)
    },

    getCityListByProv() {
        // app.wxshowloading('拼命加载中...');
        var province = app.globalData.province;
        cityApi.getCityListByProv(province).then(res => {
            let items = res.data
            let quyu = panelData['region'].find(item => item.id === 'quyu')
            quyu['items'] = items

            let city = items.find(sub => sub.name === this.data.currentCity)
            city && this.getSubList({
                selectObj: {
                    didian: LD,
                    xianshi: LD,
                    quyu: city
                },
                type: 'quyu'
            })
        }).finally(() => {
            // wx.hideLoading()
        })
    },

    getSubList(data) {
        let {
            selectObj,
            type
        } = data
        let current = selectObj[type]
        cityApi.getSubList(current.id).then(res => {
            let items = res.data
            let tmp = []
            if (type === 'quyu') {
                tmp = panelData['region'].find(item => item.id === 'didian')
                let sub = panelData['region'].find(item => item.id === 'xianshi')
                sub['items'] = [LD]
            }
            if (type === 'didian') {
                tmp = panelData['region'].find(item => item.id === 'xianshi')
            }
            items.unshift(LD)
            tmp['items'] = tmp['items'] && items
            this.setData({
                tab_panel: panelData['region']
            })
        }).finally(() => {
            // wx.hideLoading()
        })

    },

    comfirmhandle(e) {
        let data = e.detail
        let fetData = this.data.fetcherData
        console.log(data.jushi)
        let tmp = Object.assign(fetData, {
            price_s: data.jiage || fetData.price || '',
            room_s: data.jushi || '',
            bathRoom_s: data.yushi || ''
        })
        this.closeTypeActive()
        this.setData({
            fetcherData: tmp
        })
        this.closeTypeActive()
        this.getHouseList()
    },

    selecthandle(e) {
        let {
            selectObj,
            type
        } = e.detail
        console.log(e.detail)
        if (type === 'quyu' || type === 'xianshi' || type === 'didian') {
            this.getSubList(e.detail)
        }
        console.log(selectObj)
        console.log(selectObj.jushi)
        let tmp = Object.assign(this.data.fetcherData, {
            // district:selectObj.didian.name,
            price_s: selectObj.jiage ? selectObj.jiage.id : '',
            rooms: selectObj.jushi ? selectObj.jushi.id : '',
            bathRooms: selectObj.yushi ? selectObj.yushi.id : '',
            // city: selectObj.quyu.name.replace('市', '')
            city: ''
        })
        this.setData({
            fetcherData: tmp
        })
        if (type !== 'quyu' && type !== 'didian') {
            this.closeTypeActive()
        }
        this.getHouseList()
    },
    bindInputValue(e) {
        const {
            value
        } = e.detail
        this.setData({
            seachKey: value
        })
    },
    tapSearch() {
        this.setData({
            'fetcherData.title': this.data.seachKey
        })
        this.getHouseList()
    },
    closeTypeActive() {
        this.setData({
            type_acive: ''
        })
    },
    // onReachBottomDistance: 50,
    // onReachBottom: function () {
    //     let page =  this.data.fetcherData.page++
    //     this.setData({
    //         'fetcherData.page': page
    //     })
    //     this.getHouseList()
    // },
    onShow: function () {
        this.getInitData()
    },
    getInitData() {
        this.getHouseList()
        this.getCityListByProv()
    },
    getHouseList: function () {
        // app.wxshowloading('拼加载中...');
        this.data.fetcherData.agency_user_id = getApp().globalData.userinfo.user_id
        houseApi.fetchAgencyHouseList(this.data.fetcherData).then(res => {
            this.setData({
                houses: res.data.list.map(item => {
                    item.cover_image += '?x-oss-process=image/resize,w_210,limit_0'
                    return item
                })
            })
        }).finally(() => {
            // wx.hideLoading()
        })
    },
    onLoad: function (options) {
        // this.getInitData()
        isPhoneX().then(res => {
            this.setData({
                isIphoneX: res
            })
        })




    },
    onShow: function () {
        //订阅状态查询

        if (getApp().globalData.token) {
            wx.getSetting({
                withSubscriptions: true,
                success: (setting) => {
                    if (setting.subscriptionsSetting.itemSettings && setting.subscriptionsSetting.itemSettings['zWTBJFpALA3KR3qx1keYJCzJdVtRjFbxrnOJc_Htn-g']) {} else {
                        wx.showToast({
                            title: '请前往【我的】-【消息订阅】订阅带看提醒，否则无法带看。',
                            icon: 'none'
                        })
                    }
                },
            })
        }
    },
    stop() {
        return
    },
    onShareAppMessage: function (res) {
        var path = '/pages/index/index'
        return {
            title: 'RealtorEasier，海量复刻真房源',
            path: path,
            imageUrl: 'https://usa-4dkankan-project.oss-us-west-1.aliyuncs.com/4dHouse/share.png', // 分享的封面图
        }
    },
    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(province, city, district);
                            that.setData({
                                // 'fetcherData.city': city
                            })

                            that.getInitData()
                            app.ShowToast('定位城市：' + city)
                        },
                        fail: function (res) {
                            wx.showModal({
                                title: '定位失败，请手动选择城市',
                            });
                            that.getInitData()
                        }
                    });
                },
                fail(err) {
                    wx.showModal({
                        title: '定位失败，请手动选择城市',
                    });
                }
            })
        })
    }
});