<template>
  <div class="page">
    <van-list
      v-model="isLoadingMore"
      :finished="finished"
      :immediate-check="false"
      :finished-text="total ? '没有更多了' : ''"
      @load="onLoadMore"
    >
      <div class="page-top flex flex-col justify-center items-center"></div>
      <div class="page-content">
        <div
          class="navbar flex items-center flex-col"
          :style="{ top: offsetTop }"
        >
          <nuxt-link
            :to="routePrefix + '/approve/device'"
            class="link flex items-center flex-col"
          >
            <span class="icon icon-device"></span>
            <span class="text">设备认证</span>
          </nuxt-link>
          <nuxt-link
            :to="routePrefix + '/approve/personnel/operate'"
            class="link flex items-center flex-col md:mt-6 mt-4"
          >
            <span class="icon icon-doctor"></span>
            <span class="text">体疗师认证</span>
          </nuxt-link>
        </div>

        <div class="filter">
          <div class="search">
            <el-input
              placeholder="搜索机构"
              v-model="listQuery.clubName"
              @change="onSearch"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </div>
          <div class="area">
            <RossSelectGroup @change="onCityChange" ref="citySelect" />
          </div>
        </div>

        <!-- 标题 -->
        <div class="title flex justify-between px-4 pt-8 pb-6 md:px-0">
          <div>距您最近...</div>
          <div>共<span v-text="total" class="font-bold"></span>家授权机构</div>
        </div>
        <!-- 列表 -->
        <div class="list">
          <template v-for="item in list">
            <div
              class="section flex justify-between mb-4"
              :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="mobile">{{ item.mobile || '暂无' }}</div>
                <div class="address">
                  {{ formatAddress(item.area, item.address) }}
                </div>
                <div
                  class="distance"
                  v-text="generateDistance(item.distance)"
                  v-if="item.distance && item.distance !== 99999"
                ></div>
              </div>
            </div>
          </template>
        </div>
        <!-- 列表为空 -->
        <SimpleEmpty
          v-if="!total && !isRequest"
          name="icon-empty-club.png"
          description="敬请期待~"
        ></SimpleEmpty>
      </div>
    </van-list>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { loactionSelf, geolocation } from '@/utils/map-utils'
import { drawLogo, debounce } from '@/utils'
export default {
  layout: 'app-ross',
  data() {
    return {
      isLoadingMore: true,
      finished: false,
      isRequest: true,
      list: [],
      listQuery: {
        authUserId: '',
        lngAndLat: '',
        clubName: '',
        provinceId: '',
        cityId: '',
        townId: '',
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      scrollTop: 0,
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'routePrefix', 'screenWidth', 'isPc']),
    offsetTop() {
      if (this.scrollTop <= window.innerHeight / 2) return '240px'
      return 240 + this.scrollTop - window.innerHeight / 2 + 'px'
    },
  },
  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()
    }
    window.addEventListener('scroll', () => {
      this.scrollTop = document.documentElement.scrollTop
    })
  },
  beforeDestroy() {
    this.$toast.clear()
    window.removeEventListener('scroll', () => {})
  },
  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.$nextTick(() => {
        this.$refs.citySelect.initSelectValue({
          provinceId: this.listQuery.provinceId,
          cityId: this.listQuery.cityId,
          townId: this.listQuery.townId,
        })
      })
    },

    generateDistance(value) {
      return value > 1 ? value + 'km' : value * 1000 + 'm'
    },

    // 初始化页面数据
    async initData() {
      this.listQuery.authUserId = this.authUserId

      // 自定义加载图标
      this.$toast.loading({
        message: '正在获取您附近的机构...',
        duration: 0,
      })

      // 获取定位信息 这里使用的是高德地图获取用户具体位置信息
      try {
        const resLocation = await geolocation()
        this.listQuery.lngAndLat = `${resLocation.position.lng},${resLocation.position.lat}`
      } catch (error) {
        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),
    // 城市变化
    onCityChange(valueMap) {
      const { provinceId, cityId, townId } = valueMap
      this.listQuery.provinceId = provinceId
      this.listQuery.cityId = cityId
      this.listQuery.townId = townId

      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">
.el-input {
  ::v-deep {
    & > {
      .el-input.is-active .el-input__inner,
      .el-input__inner:focus {
        @include themify($themes) {
          border-color: themed('color');
        }
      }
    }
  }
}

// pc 端
@media screen and (min-width: 768px) {
  .page {
    position: relative;
    min-height: calc(100vh - 80px - 80px);
    background-color: #fff;
  }
  .page-top {
    height: 530px;
    @include themify($themes) {
      background-image: themed('pc-banner-club');
    }
    background-size: cover;
    background-position: center;
  }
  .page-content {
    position: relative;
    width: 1000px;
    margin: 0 auto;

    .title {
      font-size: 16px;
      color: #404040;

      span {
        @include themify($themes) {
          color: themed('color');
        }
      }
    }

    .filter {
      padding: 48px 0 105px;
      .search {
        width: 640px;
        margin: 0 auto;
        .el-input {
          height: 46px;
          font-size: 16px;
          .el-input__icon {
            font-size: 24px;
            line-height: 46px;
            margin-left: 12px;
          }

          ::v-deep {
            & > .el-input__inner {
              height: 46px;
              padding-left: 55px;
            }
          }
        }
      }
    }

    .navbar {
      position: absolute;
      top: 240px;
      right: -168px;
      width: 120px;
      border-radius: 16px;
      background: #fff;
      box-shadow: 0px 6px 20px rgba(40, 40, 40, 0.1);
      padding: 24px 0;
      box-sizing: border-box;
      z-index: 2;
      .link {
        &:hover {
          .icon {
            &.icon-device {
              background: url(~assets/theme-images/ross/pc-nav-entry-device-active.png)
                  no-repeat center center,
                linear-gradient(180deg, #ffba63 0%, #f3920d 100%);
              background-size: 48px, 100%;
            }
            &.icon-doctor {
              background: url(~assets/theme-images/ross/pc-nav-entry-doctor-active.png)
                  no-repeat center center,
                linear-gradient(180deg, #ffba63 0%, #f3920d 100%);
              background-size: 48px, 100%;
            }
          }
          .text {
            @include themify($themes) {
              color: themed('color');
            }
          }
        }

        span {
          display: block;
        }

        .icon {
          width: 72px;
          height: 72px;
          // background: linear-gradient(180deg, #ffba63 0%, #f3920d 100%);
          background-color: #f6f6f7;
          border-radius: 12px;

          &.icon-device {
            background: url(~assets/theme-images/ross/pc-nav-entry-device.png)
              no-repeat center center #f6f6f7;
            background-size: 48px;
          }

          &.icon-doctor {
            background: url(~assets/theme-images/ross/pc-nav-entry-doctor.png)
              no-repeat center center #f6f6f7;
            background-size: 48px;
          }
        }

        .text {
          font-size: 16px;
          color: #404040;
          margin-top: 8px;
        }
      }
    }

    .list {
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;

      .empty {
        width: 390px;
      }

      .section {
        width: 490px;
        height: 136px;
        background-color: #f3f5f6;
        border-radius: 4px;
        box-sizing: border-box;
        padding: 16px;
        cursor: pointer;
        transition: all 0.4s;
        &:hover {
          box-shadow: 0 0 24px rgba(0, 0, 0, 0.2);
        }

        .cover {
          display: block;
          width: 104px;
          height: 104px;
        }
        .info {
          position: relative;
          margin-left: 12px;
          width: 330px;
          .name {
            width: 200px;
            font-size: 18px;
            color: #101010;
            font-weight: bold;
            margin-bottom: 24px;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
          }
          .mobile,
          .address {
            width: 268px;
            position: relative;
            font-size: 14px;
            color: #404040;
            padding-left: 24px;
            line-height: 24px;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-top: 6px;
            overflow: hidden;
            &::after {
              content: '';
              display: block;
              width: 16px;
              height: 16px;
              position: absolute;
              left: 0;
              top: 50%;
              transform: translateY(-50%);
              background-size: 16px;
              background-repeat: no-repeat;
            }
          }
          .mobile {
            &::after {
              background-image: url(~assets/theme-images/common/pc-icon-mobile.png);
            }
          }
          .address {
            &::after {
              background-image: url(~assets/theme-images/common/pc-icon-address.png);
            }
          }

          .distance {
            position: absolute;
            font-size: 14px;
            color: #404040;
            top: 2px;
            right: 0;
          }
        }
      }
    }
  }
}

// 移动 端
@media screen and (max-width: 768px) {
  .page-top {
    height: 100vw;
    @include themify($themes) {
      background: themed('h5-banner-club');
    }
    background-size: 100vw 100vw !important;

    .logo {
      display: block;
      width: 14.8vw;
      height: 14.8vw;
      border-radius: 50%;
      background: #fff;
    }
    .name {
      font-size: 4vw;
      color: #fff;
    }
  }
  .page-content {
    position: relative;

    .title {
      font-size: 3.4vw;
      color: #404040;

      span {
        @include themify($themes) {
          color: themed('color');
        }
      }
    }

    .filter {
      padding: 6.4vw 3.2vw 12.8vw;
    }

    .navbar {
      position: fixed;
      top: 50% !important;
      right: 3.2vw;
      left: unset !important;
      width: 14vw;
      border-radius: 1.6vw;
      background: #fff;
      box-shadow: 0px 0.6vw 2vw rgba(40, 40, 40, 0.1);
      padding: 2.8vw 0;
      box-sizing: border-box;
      z-index: 2;
      span {
        display: block;
      }

      .icon {
        position: relative;
        width: 7.2vw;
        height: 7.2vw;
        border-radius: 1.2vw;
        background: linear-gradient(180deg, #ffba63 0%, #f3920d 100%);

        &.icon-device,
        &.icon-doctor {
          &::after {
            content: '';
            display: block;
            width: 4.8vw;
            height: 4.8vw;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            background-size: 4.8vw !important;
          }
        }

        &.icon-device {
          &::after {
            background: url(~assets/theme-images/ross/pc-nav-entry-device-active.png)
              no-repeat center;
          }
        }

        &.icon-doctor {
          &::after {
            background: url(~assets/theme-images/ross/pc-nav-entry-doctor-active.png)
              no-repeat center;
          }
        }
      }

      .text {
        font-size: 2.4vw;
        color: #f3920d;
        margin-top: 1.2vw;
      }
    }
  }

  .list {
    display: flex;
    align-items: center;
    flex-direction: column;

    .section {
      width: 93.6vw;
      height: 26vw;
      background-color: #f3f5f6;
      border-radius: 4px;
      box-sizing: border-box;
      padding: 3.2vw;

      .cover {
        display: block;
        width: 19.6vw;
        height: 19.6vw;
      }
      .info {
        position: relative;
        margin-left: 3.2vw;
        .name {
          width: 48vw;
          font-size: 4vw;
          color: #101010;
          font-weight: bold;
          margin-bottom: 4vw;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
        }
        .mobile,
        .address {
          width: 66vw;
          position: relative;
          font-size: 3vw;
          color: #404040;
          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(~assets/theme-images/common/h5-icon-mobile.png);
          }
        }
        .address {
          &::after {
            background-image: url(~assets/theme-images/common/h5-icon-address.png);
          }
        }

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