// pages/index/house/house.js
import HTTP, { GetGardenHouse } from "./../../../../requestFn/Api"
const app = getApp();
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: 'ZZFBZ-RK6L6-FPZS5-E3MBZ-63LS2-7WBJE' // 必填
});
Page({
  data: {
    navbarActiveIndex: 0,
    navbarTitle: [
      "租房",
      "二手房",
      "小区"
    ],
    hiddenName: {
      rent: false,
      old: true,
      garden: true
    },
    chooseItems: {
      0: [{},
        {
          name: '床',
          value: '1',
          selected: false
        }, {
          name: '天然气',
          value: '2',
          selected: false
        }, {
          name: '暖气',
          value: '3',
          selected: false
        }, {
          name: '宽带',
          value: '4',
          selected: false
        }, {
          name: '冰箱',
          value: '5',
          selected: false
        }, {
          name: '衣柜',
          value: '6',
          selected: false
        }, {
          name: '沙发',
          value: '7',
          selected: false
        }, {
          name: '空调',
          value: '8',
          selected: false
        }, {
          name: '电视',
          value: '9',
          selected: false
        }, {
          name: '热水器',
          value: '10',
          selected: false
        }, {
          name: '洗衣机',
          value: '11',
          selected: false
        },
      ],
      1: [{},
        {
          name: '智能门锁',
          value: '1',
          selected: false
        }, {
          name: 'WIFI',
          value: '2',
          selected: false
        }, {
          name: '近地铁',
          value: '3',
          selected: false
        }, {
          name: '停车场',
          value: '4',
          selected: false
        }, {
          name: '独立卫生间',
          value: '5',
          selected: false
        }, {
          name: '私人阳台',
          value: '6',
          selected: false
        }, {
          name: '首次出租',
          value: '7',
          selected: false
        },
      ],
    },
    house_list: [],
    garden_list:[],
    page: 1,
    garden_page:1,
    page_size: 10,
    has_more: true,
    garden_more:true
  },

  onShow(options) {
    const that = this;
    const {
      city_code
    } = app.globalData;
    if (city_code) {
      this.setData({
        city_code
      })
      this.init();
    } else {
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userFuzzyLocation'] === true) {
            that.getLocation();
          } else if (res.authSetting['scope.userFuzzyLocation'] === undefined) {
            that.locationScope();
          } else if (res.authSetting['scope.userFuzzyLocation'] !== undefined && res.authSetting['scope.userFuzzyLocation'] !== true) {
            wx.showModal({
              title: '是否授权当前位置',
              content: '需要获取您的地理位置，请确认授权，否则无法使用相关功能！',
              success: res => {
                //如果点击取消则显示授权失败
                if (res.cancel) {
                  wx.showToast({
                    title: '您已拒绝授权!',
                    icon: 'none'
                  })
                  that.setData({
                    city_name: "请选择"
                  })
                }
                //如果点击确定会打开授权页请求二次授权
                else if (res.confirm) {
                  wx.openSetting({
                    success: dataAu => {
                      if (dataAu.authSetting['scope.userFuzzyLocation'] === true) {
                        wx.showToast({
                          title: '授权成功',
                          icon: 'none'
                        })
                        //再次授权，调用getLocationt的API
                        that.locationScope()
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'none'
                        })
                      }
                    }
                  })
                }
              }
            })
          }
        },
        fail(err) {
          wx.showModal({
            title: '提示',
            content: '未知错误，请重新打开小程序！'
          })
        }
      })
    }
  },
  locationScope() {
    const that = this;
    wx.authorize({
      scope: 'scope.userFuzzyLocation',
      success(res) {
        if (res.errMsg == "authorize:ok") {
          that.getLocation();
        }
      },
      fail(e) {}
    })
  },
  getLocation() {
    const that = this;
    wx.getFuzzyLocation({
      success(res) {
        const {
          latitude,
          longitude
        } = res;
        app.globalData.longitude = longitude;
        app.globalData.latitude = latitude;
        that.setData({
          longitude,
          latitude
        })
        that.getUserLocation();
      },
    })
  },
  getUserLocation() {
    let vm = this
    qqmapsdk.reverseGeocoder({ //逆地址解析（经纬度 ==> 坐标位置）
      location: {
        latitude: vm.data.latitude,
        longitude: vm.data.longitude
      },
      success(res) {
        var {
          result: {
            ad_info: {
              city
            }
          }
        } = res;
        app.globalData.city_name = city;
        vm.setData({
          city_name: city
        })
        vm.GetCityCode();
      }
    })
  },
  async GetCityCode() {
    const {
      city_name
    } = this.data;
    const data = await HTTP.GetCityCode({
      city_name
    });
    app.globalData.city_code = data.code;
    this.setData({
      city_code: data.code
    })
    this.init();
  },
  goRent_house() {
    wx.navigateTo({
      url: './renthouse/renthouse',
    })
  },
  goRelease() {
    wx.navigateTo({
      url: './myhouse/myhouse',
    })
  },
  goAddRenthouse() {
    wx.navigateTo({
      url: './addrent/addrent',
    })
  },
  init() {
    this.loadHomePage();
  },
  loadHomePage() {
    wx.stopPullDownRefresh();
    this.setData({
      pageLoading: true,
      page: 1,
      garden_page:1,
      garden_more:true,
      has_more: true
    });
    this.getRenthouse(true, );
    this.GetGardenHouse(true);
  },
  onNavBarTap: function (event) {
    const that = this;
    let navbarTapIndex = event.currentTarget.dataset.navbarIndex
    that.setData({
      navbarActiveIndex: navbarTapIndex
    })
    if (that.data.navbarActiveIndex == 0) {
      that.setData({
        hiddenName: {
          rent: false,
          old: true,
          garden: true
        }
      })
    } else if (that.data.navbarActiveIndex == 1) {
      that.setData({
        hiddenName: {
          rent: true,
          old: false,
          garden: true
        }
      })
    } else {
      that.setData({
        hiddenName: {
          rent: true,
          old: true,
          garden: false
        },
      })
    }
  },
  async getRenthouse(fresh = false, ) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }
    this.setData({
      goodsListLoadStatus: 1
    });
    let {
      house_list,
      page,
      page_size,
      city_code
    } = this.data;
    try {
      let res = await HTTP.RentHouse({
        page,
        page_size,
        city_code
      })
      this.setData({
        house_list: fresh ? res.list : house_list.concat(res.list),
        pageLoading: false,
        page: ++page,
        has_more: res.list.length === page_size
      })
    } catch (e) {
      this.setData({
        goodsListLoadStatus: 3
      });
    }
  },
  async GetGardenHouse(fresh = false,){
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }
    this.setData({
      goodsListLoadStatus: 1
    });
    let {
      garden_list,
      garden_page,
      page_size,
      city_code
    } = this.data;
    try {
      let res = await HTTP.GetGardenList({
        page:garden_page,
        page_size,
        city_code
      })
      this.setData({
        garden_list: fresh ? res.list : garden_list.concat(res.list),
        pageLoading: false,
        garden_page: ++garden_page,
        garden_more: res.list.length === page_size
      })
    } catch (e) {
      this.setData({
        goodsListLoadStatus: 3
      });
    }
  },
  onReachBottom() {
    if (!this.data.hiddenName.rent) {
      if (!this.data.has_more) {
        wx.showToast({
          title: '没有更多数据了',
          icon: 'none'
        })
        return console.log('没有更多数据了');
      }
      this.getRenthouse(false);
    }else if(!this.data.hiddenName.garden){
      if (!this.data.garden_more) {
        wx.showToast({
          title: '没有更多数据了',
          icon: 'none'
        })
        return console.log('没有更多数据了');
      }
      this.GetGardenHouse(false);
    }
  },
  goHouseDetail(e) {
    const {
      id
    } = e.currentTarget;
    const {
      house_list
    } = this.data;
    const data = house_list.filter(item => item.id == id);
    wx.navigateTo({
      url: './detail/detail',
      success: function (res) {
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          data
        })
      }
    })
  },
  goFindGarden() {
    wx.navigateTo({
      url: './findgarden/findgarden',
    })
  },
  onPullDownRefresh: function () {
    app.onRefresh();
    this.init();
  },
})