const app = getApp();
import HTTP from "../../../../../requestFn/Api"
const citySelector = requirePlugin('citySelector');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: 'ZZFBZ-RK6L6-FPZS5-E3MBZ-63LS2-7WBJE' // 必填
});
Page({
  data: {
    city_name: "",
    pageLoading: false,
    goodsListLoadStatus: 0,
    //类型
    typeItems: ["基础设施", "房源特色"],
    typeColor: [false, false],
    room_list: ["室", "厅", "卫"],
    roomColor: [false, false, false],
    rent_list: ["租金"],
    rentColor: [false],
    area_list: ["区域"],
    areaColor: [false],
    house_list: [],
    page: 1,
    page_size: 10,
    has_more: true,
    searchData: {},
    value: "",
    city_code: "",
  },
  onLoad(e) {
    const that = this;
    const {
      garden_id,
      garden_name
    } = e;
    if (garden_id && garden_name) {
      this.setData({
        searchData: {
          garden_id
        },
        value: garden_name
      })
    }
    qqmapsdk = new QQMapWX({
      key: 'ZZFBZ-RK6L6-FPZS5-E3MBZ-63LS2-7WBJE'
    });
    const {city_name,city_code} = app.globalData;
    if(city_name&&city_code){
      this.setData({
        city_name,
        city_code
      })
      this.init();
      this.getProvice_list(city_code)
    }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: '未知错误，请重新打开小程序！'
          })
      }
      })
    }
  },
  onShow() {
    const that = this;
    this.setData({
      typeCurrentIndex: 0,
      areaShow: false,
      houseShow: false,
      rentShow: false,
      sreenShow: false,
      areaFlag: false,
      rentFlag: false,
      houseFlag: false,
      sreenFlag: false,
      houseItems: {
        0: [{
            name: "不限",
            value: 0,
            selected: true
          },
          {
            name: "一室",
            value: 1,
            selected: false
          }, {
            name: "二室",
            value: 2,
            selected: false
          }, {
            name: "三室",
            value: 3,
            selected: false
          }
        ],
        1: [{
            name: "不限",
            value: 0,
            selected: true
          },
          {
            name: "一厅",
            value: 1,
            selected: false
          }, {
            name: "二厅",
            value: 2,
            selected: false
          }, {
            name: "三厅",
            value: 3,
            selected: false
          }
        ],
        2: [{
            name: "不限",
            value: 0,
            selected: true
          },
          {
            name: "一卫",
            value: 1,
            selected: false
          }, {
            name: "二卫",
            value: 2,
            selected: false
          }, {
            name: "三卫",
            value: 3,
            selected: false
          }
        ]
      },
      rentItems: {
        0: [{
          name: "不限",
          value: [0, 0],
          selected: true
        }, {
          name: "600元以下",
          value: [0, 600],
          selectd: false
        }, {
          name: "600-1000元",
          value: [600, 1000],
          selectd: false
        }, {
          name: "1000-1500元",
          value: [1000, 1500],
          selectd: false
        }, {
          name: "1500-2000元",
          value: [1500, 2000],
          selectd: false
        }, {
          name: "2000-3000元",
          value: [2000, 3000],
          selectd: false
        }, {
          name: "3000-5000元",
          value: [3000, 5000],
          selectd: false
        }, {
          name: "5000-8000元",
          value: [5000, 8000],
          selectd: false
        }, {
          name: "8000元以上",
          value: [0, 8000],
          selectd: false
        }, ]
      },
      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
          },
        ],
      },
    })
    const selectedCity = citySelector.getCity();
    if (selectedCity) {
      let {
        id,
        name
      } = selectedCity;
      id = id.slice(0, id.length - 2)
      that.setData({
        city_name: name,
        city_code: id
      })
      that.init();
      this.getProvice_list(id)
    }
  },
  locationScope() {
    const that = this;
    wx.authorize({
      scope: 'scope.userFuzzyLocation',
      success(res) {
        if (res.errMsg == "authorize:ok") {
          that.getLocation();
        }
      },
      fail(e) {
        that.setData({
          city_name:"请选择"
        })
        console.log(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();
      }
    })
  },
  onUnload() {
    // 页面卸载时清空插件数据，防止再次进入页面，getCity返回的是上次的结果
    citySelector.clearCity();
  },
  //获取城市code
  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();
    this.getProvice_list(data.code)
  },
  //获取城市列表
  async getProvice_list(city_code) {
    const {
      area_list
    } = await HTTP.GetProvince();
    const myarea_list = area_list.filter(item => item.city_code == city_code);
    let newArr = myarea_list.map(item => {
      return {
        name: item.name,
        value: item.code,
        selected: false
      }
    })
    this.setData({
      myarea_list: {
        0: [{
          name: "不限",
          value: "",
          selected: true
        }, ...newArr]
      }
    })
  },
  navToSearchPage() {
    wx.navigateTo({
      url: '../search/search',
    })
  },
  handleSubmit(e) {
    const {
      searchData
    } = this.data;
    const {
      value
    } = e.detail;
    this.setData({
      searchData: {
        ...searchData,
        garden_name: value
      }
    })
    this.init();
  },
  clearData(e) {
    const {
      searchData
    } = this.data;
    const {
      value
    } = e.detail;
    this.setData({
      searchData: {
        ...searchData,
        garden_name: value
      }
    })
    this.init();
  },
  //筛选
  //下拉收回
  sreenShow: function (e) {
    this.setData({
      sreenShow: !this.data.sreenShow,
      houseShow: false,
      rentShow: false,
      areaShow: false,
      typeCurrentIndex: 0
    })
  },
  houseShow() {
    this.setData({
      houseShow: !this.data.houseShow,
      rentShow: false,
      areaShow: false,
      sreenShow: false,
      typeCurrentIndex: 0
    })
  },
  rentShow() {
    this.setData({
      rentShow: !this.data.rentShow,
      houseShow: false,
      areaShow: false,
      sreenShow: false,
      typeCurrentIndex: 0
    })
  },
  areaShow() {
    this.setData({
      areaShow: !this.data.areaShow,
      houseShow: false,
      rentShow: false,
      sreenShow: false,
      typeCurrentIndex: 0
    })
  },
  //清空选择
  clear: function (e) {
    const {
      name
    } = e.currentTarget.dataset;
    const way = this.data[name];
    this.clearAll(way, name)
  },
  clearAll(way, name) {
    for (var i = 0, t = 1000; i < t; i++) {
      if (way[i] == null) {
        break;
      }
      for (var m = 0, n = 1000; m < n; m++) {
        if (way[i][m] == null) {
          break;
        }
        if (name == 'houseItems' || name == 'rentItems' || name == "myarea_list") {
          way[i][m].selected = false;
          way[i][0].selected = true;
          if (name == 'houseItems') {
            this.setData({
              roomColor: [false, false, false],
            })
          } else if (name == 'rentItems') {
            this.setData({
              rentColor: [false],
            })
          } else if (name == 'myarea_list') {
            this.setData({
              areaColor: [false],
            })
          }
        } else {
          way[i][m].selected = false;
          this.setData({
            typeColor: [false, false]
          })
        }
      }
    }
    this.setData({
      [name]: way
    })
  },
  //确认筛选
  confirm: function (e) {
    let base_arr = [];
    let special_arr = [];
    const {
      chooseItems
    } = this.data;
    chooseItems[0].map(item => {
      if (item.selected) {
        base_arr.push(item.value)
      }
    })
    chooseItems[1].map(item => {
      if (item.selected) {
        special_arr.push(item.value)
      }
    })
    const base_conf = this.get_conf(base_arr);
    const special_conf = this.get_conf(special_arr)
    if (base_conf != 0 || special_conf != 0) {
      this.setData({
        sreenFlag: true
      })
    } else {
      this.setData({
        sreenFlag: false
      })
    }
    this.setData({
      sreenShow: false,
      page: 1,
      has_more: true,
      searchData: {
        ...this.data.searchData,
        base_conf,
        special_conf
      }
    })
    this.getRenthouse(true, this.data.searchData)
  },
  house_confim() {
    const {
      houseItems
    } = this.data;
    const room_count = houseItems[0].filter(item => item.selected == true)[0]?.value
    const hall_count = houseItems[1].filter(item => item.selected == true)[0]?.value
    const wc_count = houseItems[2].filter(item => item.selected == true)[0]?.value
    if (room_count != 0 || hall_count != 0 || wc_count != 0) {
      this.setData({
        houseFlag: true
      })
    } else {
      this.setData({
        houseFlag: false
      })
    }
    this.setData({
      searchData: {
        ...this.data.searchData,
        room_count,
        hall_count,
        wc_count
      },
      page: 1,
      has_more: true,
      houseShow: false
    })
    this.getRenthouse(true, this.data.searchData)
  },
  rent_confim() {
    const {
      rentItems
    } = this.data;
    const value = rentItems[0].filter(item => item.selected == true)[0]?.value;
    const rent_price_greater = value[0];
    const rent_price_less = value[1];
    if (rent_price_greater == 0 && rent_price_less == 0) {
      this.setData({
        rentFlag: false
      })
    } else {
      this.setData({
        rentFlag: true
      })
    }
    this.setData({
      page: 1,
      has_more: true,
      searchData: {
        ...this.data.searchData,
        rent_price_greater,
        rent_price_less
      },
      rentShow: false
    })
    this.getRenthouse(true, this.data.searchData)
  },
  area_confim() {
    const {
      myarea_list
    } = this.data;
    const value = myarea_list[0].filter(item => item.selected == true)[0]?.value;
    if (value) {
      this.setData({
        areaFlag: true
      })
    } else {
      this.setData({
        areaFlag: false
      })
    }
    this.setData({
      page: 1,
      has_more: true,
      searchData: {
        ...this.data.searchData,
        area_code: value
      },
      areaShow: false
    })
    this.getRenthouse(true, this.data.searchData)
  },
  sortShow: function () {
    this.setData({
      sortShow: !this.data.sortShow
    })
  },
  //点击遮罩层
  mask: function () {
    this.setData({
      sreenShow: false,
      sortShow: false
    })
  },
  //选择类型
  chooseType: function (e) {
    const {
      index,
    } = e.currentTarget.dataset;
    this.setData({
      typeCurrentIndex: index,
    })
  },
  //选择具体内容
  chooseItem: function (e) {
    const {
      index,
      name
    } = e.target.dataset;
    const way = this.data[name]
    this.selectItems(index, way, name)
  },
  selectItems(index, way, name) {
    const {
      typeCurrentIndex
    } = this.data;
    if (name == 'houseItems' || name == 'rentItems' || name == "myarea_list") {
      for (let i = 0; i < way[typeCurrentIndex].length; i++) {
        if (i == index) {
          way[typeCurrentIndex][i].selected = true
          if (index !== 0) {
            if (name == 'houseItems') {
              this.setData({
                [`roomColor[${typeCurrentIndex}]`]: true
              })
            } else if (name == 'rentItems') {
              this.setData({
                [`rentColor[${typeCurrentIndex}]`]: true
              })
            } else if (name == 'myarea_list') {
              this.setData({
                [`areaColor[${typeCurrentIndex}]`]: true
              })
            }
          } else {
            if (name == 'houseItems') {
              this.setData({
                [`roomColor[${typeCurrentIndex}]`]: false
              })
            } else if (name == 'rentItems') {
              this.setData({
                [`rentColor[${typeCurrentIndex}]`]: false
              })
            } else if (name == 'myarea_list') {
              this.setData({
                [`areaColor[${typeCurrentIndex}]`]: false
              })
            }
          }
        } else {
          way[typeCurrentIndex][i].selected = false;
        }
      }
    } else {
      way[typeCurrentIndex][index].selected = !way[typeCurrentIndex][index].selected
      if (way[typeCurrentIndex][index].selected) {
        this.setData({
          [`typeColor[${typeCurrentIndex}]`]: true
        })
      } else {
        let num = 0;
        way[typeCurrentIndex].map(item => {
          if (item.selected) {
            num = num + 1
          }
        })
        if (num == 0) {
          this.setData({
            [`typeColor[${typeCurrentIndex}]`]: false
          })
        }
      }
    }
    this.setData({
      [name]: way
    })
  },
  init() {
    this.loadHomePage();
  },
  onPullDownRefresh() {
    this.init();
  },
  loadHomePage() {
    wx.stopPullDownRefresh();
    this.setData({
      pageLoading: true,
      page: 1,
      has_more: true
    });
    this.getRenthouse(true, this.data.searchData);
  },
  async getRenthouse(fresh = false, data = {}) {
    let {
      house_list,
      page,
      page_size,
      city_code
    } = this.data;
    let res = await HTTP.RentHouse({
      page,
      page_size,
      city_code,
      approve_status: 2,
      ...data
    })
    this.setData({
      house_list: fresh ? res.list : house_list.concat(res.list),
      pageLoading: false,
      page: ++page,
      has_more: res.list.length === page_size
    })
  },
  onReachBottom() {
    if (!this.data.has_more) {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none'
      })
      return console.log('没有更多数据了');
    }
    this.getRenthouse(false, this.data.searchData);
  },
  goada() {
    wx.navigateTo({
      url: '../../notice/index',
    })
  },
  get_conf(arr) {
    let value = 0;
    arr.forEach(n => {
      value = value | (1 << n)
    });
    return value
  },
  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
        })
      }
    })
  },
  onPullDownRefresh: function () {
    app.onRefresh();
    this.init();
  },
  goCity() {
    const key = 'ZZFBZ-RK6L6-FPZS5-E3MBZ-63LS2-7WBJE'; // 使用在腾讯位置服务申请的key
    const referer = '易小居'; // 调用插件的app的名称
    const hotCitys = '北京,上海,天津,重庆,广州,深圳,成都,杭州'; // 用户自定义的的热门城市
    wx.navigateTo({
      url: `plugin://citySelector/index?key=${key}&referer=${referer}&hotCitys=${hotCitys}`,
    })
  }
})