import HTTP from "../../../../../requestFn/Api"
const app = getApp();
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: {
    house_list: [],
    show: false,
    garden_name: '',
    loadMoreStatus: 0,
    page: 1,
    page_size: 10,
    has_more: true,
    total: 0,
    sorts: '',
    overall: 0,
    areaall: 0,
    area: '',
    typeall: 0,
    type: '',
    ageall: 0,
    age: '',
    rentItems: [{
      name: "不限",
      rent_price_greater: '0',
      rent_price_less: '0',
      selected: false
    }, {
      name: "0.5万以下",
      rent_price_greater: '0',
      rent_price_less: '5000',
      selectd: false
    }, {
      name: "0.5万-0.8万",
      rent_price_greater: '5000',
      rent_price_less: '8000',
      selectd: false
    }, {
      name: "0.8万-1万",
      rent_price_greater: '8000',
      rent_price_less: '10000',
      selectd: false
    }, {
      name: "1万-1.5万",
      rent_price_greater: '10000',
      rent_price_less: '15000',
      selectd: false
    }, {
      name: "1.5万-到2万",
      rent_price_greater: '15000',
      rent_price_less: '20000',
      selectd: false
    }, {
      name: "2万以上",
      rent_price_greater: '0',
      rent_price_less: '20000',
      selectd: false
    }],
    typeItems: [{
        name: "不限",
        selected: false,
        building_type: '0',
      },
      {
        name: "塔楼",
        selected: false,
        building_type: '1',
      },
      {
        name: "板楼",
        selected: false,
        building_type: '2',
      },
      {
        name: "塔板结合",
        selected: false,
        building_type: '3',
      },
      {
        name: "其他",
        selected: false,
        building_type: '4',
      }
    ],
    ageItems: [{
      name: "不限",
      selected: false,
      building_year_greater: '0',
      building_year_less: '0'
    }, {
      name: "5年以内",
      selected: false,
      building_year_greater: '0',
      building_year_less: '5'
    }, {
      name: "10年以内",
      selected: false,
      building_year_greater: '0',
      building_year_less: '10'
    }, {
      name: "15年以内",
      selected: false,
      building_year_greater: '0',
      building_year_less: '15'
    }, {
      name: "20年以内",
      selected: false,
      building_year_greater: '0',
      building_year_less: '20'
    }, {
      name: "20年以上",
      selected: false,
      building_year_greater: '20',
      building_year_less: '999'
    }, ],
    minVal: '',
    maxVal: '',
    name: "no",
    city_code: "",
    area_code: "",
    building_list: {
      1: "塔楼",
      2: "板楼",
      3: "塔板结合",
      4: "其他"
    },
    building_type: "",
    building_year_greater: "",
    building_year_less: "",
    city_name: ""
  },
  onLoad(e) {
    qqmapsdk = new QQMapWX({
      key: 'ZZFBZ-RK6L6-FPZS5-E3MBZ-63LS2-7WBJE'
    });
    const that = this;
    const {
      city_name,
      city_code
    } = app.globalData;
    if (city_name && city_code) {
      this.setData({
        city_name,
        city_code
      })
      this.init(true);
      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(options) {
    const that = this;
    const {
      searchValue = ''
    } = options || {};
    this.setData({
      garden_name: searchValue,
      loadMoreStatus: 0,
    });
    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(true);
      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();
      }
    })
  },
  async getCityCode() {
    const {
      city_name
    } = this.data;
    const {
      code
    } = await HTTP.GetCityCode({
      city_name
    });
    app.globalData.city_code = code
    this.setData({
      city_code: code
    })
    this.init(true);
    this.getProvice_list(code);
  },
  generalQueryData(reset = false) {
    const {
      garden_name,
      page,
      page_size,
      minVal,
      maxVal,
      building_type,
      building_year_greater,
      building_year_less,
      area_code,
      city_code
    } = this.data;
    const params = {
      page: 1,
      page_size: 10,
      garden_name,
      city_code
    };
    params.area_code = area_code == 0 ? '' : area_code;
    params.building_type = building_type;
    params.building_year_greater = building_year_greater;
    params.building_year_less = building_year_less;
    params.price_greater = minVal * 100;
    params.price_less = maxVal * 100;
    if (reset) return params;
    return {
      ...params,
      page: page + 1,
      page_size,
    };
  },

  async init(reset = true) {
    const {
      loadMoreStatus,
      house_list = []
    } = this.data;
    const params = this.generalQueryData(reset);
    if (loadMoreStatus !== 0) return;
    this.setData({
      loadMoreStatus: 1,
    });
    try {
      const result = await HTTP.GetGardenList(params);
      const code = 'Success';
      const data = result;
      if (code.toUpperCase() === 'SUCCESS') {
        const {
          list,
          total = 0
        } = data;
        if (total === 0 && reset) {
          this.setData({
            emptyInfo: {
              tip: '抱歉，未找到相关商品',
            },
            loadMoreStatus: 0,
            total,
            house_list: [],
          });
          return;
        }

        const _goodsList = reset ? list : house_list.concat(list);
        const _loadMoreStatus = _goodsList.length === total ? 2 : 0;
        this.setData({
          house_list: _goodsList,
          loadMoreStatus: _loadMoreStatus,
          total,
          page: params.page || 1
        });
      } else {
        wx.showToast({
          title: '查询失败，请稍候重试',
        });
      }
    } catch (error) {}
  },
  onReachBottom() {
    const {
      house_list,
      total
    } = this.data;
    if (house_list.length == total) {
      this.setData({
        loadMoreStatus: 2,
      });
      return;
    }
    this.init(false)
  },
  onPullDownRefresh: function () {
    app.onRefresh();
    this.init(true);
  },
  handleCartTap() {
    wx.switchTab({
      url: '/pages/cart/index',
    });
  },

  clearGarden_name() {
    this.setData({
        house_list: [],
        loadMoreStatus: 0,
        garden_name: ""
      },
      () => {
        this.init(true);
      },
    );
  },

  handleSubmit(e) {
    const {
      value
    } = e.detail;
    this.setData({
        house_list: [],
        loadMoreStatus: 0,
        garden_name: value
      },
      () => {
        this.init(true);
      },
    );
  },

  handleFilterChange(e) {
    const {
      area_code,
      building_type,
      building_year_greater,
      building_year_less,
      minVal,
      maxVal
    } = this.data;
    const {
      overall,
      sorts,
      areaall,
      area,
      typeall,
      type,
      ageall,
      age,
      index
    } = e.detail;
    if (index == 1 && areaall == 1) {
      if (area == 'desc') {
        this.setData({
          name: 'area',
          show: true,
          areaall,
          area,
          type: '',
          age: '',
          sorts: "",
        })
        if (building_type) {
          this.setData({
            typeall,
          })
        } else {
          this.setData({
            typeall: "",
          })
        }
        if (building_year_greater || building_year_less) {
          this.setData({
            ageall,
          })
        } else {
          this.setData({
            ageall: "",
          })
        }
        if (minVal || maxVal) {
          this.setData({
            overall,
          })
        } else {
          this.setData({
            overall: "",
          })
        }
      } else {
        this.resetAll();
      }
    } else if (index == 2 && typeall == 1) {
      if (type == 'desc') {
        this.setData({
          name: 'type',
          show: true,
          typeall,
          type,
          area: "",
          sorts: "",
          age: ''
        })
        if (area_code) {
          this.setData({
            areaall
          })
        } else {
          this.setData({
            areaall: ""
          })
        }
        if (building_year_greater || building_year_less) {
          this.setData({
            ageall,
          })
        } else {
          this.setData({
            ageall: "",
          })
        }
        if (minVal || maxVal) {
          this.setData({
            overall,
          })
        } else {
          this.setData({
            overall: "",
          })
        }
      } else {
        this.resetAll();
      }
    } else if (index == 3 && ageall == 1) {
      if (age == 'desc') {
        this.setData({
          name: 'age',
          show: true,
          area: "",
          sorts: "",
          type: "",
          ageall,
          age
        })
        if (area_code) {
          this.setData({
            areaall
          })
        } else {
          this.setData({
            areaall: ""
          })
        }
        if (building_type) {
          this.setData({
            typeall,
          })
        } else {
          this.setData({
            typeall: "",
          })
        }
        if (minVal || maxVal) {
          this.setData({
            overall,
          })
        } else {
          this.setData({
            overall: "",
          })
        }
      } else {
        this.resetAll();
      }
    } else if (index == 4 && overall == 1) {
      if (sorts == 'desc') {
        this.setData({
          name: 'sorts',
          show: true,
          area: "",
          overall,
          sorts,
          type: "",
          age: ""
        })
        if (area_code) {
          this.setData({
            areaall
          })
        } else {
          this.setData({
            areaall: ""
          })
        }
        if (building_type) {
          this.setData({
            typeall,
          })
        } else {
          this.setData({
            typeall: "",
          })
        }
        if (building_year_greater || building_year_less) {
          this.setData({
            ageall,
          })
        } else {
          this.setData({
            ageall: "",
          })
        }
      } else {
        this.showFilterPopupClose(areaall, typeall, ageall, 0);
      }
    }
  },

  showFilterPopup() {
    this.setData({
      show: true,
    });
  },

  showFilterPopupClose(areaall, typeall, ageall, overall) {
    this.setData({
      show: false,
      overall,
      sorts: "",
      areaall: areaall,
      area: "",
      typeall,
      type: '',
      ageall,
      age: ''
    });
  },

  onMinValAction(e) {
    const {
      value
    } = e.detail;
    this.setData({
      minVal: value
    });
    this.resetrentItems();
  },

  onMaxValAction(e) {
    const {
      value
    } = e.detail;
    this.setData({
      maxVal: value
    });
    this.resetrentItems();
  },
  resetrentItems() {
    const {
      rentItems
    } = this.data;
    let newArr = rentItems.map(item => {
      return {
        ...item,
        selected: false
      }
    })
    this.setData({
      rentItems: newArr,
      minVal: '',
      maxVal: '',
    })
  },
  resetageItems() {
    const {
      ageItems
    } = this.data;
    let newArr = ageItems.map(item => {
      return {
        ...item,
        selected: false
      }
    })
    this.setData({
      ageItems: newArr,
      building_year_greater: "",
      building_year_less: "",
    })
  },
  resettypeItems() {
    const {
      typeItems
    } = this.data;
    let newArr = typeItems.map(item => {
      return {
        ...item,
        selected: false
      }
    })
    this.setData({
      typeItems: newArr,
      building_type: ""
    })
  },
  resetareaItems() {
    const {
      myarea_list
    } = this.data;
    let newArr = myarea_list.map(item => {
      return {
        ...item,
        selected: false
      }
    })
    this.setData({
      myarea_list: newArr,
      area_code: ""
    })
  },
  resetAll() {
    this.resetareaItems();
    this.resettypeItems();
    this.resetageItems();
    this.resetrentItems();
    this.showFilterPopupClose(0, 0, 0, 0)
  },
  reset() {
    this.resetAll();
    this.init(true);
  },

  confirm() {
    const {
      minVal,
      maxVal,
      rentItems,
      name,
      building_type,
      building_year_greater,
      building_year_less,
      area_code
    } = this.data;
    if (name == 'overall') {
      let message = '';
      let flag = true;
      let [value] = rentItems.filter(item => item.selected == true);
      const {
        rent_price_greater,
        rent_price_less
      } = value || {};
      if (minVal && maxVal && minVal > maxVal) {
        message = '请输入正确范围';
        flag = false
      } else if (!minVal && !maxVal & !rent_price_greater && !rent_price_less) {
        message = '请输入价格或选择范围';
        flag = false
      }
      if (!flag) {
        wx.showToast({
          title: message,
          icon: 'none'
        })
        return
      } else {
        this.setData({
            show: false,
            loadMoreStatus: 0,
            sorts: 'asc',
          },
          () => {
            this.init(true);
          },
        );
      }
    }
    if (name == 'type') {
      if (building_type) {
        this.setData({
            show: false,
            loadMoreStatus: 0,
            type: 'asc',
          },
          () => {
            this.init(true);
          },
        );
      } else {
        wx.showToast({
          title: "请选择类型",
          icon: 'none'
        })
      }
    }
    if (name == 'age') {
      if (building_year_greater && building_year_less) {
        this.setData({
            show: false,
            loadMoreStatus: 0,
            age: 'asc',
          },
          () => {
            this.init(true);
          },
        );
      } else {
        wx.showToast({
          title: "请选择楼龄",
          icon: 'none'
        })
      }
    }
    if (name == 'area') {
      if (area_code) {
        this.setData({
            show: false,
            loadMoreStatus: 0,
            area: 'asc',
          },
          () => {
            this.init(true);
          },
        );
      } else {
        wx.showToast({
          title: "请选择区域",
          icon: 'none'
        })
      }
    }
  },
  choicePrice(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const {
      rentItems
    } = this.data;
    let newArr = rentItems.map((item, num) => {
      if (num == index) {
        this.setData({
          minVal: item.rent_price_greater,
          maxVal: item.rent_price_less
        })
        return {
          ...item,
          selected: !item.selected
        }
      } else {
        return {
          ...item,
          selected: false
        }
      }
    })
    this.setData({
      rentItems: newArr
    })
  },
  choiceType(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const {
      typeItems
    } = this.data;
    let newArr = typeItems.map((item, num) => {
      if (num == index) {
        this.setData({
          building_type: !item.selected ? item.building_type : '',
        })
        return {
          ...item,
          selected: !item.selected
        }
      } else {
        return {
          ...item,
          selected: false
        }
      }
    })
    this.setData({
      typeItems: newArr
    })
  },
  choiceAge(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const {
      ageItems
    } = this.data;
    let newArr = ageItems.map((item, num) => {
      if (num == index) {
        this.setData({
          building_year_greater: !item.selected ? item.building_year_greater : '',
          building_year_less: !item.selected ? item.building_year_less : ''
        })
        return {
          ...item,
          selected: !item.selected
        }
      } else {
        return {
          ...item,
          selected: false
        }
      }
    })
    this.setData({
      ageItems: newArr
    })
  },
  choiceArea(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const {
      myarea_list
    } = this.data;
    let newArr = myarea_list.map((item, num) => {
      if (num == index) {
        this.setData({
          area_code: !item.selected ? item.code : '',
        })
        return {
          ...item,
          selected: !item.selected
        }
      } else {
        return {
          ...item,
          selected: false
        }
      }
    })
    this.setData({
      myarea_list: newArr
    })
  },
  //获取当前定位
  getCity_code() {

  },
  //获取城市列表
  async getProvice_list(city_code) {
    const {
      area_list
    } = await HTTP.GetProvince();
    const myarea_list = area_list.filter(item => item.city_code == city_code);
    this.setData({
      myarea_list: [{
        name: "不限",
        code: "0"
      }, ...myarea_list]
    })
  },
  goGardenDetail(e) {
    const {
      item
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '../garden-detail/garden-detail',
      success: function (res) {
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          garden_info: item
        })
      }
    })
  },
  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}`,
    })
  }
});