<template>
  <div class="page">
    <van-list
      v-model="isLoadingMore"
      :finished="finished"
      :immediate-check="false"
      :finished-text="total ? '没有更多了' : ''"
      @load="onLoadMore"
    >
      <div class="page-top"></div>
      <div class="page-content">
        <!-- 搜索区域 -->
        <div class="search flex justify-center">
          <input
            type="text"
            placeholder="搜索店铺"
            v-model="listQuery.clubName"
            @keyup.enter="onSearch"
          />
        </div>
        <!-- 地区筛选 -->
        <div class="city">
          <LdmCity
            ref="citySelect"
            @change="onCityChange"
            :options="cityList"
            labelName="name"
            valueName="id"
          ></LdmCity>
        </div>
        <!-- 标题 -->
        <div class="title">距你最近...</div>
        <!-- 机构列表 -->
        <div class="list">
          <div
            class="section flex items-center"
            v-for="item in list"
            :key="item.authId"
            @click="toDetail(item)"
          >
            <img class="cover" :src="item.logo || drawLogo(item.clubName)" />
            <div class="info">
              <div class="name" v-text="item.clubName"></div>
              <div class="line"></div>
              <div class="mobile">{{ item.mobile || '未知' }}</div>
              <div class="address">
                {{ formatAddress(item.area, item.address) }}
              </div>
              <div
                class="distance"
                v-text="item.distance + 'km'"
                v-if="item.distance && item.distance !== 99999"
              ></div>
            </div>
          </div>
        </div>
        <!-- 列表为空 -->
        <LdmEmpty v-if="!total && !isRequest" name="ldm-empty.png"></LdmEmpty>
      </div>
    </van-list>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { loactionSelf } from '@/utils/map-utils'
import { debounce, drawLogo } from '@/utils'
export default {
  layout: 'app-ldm',
  data() {
    return {
      isLoadingMore: true,
      finished: false,
      isRequest: true,
      list: [],
      listQuery: {
        authUserId: '',
        lngAndLat: '',
        clubName: '',
        provinceId: '',
        cityId: '',
        townId: '',
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      cityList: [],
      selectValue: [],
    }
  },
  computed: {
    ...mapGetters(['supplierInfo', 'authUserId', 'routePrefix']),
    emptyList() {
      return 3 - (this.list.length % 3)
    },
  },
  mounted() {
    const cacheData = this.$getStorage(this.routePrefix, 'club_list_data')
    if (cacheData) {
      this.initFromCache(cacheData)
      this.$removeStorage(this.routePrefix, 'club_list_data')
    } else {
      this.initData()
      this.fetchCityList()
    }
  },
  beforeDestroy() {
    this.$toast.clear()
  },
  methods: {
    // 绘制logo的方法
    drawLogo,
    // 查看详情
    toDetail(item) {
      this.$setStorage(this.routePrefix, 'club_list_data', this.$data, {
        expiredTime: 5 * 60 * 1000,
      })
      this.$setStorage(this.routePrefix, 'clubInfo', item)
      const url = `${this.routePrefix}/approve/club/detail?id=${item.authId}`
      this.$router.push(url)
    },
    // 从缓存中获取数据
    initFromCache(cacheData) {
      this.isLoadingMore = cacheData.isLoadingMore
      this.finished = cacheData.finished
      this.isRequest = cacheData.isRequest
      this.list = cacheData.list
      this.listQuery = cacheData.listQuery
      this.total = cacheData.total
      this.cityList = cacheData.cityList
      this.selectValue = cacheData.selectValue
      this.$refs.citySelect.setSelectValue(this.selectValue)
    },
    // 初始化页面数据
    async initData() {
      this.listQuery.authUserId = this.authUserId
      // 自定义加载图标
      this.$toast.loading({
        message: '正在获取您附近的机构...',
        duration: 0,
      })

      // 获取定位信息 百度坐标转高德坐标
      try {
        const location = await loactionSelf()
        const result = await this.$http.api.assistant({
          key: '1bcc97330f6cf517e8dd9d5278957e67',
          locations: `${location.point.lng},${location.point.lat}`,
          coordsys: 'baidu',
          output: 'JSON',
        })
        const res = await result.json()
        this.listQuery.lngAndLat = res.locations
      } catch (error) {
        this.$toast.clear()
        this.$toast('获取定位信息失败，请确保您开启的定位权限并保存网络畅通')
        this.isRequest = false
      }

      // 获取机构列表
      this.fetchList()
    },
    // 获取机构列表
    fetchList: debounce(async function () {
      try {
        this.isLoadingMore = true
        const res = await this.$http.api.getAuthClubList(this.listQuery)
        this.total = res.data.total
        this.list = [...this.list, ...res.data.list]
        this.finished = !res.data.hasNextPage
        this.isLoadingMore = false
        this.listQuery.pageNum += 1
      } catch (error) {
        console.log(error)
      } finally {
        this.$toast.clear()
        this.isRequest = false
      }
    }, 400),

    // 获取地址列表
    fetchCityList() {
      this.$http.api.fetchAllCityList().then((res) => {
        this.cityList = res.data
      })
    },
    // 城市变化
    onCityChange(selectValue) {
      this.listQuery.provinceId = ''
      this.listQuery.cityId = ''
      this.listQuery.townId = ''

      this.selectValue = selectValue

      selectValue.map((item, index) => {
        if (index === 0) {
          this.listQuery.provinceId = item.id
        } else if (index === 1) {
          this.listQuery.cityId = item.id
        } else {
          this.listQuery.townId = item.id
        }
      })
      this.listQuery.pageNum = 1
      this.list = []
      this.fetchList()
    },
    // 搜索
    onSearch() {
      this.listQuery.pageNum = 1
      this.list = []
      this.fetchList()
    },
    // 格式化地址
    formatAddress(a1, a2) {
      let resutl = ''
      if (typeof a1 === 'string') {
        resutl += a1
      }
      if (typeof a2 === 'string') {
        resutl += a2
      }
      return resutl || '未知'
    },
    // 加载更多
    onLoadMore() {
      this.fetchList()
    },
  },
}
</script>

<style scoped lang="scss">
@media screen and (min-width: 768px) {
  .page-top {
    height: 596px;
    background: url(https://static.caimei365.com/www/authentic/pc/ldm-bg-club.png)
      no-repeat center;
    background-size: auto 596px;
  }
  .page-content {
    width: 836px;
    margin: 0 auto;
    overflow: hidden;

    .city {
      position: relative;
      z-index: 99;
    }

    .search {
      width: 836px;
      position: relative;
      margin: 69px auto 40px;
      input {
        display: block;
        width: 100%;
        height: 56px;
        border: 0.1vw solid #000000;
        box-sizing: border-box;
        padding-left: 80px;
        font-size: 24px;
      }

      &::after {
        position: absolute;
        left: 33px;
        top: 50%;
        transform: translateY(-50%);
        content: '';
        display: block;
        width: 37px;
        height: 37px;
        background: url(https://static.caimei365.com/www/authentic/pc/ldm-icon-search.png)
          no-repeat center;
        background-size: 37px;
      }
    }

    .title {
      text-align: right;
      font-size: 22px;
      color: #000;
    }
    .list {
      padding-top: 24px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
      .section {
        width: 409px;
        background: #f1f1f1;
        border-radius: 20px;
        padding: 16px;
        box-sizing: border-box;
        margin-bottom: 20px;
        cursor: pointer;

        .cover {
          width: 92px;
          height: 92px;
          border-radius: 17px;
        }
        .info {
          position: relative;
          width: 263px;
          margin-left: 23px;
          .name {
            width: 200px;
            position: relative;
            font-size: 15px;
            color: #000;
            font-weight: bold;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            padding-left: 20px;
            line-height: 20px;

            &::after {
              content: '';
              display: block;
              width: 20px;
              height: 20px;
              position: absolute;
              left: 0;
              top: 50%;
              transform: translateY(-50%);
              background-size: 20px 20px;
              background-repeat: no-repeat;
              background-position: left center;
            }
          }

          .name {
            &::after {
              background-image: url(https://static.caimei365.com/www/authentic/pc/ldm-icon-store.png);
            }
          }
          .line {
            height: 1px;
            margin: 14px 0;
            background: rgba(0, 0, 0, 0.169);
          }
          .mobile,
          .address {
            position: relative;
            font-size: 12px;
            color: #000000;
            padding-left: 20px;
            line-height: 20px;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;

            &::after {
              content: '';
              display: block;
              width: 24px;
              height: 24px;
              position: absolute;
              left: 0;
              top: 50%;
              transform: translateY(-50%);
              background-size: 24px 24px;
              background-repeat: no-repeat;
              background-position: left center;
            }
          }
          .mobile {
            &::after {
              background-image: url(https://static.caimei365.com/www/authentic/pc/ldm-icon-contact.png);
            }
          }
          .address {
            &::after {
              background-image: url(https://static.caimei365.com/www/authentic/pc/ldm-icon-address.png);
            }
          }

          .distance {
            position: absolute;
            font-size: 12px;
            color: #404040;
            top: 0.2vw;
            right: 0;
          }
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .page-top {
    height: 59.6vw;
    background: url(https://static.caimei365.com/www/authentic/h5/ldm-bg-club.png);
    background-size: auto 59.6vw;
  }
  .page-content {
    overflow: hidden;
    .search {
      width: 86vw;
      position: relative;
      margin: 7.6vw auto 5.6vw;
      input {
        display: block;
        width: 100%;
        height: 8vw;
        border: 0.1vw solid #000000;
        box-sizing: border-box;
        padding-left: 10.5vw;
      }

      &::after {
        position: absolute;
        left: 2.9vw;
        top: 50%;
        transform: translateY(-50%);
        content: '';
        display: block;
        width: 5.4vw;
        height: 5.4vw;
        background: url(https://static.caimei365.com/www/authentic/h5/ldm-icon-search.png)
          no-repeat center;
        background-size: 5.4vw;
      }
    }

    .title {
      text-align: right;
      padding-right: 6.6vw;
      font-size: 3.5vw;
      color: #000;
    }
    .list {
      display: flex;
      flex-direction: column;
      align-items: center;
      .section {
        width: 95.1vw;
        background: #f1f1f1;
        border-radius: 2vw;
        padding: 3.2vw;
        box-sizing: border-box;
        margin-top: 5.7vw;

        .cover {
          width: 21.5vw;
          height: 21.5vw;
          border-radius: 1.7vw;
        }
        .info {
          position: relative;
          width: 61.3vw;
          margin-left: 5.8vw;
          .name {
            width: 46vw;
            position: relative;
            font-size: 3.5vw;
            color: #000;
            font-weight: bold;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            padding-left: 5vw;
            line-height: 5vw;

            &::after {
              content: '';
              display: block;
              width: 4vw;
              height: 4vw;
              position: absolute;
              left: 0;
              top: 50%;
              transform: translateY(-50%);
              background-size: 4vw;
              background-repeat: no-repeat;
            }
          }

          .name {
            &::after {
              background-image: url(https://static.caimei365.com/www/authentic/h5/ldm-icon-store.png);
            }
          }
          .line {
            height: 0.1vw;
            margin: 2.8vw 0;
            background: rgba(0, 0, 0, 0.169);
          }
          .mobile,
          .address {
            position: relative;
            font-size: 3vw;
            color: #000000;
            padding-left: 5vw;
            line-height: 5vw;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;

            &::after {
              content: '';
              display: block;
              width: 4vw;
              height: 4vw;
              position: absolute;
              left: 0;
              top: 50%;
              transform: translateY(-50%);
              background-size: 4vw 4vw;
              background-repeat: no-repeat;
            }
          }
          .mobile {
            &::after {
              background-image: url(https://static.caimei365.com/www/authentic/h5/ldm-icon-contact.png);
            }
          }
          .address {
            &::after {
              background-image: url(https://static.caimei365.com/www/authentic/h5/ldm-icon-address.png);
            }
          }

          .distance {
            position: absolute;
            font-size: 3vw;
            color: #404040;
            top: 0.2vw;
            right: 0;
          }
        }
      }
    }
  }
}
</style>
