<template>
  <div class="home">
    <header>
      <!-- 搜索 -->
      <div class="flex align-c">
        <i class="icon icon-jiantou-zuo" @click="goBack"/>
        <div class="search-wrap pr" @click="goSearch">
          <i class="icon icon-sousuokuangsousuo"/>
          <input
            type="text"
            disabled
            placeholder="目的地、区域、公寓名称">
        </div>
      </div>
      <!-- 筛选 -->
      <div class="filter-wrap align-c pr">
        <div class="sort-bar align-c">
          <template v-for="(items, index) in filterCloneData">
            <div
              class="sort flex_c align-c"
              :class="{active: filterActive === index}"
              :key="index"
              v-if="items.name !== '排序'">
              <p
                class="flex_ac"
                @click="checkDroplist(index)"
                :class="{active: filterChecked.indexOf(index) != -1}">
                  <span>{{items.name}}</span>
                  <i class="icon icon-xialatishi"/>
              </p>
              <!-- 类型 -->
              <div class="pa droplist" :class="index" v-if="index === 'type'">
                <p
                  class="flex_ac"
                  :class="{active: typeVal === item.value}"
                  v-for="item in items.values"
                  :key="item.value"
                  @click="setSingle(item, 'type')"
                >
                  {{item.name}}
                  <i class="icon icon-duigou" v-if="typeVal === item.value"/>
                </p>
              </div>
              <!-- 户型 -->
              <div class="pa droplist" :class="index" v-else-if="index === 'roomType'">
                <div>
                  <div
                    v-for="(item, index) in items.values"
                    :key="index"
                    class="wrap">
                    <p>{{item.name}}</p>
                    <div class="radio flex">
                      <p
                        v-for="child in item.values"
                        :class="{active: item.checked.indexOf(child.value) !== -1}"
                        @click="setFilter(child, index, item.select, 'roomType')"
                        :key="child.value">{{child.name}}</p>
                    </div>
                  </div>
                </div>
                <div class="btn">
                  <van-button class="clear" @click="clean('roomType')">清空</van-button>
                  <van-button class="sure" type="danger" @click="getData('roomType')">确定</van-button>
                </div>
              </div>
              <!-- 租金 -->
              <div class="pa droplist" :class="index" v-else-if="index === 'price'">
                <p class="flex_c">{{rangeSlider[0]}}-{{rangeSliderMax || rangeSlider[1]}}</p>
                <div class="range">
                  <el-slider
                    v-model="rangeSlider"
                    range
                    :step="step"
                    :show-tooltip=false
                    :min="min"
                    :max="max">
                  </el-slider>
                </div>
                <van-button type="danger" @click="getData('price')">确定</van-button>
              </div>
              <!-- 更多 -->
              <div class="pa droplist" :class="index" v-else-if="index === 'other'">
                  <div class="more">
                    <div
                      v-for="(item, index) in items.values"
                      :key="index"
                      class="wrap">
                      <p>{{item.name}}</p>
                      <div class="radio flex">
                        <p
                          v-for="child in item.values"
                          :class="{active: item.checked.indexOf(child.value) !== -1}"
                          @click="setFilter(child, index, item.select, 'other')"
                          :key="child.value">{{child.name}}</p>
                      </div>
                    </div>
                  </div>
                  <div class="btn">
                    <van-button class="clear" @click="clean('other')">清空</van-button>
                    <van-button class="sure" type="danger" @click="getData('other')">确定</van-button>
                  </div>
              </div>
            </div>
          </template>
        </div>
        <!-- 排序 -->
        <div
          class="switch flex_c align-c"
          :class="{active: filterActive === 'order'}">
          <i
          class="icon icon-paixu flex_c align-c"
          :class="{active: filterChecked.indexOf('order') !== -1}"
          @click="checkDroplist('order')"/>
          <template v-for="(items, index) in filterCloneData">
            <div
              class="pa droplist type"
              :class="index"
              :key="index"
              v-if="items.name === '排序'"
            >
              <p
                class="flex_ac"
                :class="{active: orderVal === item.value}"
                v-for="item in items.values"
                :key="item.value"
                @click="setSingle(item, 'order')"
              >
                {{item.name}}
                <i class="icon icon-duigou" v-if="orderVal === item.value"/>
              </p>
            </div>
          </template>
        </div>
      </div>
    </header>
    <!-- 列表 -->
    <div class="building-list">
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh" v-if="data">
        <van-list
          v-if="data.length"
          v-model="loading"
          :finished="finished"
          :immediate-check='false'
          :offset="200"
          @load="onLoad">
          <div
            class="items goods"
            v-for="item in data"
            :key="item.houseId"
            @click="handleDetail(item.houseId)">
            <div class="img pr">
              <img :src="item.marketTagUrl" class="pa tag" alt="">
              <img v-if="item.imgUrl" :src='item.imgUrl' alt="">
              <img v-else src="../assets/imgs/buildings-img@2x.png" alt="">
            </div>
            <div class="info">
              <h4 class="lineTwoHidden">{{item.houseName}}</h4>
              <p class="lineHidden">{{item.roomTypeText}}</p>
              <div class="tag">
                <p
                  :style="{color: tag.color,background: $util.colorToRgba(tag.bgColor)}"
                  v-for="tag in item.tags"
                  :key="tag.title"
                  >{{tag.title}}</p>
              </div>
              <div class="price">
                <i>{{item.unit}}</i>
                <p>{{item.price}}</p>
                <span v-show="item.rentTimeUnit">/{{item.rentTimeUnit}}</span>
              </div>
            </div>
          </div>
        </van-list>
        <is-empty v-if="isEmpty"></is-empty>
        <!-- 无数据 -->
        <div class="noData" v-show="showRecommend">
          <img src="../assets/imgs/none-building.png" alt="">
          <p>没有找到房源，请换个搜索条件试试哦～</p>
          <div class="list" v-show="recommendData">
            <h4>热门公寓</h4>
            <div
              class="items goods"
              v-for="item in recommendData.list"
              :key="item.houseId"
              @click="handleDetail(item.houseId)">
              <div class="img pr">
                <img :src="item.marketTagUrl" class="pa tag" alt="">
                <img v-if="item.imgUrl" :src='item.imgUrl' alt="">
                <img v-else src="../assets/imgs/buildings-img@2x.png" alt="">
              </div>
              <div class="info">
                <h4 class="lineTwoHidden">{{item.houseName}}</h4>
                <p class="lineHidden">{{item.roomTypeText}}</p>
                <div class="tag">
                  <p
                    :style="{color: tag.color,background: $util.colorToRgba(tag.bgColor)}"
                    v-for="tag in item.tags"
                    :key="tag.title"
                    >{{tag.title}}</p>
                </div>
                <div class="price">
                  <i>{{item.unit}}</i>
                  <p>{{item.price}}</p>
                  <span v-show="item.rentTimeUnit">/{{item.rentTimeUnit}}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-pull-refresh>
    </div>
    <!-- 遮罩 -->
    <div class="layer" v-if="showLayer" @click="closeFilter"/>
  </div>
</template>

<script>
import IsEmpty from "@/components/common/IsEmpty";

export default {
  components: {
    IsEmpty
  },
  data() {
    return {
      filterData: null,
      filterCloneData: null,
      data: [],
      recommendData: [],
      showRecommend: false,
      rangeSlider: [],
      min: null,
      max: null,
      step: null,
      rangeSliderMax: "",
      showLayer: false,
      filterActive: null,
      filterChecked: [],
      cityItem: this.$util.storage.fetch("CityItem"),
      typeVal: "",
      orderVal: "",
      pages: {},
      page: 0,
      lang: this.$store.state.langStr,
      isEmpty: false,
      loading: false,
      finished: false,
      isLoading: false,
      isOnLoad: false,
      isOnRefresh: false
    };
  },
  created() {
    this.verificationCity();
  },
  watch: {
    rangeSlider(val) {
      if (this.max - val[1] < this.step) {
        this.rangeSliderMax = "最大";
        this.rangeSlider[1] = this.max;
      } else {
        this.rangeSliderMax = "";
      }
    }
  },
  methods: {
    // 重新请求国家城市进行验证
    getCountryList() {
      let params = {};
      params.url = this.$apis.api_national_real_all_city;
      this.$net.req(params, this).then(res => {
        this.$store.commit("setCountryArr", res.data);
        this.verificationCity();
      });
    },
    // 验证城市
    verificationCity() {
      let cityName = this.$route.params.cityTag;
      let countryArr = this.$store.state.countryArr;
      let isTrue = null;
      if (countryArr.length) {
        countryArr.some(el => {
          el.son.some(element => {
            if (cityName == element.other_name) {
              isTrue = true;
              this.$util.storage.save("CityItem", element);
              this.cityItem = element;
              this.getFilterData();
              return true;
            }
          });
        });
      } else {
        this.getCountryList();
      }
      if (!isTrue && countryArr.length) {
        this.$Dialog
          .alert({
            message: "城市信息错误，请重新选择。"
          })
          .then(() => {
            this.$router.push({
              path: `/${this.lang}/guide`
            });
          });
      }
    },
    // 加载筛选项
    getFilterData() {
      let params = {};
      params.url = this.$apis.api_filter_attr;
      params.data = {
        cityId: this.cityItem.id
      };
      this.$net.req(params, this).then(
        res => {
          this.filterData = res.data;
          this.filterCloneData = this.$util.deepClone(this.filterData);
          for (const i in this.filterCloneData) {
            if (this.filterCloneData.hasOwnProperty(i)) {
              const elements = this.filterCloneData[i];
              if (i === "roomType" || i === "other") {
                elements.values.some(element => {
                  element.checked = [];
                  for (const key in this.$route.query) {
                    if (this.$route.query.hasOwnProperty(key)) {
                      const ele = this.$route.query[key];
                      if (element.keys === key) {
                        element.checked = ele.split(",").map(Number);
                        continue;
                      }
                    }
                  }
                });
              } else if (i === "type" || i === "order") {
                elements.checked = [];
                for (const key in this.$route.query) {
                  if (this.$route.query.hasOwnProperty(key)) {
                    const ele = this.$route.query[key];
                    if (i === key) {
                      elements.checked = Number(ele);
                      this[i + "Val"] = Number(ele);
                      continue;
                    }
                  }
                }
              }
            }
          }
          this.filterCloneData.type.values.unshift({ name: "不限", value: "" });
          this.filterCloneData.order.values.unshift({
            name: "综合排序",
            value: ""
          });
          this.min = res.data.price.values.minPrice.value;
          this.max = res.data.price.values.maxPrice.value;
          this.step = Math.ceil(this.max / res.data.price.unit);
          // 设置选中租金
          this.$route.query.maxPrice
            ? (this.rangeSlider = [
                this.$route.query.minPrice,
                this.$route.query.maxPrice
              ])
            : (this.rangeSlider = [this.min, this.max]);
          this.getData();
        },
        e => {
          this.$Toast(e.msg);
        }
      );
    },
    // 上拉加载
    onLoad() {
      setTimeout(() => {
        this.isOnRefresh = false;
        this.isOnLoad = true;
        this.getData();
      }, 500);
    },
    // 下拉刷新
    onRefresh() {
      setTimeout(() => {
        this.page = 0;
        this.isOnLoad = false;
        this.isOnRefresh = true;
        this.getData();
      }, 500);
    },
    // 加载数据
    getData(type) {
      let params = {};
      params.url = this.$apis.api_buildings_list;
      params.data = {
        limit: 10,
        cityId: this.cityItem.id,
        type: this.typeVal,
        order: this.orderVal,
        minPrice: this.rangeSlider[0],
        maxPrice: this.rangeSlider[1],
        rentType: this.rentTypeVal
      };
      if (this.filterCloneData) {
        this.filterCloneData.roomType.values.forEach(element => {
          params.data[element.keys] = JSON.stringify(element.checked);
        });
        this.filterCloneData.other.values.forEach(element => {
          params.data[element.keys] = JSON.stringify(element.checked);
        });
      }
      this.$util.sessionStorage.save("filter", JSON.stringify(params.data));
      this.$util.removeProperty(params.data);
      if (type) {
        this.page = 0;
        this.isOnLoad = false;
        this.isOnRefresh = false;
        this.closeFilter();
        // 添加高亮选中
        this.checkedFilter(type);
      } else {
        // 添加高亮选中
        this.checkedFilter();
      }
      this.page = this.page + 1;
      params.data.page = this.page;
      if (this.$route.query.locationId)
        params.data.locationId = this.$route.query.locationId;
      this.$net.req(params, this).then(
        res => {
          let data = res.data.list;
          this.pages = {
            limit: res.data.limit,
            page: res.data.page,
            totalCount: res.data.totalCount,
            totalPage: res.data.totalPage
          };
          if (data.length === 0) {
            this.showRecommend = true;
            this.getRecommendData();
          } else {
            this.showRecommend = false;
          }
          if (this.isOnLoad) {
            this.loading = false;
            if (this.page * params.data.limit >= this.pages.totalCount) {
              this.finished = true;
              this.isEmpty = true;
            }
            this.data = this.data.concat(data);
          } else if (this.isOnRefresh) {
            this.data = data;
            this.$toast("刷新成功");
            this.isLoading = false;
          } else {
            this.data = data;
          }
        },
        e => {
          this.$Toast(e.msg);
        }
      );
    },
    // 筛选项高亮
    checkedFilter(index) {
      let eq = this.filterChecked.indexOf(index);
      let queryData = this.$util.deepClone(this.$route.query);
      if (!index) {
        for (const key in this.filterData) {
          if (this.filterData.hasOwnProperty(key)) {
            index = key;
            this.checkedFilter(index);
          }
        }
      }
      if (index === "roomType" || index === "other") {
        let length = 0;
        this.filterCloneData[index].values.forEach(element => {
          // 判断是否存在已选项
          if (element.checked.length > 0) {
            queryData[element.keys] = element.checked.join(",");
            length++;
          } else {
            delete queryData[element.keys];
          }
        });
        if (length > 0) {
          if (eq === -1) {
            this.filterChecked.push(index);
          }
        } else {
          if (eq !== -1) {
            this.filterChecked.splice(eq, 1);
          }
        }
      } else if (index === "price") {
        let min = this.filterCloneData.price.values.minPrice.value;
        let max = this.filterCloneData.price.values.maxPrice.value;
        if (
          Number(this.rangeSlider[0]) !== min ||
          Number(this.rangeSlider[1]) !== max
        ) {
          queryData.minPrice = this.rangeSlider[0];
          queryData.maxPrice = this.rangeSlider[1];
          if (eq === -1) {
            this.filterChecked.push(index);
          }
        } else {
          delete queryData.minPrice;
          delete queryData.maxPrice;
          if (eq !== -1) {
            this.filterChecked.splice(eq, 1);
          }
        }
      } else if (index === "type" || index === "order") {
        if (this[index + "Val"] !== "") {
          queryData[index] = this[index + "Val"];
          if (eq === -1) {
            this.filterChecked.push(index);
          }
        } else {
          delete queryData[index];
          if (eq !== -1) {
            this.filterChecked.splice(eq, 1);
          }
        }
      }
      if (this.cityItem) {
        this.$router.push({
          path: `/${this.lang}/${this.cityItem.other_name}/buildings`,
          query: queryData
        });
      }
    },
    // 猜你喜欢
    getRecommendData() {
      let params = {};
      params.url = this.$apis.api_recommend_list;
      params.data = {
        cityId: this.cityItem.id
      };
      this.$net.req(params, this).then(
        res => {
          this.recommendData = res.data;
        },
        e => {
          this.$Toast(e.msg);
        }
      );
    },
    // 清空筛选
    clean(val) {
      if (val === "roomType" || val === "other") {
        let data = this.filterCloneData;
        this.filterCloneData[val].values.forEach(element => {
          element.checked = [];
        });
        this.filterCloneData = this.$util.deepClone(data);
        this.getData(val);
        let eq = this.filterChecked.indexOf(val);
        if (eq) this.filterChecked.splice(eq, 1);
      }
    },
    // 类型筛选、排序筛选
    setSingle(item, type) {
      this[type + "Val"] = item.value;
      this.getData(type);
    },
    // 户型筛选、更多筛选
    setFilter(child, index, select, type) {
      let data = this.filterCloneData;
      let _index = data[type].values[index];
      // 判断 1单选、2多选
      if (Number(select) === 1) {
        _index.checked[0] === child.value
          ? (_index.checked = [])
          : (_index.checked[0] = child.value);
      } else {
        let eq = _index.checked.indexOf(child.value);
        if (eq === -1) {
          _index.checked.push(child.value);
        } else {
          _index.checked.splice(eq, 1);
        }
      }
      this.filterCloneData = this.$util.deepClone(data);
    },
    // 选择筛选项
    checkDroplist(index) {
      if (index === this.filterActive) {
        this.filterActive = null;
        this.showLayer = false;
      } else {
        this.filterActive = index;
        this.showLayer = true;
      }
    },
    // 搜索
    goSearch() {
      this.$router.push({
        path: `/${this.lang}/${this.cityItem.other_name}/search`
      });
    },
    // 关闭遮罩
    closeFilter() {
      this.filterActive = null;
      this.showLayer = false;
    },
    // building详情页
    handleDetail(id) {
      this.$router.push({
        path: "/" + this.lang + "/building/" + id
      });
    },
    // 返回
    goBack() {
      window.history.length > 1 ? this.$router.go(-1) : this.$router.push("/");
    }
  }
};
</script>

<style scoped lang='less'>
.home {
  header {
    background: rgba(249, 249, 249, 1);
    box-shadow: 0px 6px 10px 0px rgba(0, 0, 0, 0.05);
    padding: 10px 15px 0;
    position: relative;
    z-index: 3;
    .search-wrap {
      height: 45px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 0px 14px 0px rgba(238, 238, 238, 1);
      border-radius: 4px;
      width: 100%;
      margin-left: 15px;
      input {
        height: 45px;
        line-height: 45px;
        border-radius: 4px;
        border: 0;
        font-size: 14px;
        color: #bbb;
        width: 100%;
        padding: 4px 10px 4px 30px;
        background: rgba(249, 249, 249, 1);
      }
      input::-webkit-input-placeholder {
        color: #bbb;
      }
      .input:-moz-placeholder {
        color: #bbb;
      }
      .input:-ms-input-placeholder {
        color: #bbb;
      }
      i {
        position: absolute;
        left: 10px;
        top: 16px;
        color: #bbb;
        font-size: 14px;
      }
    }
    .filter-wrap {
      height: 44px;
      display: flex;
      justify-content: space-between;
      .droplist {
        display: none;
        width: 100vw;
        padding: 0 15px;
        left: -15px;
        top: 44px;
        background: #fff;
        z-index: 3;
        box-shadow: 0px 6px 10px 0px rgba(0, 0, 0, 0.07);
        .more {
          max-height: calc(100vh - 210px);
          overflow-y: auto;
          overflow-x: hidden;
        }
      }
      .sort-bar {
        width: 312px;
        display: flex;
        justify-content: space-around;
        height: 100%;
        .sort {
          height: 100%;
          width: 25%;
          padding: 0 10px;
          .type {
            p {
              height: 50px;
              color: #000;
              font-size: 15px;
              line-height: 50px;
              text-indent: 18px;
              border-top: 1px solid #ccc;
              i {
                margin-left: 15px;
                text-indent: 0;
                color: #ff523d;
              }
            }
            .active {
              color: #ff523d;
            }
          }
          .roomType,
          .other {
            .wrap {
              border-top: 1px solid #ccc;
              padding-bottom: 5px;
              > p {
                color: #333;
                font-size: 15px;
                margin: 15px 0;
              }
              .radio {
                flex-wrap: wrap;
                p {
                  display: flex;
                  flex-shrink: 0;
                  align-items: center;
                  justify-content: center;
                  color: #333;
                  margin: 0 15px 15px 0;
                  width: 75px;
                  height: 30px;
                  background: #eee;
                  border-radius: 4px;
                  border: 2px solid #eee;
                  font-size: 14px;
                  white-space: nowrap;
                }
                p.active {
                  color: #ff523d;
                  border-color: #ff523d;
                  background: #fff;
                }
              }
            }
            .btn {
              margin: 0 0 20px 0;
              display: flex;
              button {
                color: #333;
                font-size: 15px;
                width: 168px;
                background: rgba(242, 242, 242, 1);
                border-radius: 4px;
              }
              button:last-child {
                color: #fff;
                background: rgba(255, 82, 61, 1);
                margin-left: 10px;
              }
            }
          }
          .price {
            padding: 20px 15px;
            > p {
              font-size: 15px;
              color: #333;
            }
            button {
              width: 100%;
              height: 45px;
              background: rgba(255, 82, 61, 1);
              border-radius: 4px;
              font-size: 15px;
              font-weight: 400;
              color: #fff;
            }
          }
          > p {
            height: 100%;
            span {
              font-size: 13px;
              color: #bbb;
              margin-right: 6px;
            }
            i {
              color: #bbb;
              transition: all 0.3s;
              font-size: 10px;
              margin-top: 4px;
              transition: all 0.3s;
            }
          }
          > p.active {
            span,
            i {
              color: #ff523d;
            }
          }
        }
        .sort.active {
          > p {
            i {
              margin-top: 0;
              transform: rotate(180deg);
            }
          }
          span,
          i {
            color: #ff523d;
          }
          .droplist {
            display: block;
          }
        }
      }
      .switch {
        width: 48px;
        height: 100%;
        > i {
          font-size: 14px;
          color: #bbb;
          font-weight: bold;
          height: 100%;
          width: 100%;
        }
        .active {
          color: #ff523d;
        }
      }
      .switch.active {
        i {
          color: #ff523d;
        }
        .droplist {
          display: block;
        }
      }
      .order {
        p {
          height: 50px;
          color: #000;
          font-size: 15px;
          line-height: 50px;
          text-indent: 18px;
          border-top: 1px solid #ccc;
          i {
            margin-left: 15px;
            text-indent: 0;
            color: #ff523d;
          }
        }
      }
    }
  }
  .building-list {
    .van-pull-refresh {
      height: 100vh;
      overflow: auto;
    }
    .noData {
      > img {
        width: 68px;
        height: 75px;
        margin: 45px auto 0;
        display: flex;
      }
      > p {
        color: #ccc;
        font-size: 11px;
        text-align: center;
        margin: 10px 0 45px;
      }
      .list {
        border-top: 1px solid #eee;
        margin: 0 20px;
        > h4 {
          font-size: 20px;
          font-weight: 600;
          color: #000;
          margin: 20px 0 4px;
        }
        .items {
          padding: 20px 0;
        }
        .items:after {
          left: 0;
          right: 0;
        }
      }
    }
  }
  .layer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
    background: rgba(0, 0, 0, 0.3);
    width: 100vw;
    height: 100vh;
  }
}
</style>
