<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app'
import {
  getParkServiceOil,
  getParkServicePower,
  getParkServiceShopList,
  getParkServiceScenicList,
  getParkServiceFacility,
  getParkServiceNoticeList,
  getBannerApi
} from '@/api/home'
import { h5PhoneLoginApi } from '@/api/login'
import { useListLoader } from '@/composables/useListLoader'
import { useGlobal } from '@/composables/index'
import { user } from '@/stores/modules/user'

const { minioUrl, pathPre } = useGlobal()
const userStore = user()

const angle = ref(45)
// 监听页面滚动
onPageScroll((e) => {
  if (e.scrollTop > 80) {
    angle.value = 90
  } else {
    angle.value = 45
  }
})

// 轮播图数据
const list = ref([`${minioUrl}/home_banner.png`])

const tabs = ref([{ name: '加油' }, { name: '充电' }])
const tabActive = ref(0)

// 金刚区列表
const navList = ref([
  { image: `${minioUrl}/icon_nav_01.png`, text: '我要加油', path: '/base/common/refuel', w: '53rpx', h: '53rpx' },
  { image: `${minioUrl}/icon_nav_02.png`, text: '我要充电', path: '/base/common/charge', w: '60rpx', h: '53rpx' },
  { image: `${minioUrl}/icon_nav_03.png`, text: '我要吃饭', path: '/base/shop/meal', w: '57rpx', h: '57rpx' },
  { image: `${minioUrl}/icon_nav_04.png`, text: '我要修车', path: '/base/common/repair', w: '60rpx', h: '56rpx' },
  { image: `${minioUrl}/icon_nav_05.png`, text: '投诉建议', path: '/base/suggest/index', w: '59rpx', h: '53rpx' },
  { image: `${minioUrl}/icon_nav_06.png`, text: '一键救援', path: '', w: '76rpx', h: '76rpx', type: 'popup' },
  { image: `${minioUrl}/icon_nav_07.png`, text: '司机之家', path: '/base/common/driversHome', w: '76rpx', h: '76rpx' },
  { image: `${minioUrl}/icon_nav_08.png`, text: '母婴室', path: '/base/common/nursingRoom', w: '76rpx', h: '76rpx' },
  { image: `${minioUrl}/icon_nav_09.png`, text: '失物招领', path: '', w: '76rpx', h: '76rpx', type: 'popup' },
  { image: `${minioUrl}/icon_nav_10.png`, text: '招商加盟', path: '/base/common/join', w: '76rpx', h: '76rpx' }
])

const selectedValue = ref('')

// 一键救援弹窗展示
const isRescueShow = ref(false)
// 失物招领弹窗展示
const isLostFoundShow = ref(false)

onLoad((options) => {
  const m = options?.m || ''
  if (m) {
    h5PhoneLoginApi(m).then((res: any) => {
      const token = res.data.token || ''
      if (token) {
        uni.setStorageSync('token', token)
        userStore.setToken(token)
      }
    })
  }
  // 页面加载时从本地缓存获取园区ID
  // const cachedParkId = uni.getStorageSync('parkId')
  // if (cachedParkId) {
  //   selectedValue.value = cachedParkId
  //   params.value.parkId = cachedParkId
  // }
})

const init = () => {
  // 获取我要加油数据
  getOilList()
  // 获取我要充电数据
  getPowerList()
  // 获取精选商家数据
  getShopList()
  // 获取服务设施数据
  getFacilityList()
  // 获取出行提醒数据
  getNoticeList()
  // 获取banner数据
  // getBannerList()
}

// 处理园区选择变化
const handleParkChange = () => {
  params.value.parkId = selectedValue.value
  oilInfo.value = {}
  listOli.value = []
  powerInfo.value = {}
  // 初始化数据
  init()
  // 重新加载列表数据
  handleSearch()
}

onShow(() => {
  if (selectedValue.value) {
    params.value.parkId = selectedValue.value
    // 初始化数据
    init()
  }
})

// 获取banner数据
const bannerList = ref<any>([])
const getBannerList = async () => {
  const res = (await getBannerApi()) as any
  if (res.data) {
    bannerList.value = res.data.map((item: any) => item.imageInfo?.url)
  }
}

// 获取我要加油数据
const oilInfo = ref<any>({})
const listOli = ref<any>([])
const getOilList = async () => {
  const res = (await getParkServiceOil(selectedValue.value)) as any
  if (res.data) {
    oilInfo.value = JSON.parse(res.data.content)
    const {
      oil92ActivityPrice,
      oil92OriginalPrice,
      oil95ActivityPrice,
      oil95OriginalPrice,
      oil89ActivityPrice,
      oil89OriginalPrice,
      dieselActivityPrice,
      dieselOriginalPrice
    } = oilInfo.value
    const _list = [
      { name: '92#', activityPrice: oil92ActivityPrice, originalPrice: oil92OriginalPrice },
      { name: '95#', activityPrice: oil95ActivityPrice, originalPrice: oil95OriginalPrice },
      { name: '89#', activityPrice: oil89ActivityPrice, originalPrice: oil89OriginalPrice },
      { name: '柴油#', activityPrice: dieselActivityPrice, originalPrice: dieselOriginalPrice }
    ]
    listOli.value = _list
  }
}

// 获取我要充电数据
const powerInfo = ref<any>({})
const getPowerList = async () => {
  const res = (await getParkServicePower(selectedValue.value)) as any
  if (res.data) {
    powerInfo.value = JSON.parse(res.data.content)
  }
}

// 获取精选商家数据
const shopList = ref<any>([])
const getShopList = async () => {
  const res = (await getParkServiceShopList({ parkId: selectedValue.value })) as any
  shopList.value = res.rows.slice(0, 5).map((item: any) => ({
    ...item,
    content: JSON.parse(item.content)
  }))
}

// 获取服务设施数据
const facilityList = ref<any>([])
const getFacilityList = async () => {
  const res = (await getParkServiceFacility({
    parkId: selectedValue.value
  })) as any
  facilityList.value = res.rows
    .slice(0, 6)
    .reverse()
    .map((item: any) => ({
      ...item,
      content: JSON.parse(item.content)
    }))
}

// 获取附近景区数据
const scenicList = computed(() => {
  return listData.value.map((item: any) => ({
    ...item,
    content: JSON.parse(item.content)
  }))
})

// 获取出行提醒数据
const noticeList = ref<any>([])
const getNoticeList = async () => {
  const res = (await getParkServiceNoticeList({
    top: 1
  })) as any
  noticeList.value = res.rows.map((v: any) => v.title)
}

// 列表加载
const { listData, upCallback, downCallback, handleSearch, mescrollInit, params } = useListLoader({
  apiFn: getParkServiceScenicList,
  initialParams: {
    parkId: selectedValue.value
  }
})

// 金刚区点击事件
const navClick = (item: { path: string; type?: string; text?: string }) => {
  if (item.type === 'popup') {
    // 弹窗展示
    if (item.text === '一键救援') {
      isRescueShow.value = true
    } else if (item.text === '失物招领') {
      isLostFoundShow.value = true
    }
    return
  }
  uni.navigateTo({
    url: item.path
  })
}

// 出行提示点击事件
const navigateToTips = () => {
  uni.navigateTo({
    url: '/base/travel/tips'
  })
}

// 精选商家点击事件
const navigateToShop = () => {
  uni.navigateTo({
    url: '/base/shop/index'
  })
}

// 精选商家详情点击事件
const navigateToShopDetail = (id: string) => {
  uni.navigateTo({
    url: '/base/shop/detailsShop?id=' + id
  })
}

// 景点点击事件
const navigateToSpot = (id: string) => {
  uni.navigateTo({
    url: '/base/common/spot?id=' + id
  })
}

// 导航功能
const goToNavigation = (longitude: string, latitude: string, name: string) => {
  uni.openLocation({
    latitude: Number(latitude),
    longitude: Number(longitude),
    name: name,
    success: () => {
      console.log('导航功能调用成功')
    }
  })
}

// 拨打电话
const callPhone = (phone: string) => {
  uni.makePhoneCall({
    phoneNumber: phone
  })
}
</script>

<template>
  <mescroll-body
    @init="mescrollInit"
    :down="{ use: false, minAngle: angle }"
    :bottombar="false"
    :up="{ bgColor: '#f6f7fb', textColor: '#999', empty: { use: false } }"
    @down="downCallback"
    @up="upCallback"
  >
    <view class="index-container">
      <!-- 头部背景 -->
      <view class="header-bg" :style="{ backgroundImage: 'url(' + minioUrl + '/index_bg.png)' }"></view>
      <!-- header -->
      <view class="index-header-wrapper">
        <image :src="minioUrl + '/logo.png'" mode="aspectFill" class="logo" />
        <view class="header-right-wrap">
          <view class="top-title-box">
            <HySelect v-model="selectedValue" @change="handleParkChange" />
          </view>
          <image class="star-img" :src="minioUrl + '/star.png'" mode="aspectFill" />
          <view class="bottom-box">
            <!-- 天气 -->
            <iframe
              scrolling="no"
              src="https://widget.tianqiapi.com/?style=tv&skin=cucumber&color=333"
              frameborder="0"
              width="130"
              height="25"
              allowtransparency="true"
            ></iframe>
            <!-- 营业状态 -->
            <view class="bottom-tag-item">正常营业</view>
          </view>
        </view>
      </view>
      <!-- 轮播图 -->
      <u-swiper :height="306" :list="list"></u-swiper>
      <!-- 金刚区 -->
      <view class="index-nav-wrapper">
        <view class="nav-item" v-for="(item, index) in navList" :key="index" @click="navClick(item)">
          <view class="nav-image">
            <image :src="item.image" mode="aspectFill" :style="{ width: item.w, height: item.h }" />
          </view>
          <view class="nav-item-text">{{ item.text }}</view>
        </view>
      </view>
      <!-- 出行提示 -->
      <view class="index-tips-wrapper" @click="navigateToTips">
        <image class="tips-img" :src="minioUrl + '/icon_chuxing.png'" mode="scaleToFill" />
        <view class="tips-line"></view>
        <u-notice-bar
          mode="vertical"
          style="width: 100%"
          :list="noticeList"
          :volume-icon="false"
          type="none"
          padding="10rpx"
          font-size="25"
          color="#333"
        ></u-notice-bar>
      </view>
      <!-- 加油充电 -->
      <view class="index-tabs-wrapper">
        <u-tabs
          v-model="tabActive"
          :list="tabs"
          active-color="#333"
          :font-size="31"
          :height="60"
          :gutter="20"
          :bar-style="{
            width: '30rpx',
            height: '6rpx',
            backgroundImage: 'linear-gradient(90deg, #0f91f8 0%, #32a9c8 68%, #54c197 100%), linear-gradient(#6c85fc, #6c85fc)',
            backgroundBlendMode: 'normal, normal',
            borderRadius: '2rpx'
          }"
        ></u-tabs>
        <template v-if="tabActive === 0">
          <view class="tab-station-wrap" v-if="listOli.length > 0">
            <HyStation v-for="(item, index) in listOli" :key="index" :item="item"></HyStation>
          </view>
          <view class="no-data-wrap" v-else>
            <u-empty />
          </view>
        </template>
        <template v-if="tabActive === 1">
          <view class="tab-station-wrap column" v-if="powerInfo?.fastChargeTotal > 0">
            <HyCharge
              title="快充"
              :freeNum="powerInfo?.fastChargeFree"
              :totalNum="powerInfo?.fastChargeTotal"
              :status="powerInfo?.fastChargeStatus"
            />
            <HyCharge
              title="慢充"
              :freeNum="powerInfo?.slowChargeFree"
              :totalNum="powerInfo?.slowChargeTotal"
              :status="powerInfo?.slowChargeStatus"
            />
          </view>
          <view class="no-data-wrap" v-else>
            <u-empty />
          </view>
        </template>
      </view>
      <!-- 服务设施 -->
      <HyCard title="服务设施" :marginBottom="24">
        <view class="index-service-wrapper" v-if="facilityList.length > 0">
          <HyService v-for="(item, index) in facilityList" :key="index" :item="item"></HyService>
        </view>
        <view class="no-data-wrap" v-else>
          <u-empty text="暂无服务设施数据" />
        </view>
      </HyCard>
      <!-- 人气优选商家 -->
      <HyCard title="人气优选商家" rightText="更多商家" isShowRight :marginBottom="24" @clickRight="navigateToShop">
        <view class="index-shop-wrapper" v-if="shopList.length > 0">
          <view class="shop-item" v-for="(item, index) in shopList" :key="index" @click="navigateToShopDetail(item.id)">
            <view class="img-wrap">
              <image :src="pathPre + item.content.image" mode="aspectFill" />
            </view>
            <view class="item-text u-line-1">{{ item.title }}</view>
          </view>
        </view>
        <view class="no-data-wrap" v-else>
          <u-empty text="暂无商家数据" />
        </view>
      </HyCard>
      <!-- 附近景点 -->
      <HyCard title="附近景点" isBg :bgImg="minioUrl + '/index_spot_bg.png'">
        <view class="index-spot-wrapper" v-if="scenicList.length > 0">
          <view class="spot-item" v-for="(item, index) in scenicList" :key="index" @click="navigateToSpot(item.id)">
            <view class="spot-img-wrap">
              <image :src="pathPre + item.content.image" mode="aspectFill" />
            </view>
            <view class="spot-right-wrap">
              <view class="right-header">
                <view class="title">{{ item.title }}</view>
                <view class="price">{{ item.content.isFree === 1 ? '免费' : item.content.price + '元' }}</view>
              </view>
              <view class="right-tag-box">
                <view class="s-tag-green" v-for="(tag, index) in item.content.tags" :key="index">{{ tag }}</view>
              </view>
              <view class="right-location-box">
                <view class="left">
                  <image class="icon-address" :src="minioUrl + '/icon_address.png'" mode="aspectFill" />
                  <view class="address-text-wrap"
                    >距您<text>{{ item.content.distance }}</text
                    >公里，驾车预计<text>{{ item.content.driveTime }}</text
                    >分钟</view
                  >
                </view>
                <view class="right-go-icon" @click.stop="goToNavigation(item.content.longitude, item.content.latitude, item.title)">
                  <image :src="minioUrl + '/icon_go.png'" mode="aspectFill" />
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="no-data-wrap" v-else>
          <u-empty text="暂无景点数据" />
        </view>
      </HyCard>
      <!-- 一键救援 -->
      <HyPopup v-model="isRescueShow" width="700rpx" showClose>
        <view class="popup-content-wrapper">
          <view class="popup-content-item" @click="callPhone('96659')">
            <view class="p-item-left">
              <view class="left-title">车辆救援</view>
              <view class="left-sub-title">山东高速集团出行服务热线</view>
            </view>
            <view class="p-item-right">
              <view class="mobile">96659</view>
              <view class="icon-box">
                <u-icon name="phone-fill" color="#fff" size="24"></u-icon>
              </view>
            </view>
          </view>
          <view class="popup-content-item" @click="callPhone('12122')">
            <view class="p-item-left">
              <view class="left-title">事故报警</view>
              <view class="left-sub-title">山东高速交警报警热线</view>
            </view>
            <view class="p-item-right">
              <view class="mobile">12122</view>
              <view class="icon-box">
                <u-icon name="phone-fill" color="#fff" size="24"></u-icon>
              </view>
            </view>
          </view>
        </view>
      </HyPopup>
      <!-- 失物招领 -->
      <HyPopup v-model="isLostFoundShow" width="700rpx" showClose>
        <view class="popup-content-wrapper">
          <view class="popup-content-item column" @click="callPhone('0532-8889999')">
            <view class="column-title">失物招领</view>
            <view class="column-mobile">0532-8889999</view>
            <view class="icon-box">
              <u-icon name="phone-fill" color="#fff" size="24"></u-icon>
            </view>
          </view>
        </view>
      </HyPopup>
    </view>
  </mescroll-body>
</template>

<style lang="scss" scoped>
.no-data-wrap {
  width: 100%;
  height: 400rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}
.popup-content-wrapper {
  height: 330rpx;
  background-color: #fff;
  border-radius: 14rpx;
  .popup-content-item {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 48rpx 48rpx 24rpx 48rpx;
    &.column {
      flex-direction: column;
      justify-content: center;
      .column-title {
        font-size: 28rpx;
        color: #607f2f;
      }
      .column-mobile {
        font-size: 42rpx;
        color: #333;
        font-weight: 600;
        margin: 40rpx 0;
      }
      .icon-box {
        width: 48rpx;
        height: 48rpx;
        background-color: #247d54;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        margin-left: 16rpx;
      }
    }
    .p-item-left {
      display: flex;
      flex-direction: column;
      .left-title {
        font-size: 28rpx;
        color: #607f2f;
      }
      .left-sub-title {
        font-size: 24rpx;
        color: #999;
        margin-top: 8rpx;
      }
    }
    .p-item-right {
      display: flex;
      align-items: center;
      .mobile {
        font-size: 42rpx;
        color: #333;
        font-weight: 600;
      }
      .icon-box {
        width: 48rpx;
        height: 48rpx;
        background-color: #247d54;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        margin-left: 16rpx;
      }
    }
  }
}
:deep(.mescroll-upwarp) {
  padding-top: 0;
}
.index-container {
  width: 100%;
  min-height: 100dvh;
  position: relative;
  box-sizing: border-box;
  padding: 24rpx;
  background-color: #f6f7fb;
  .header-bg {
    width: 100%;
    height: 494rpx;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: 100% 494rpx;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }
  .index-header-wrapper {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    padding-left: 33rpx;
    position: relative;
    z-index: 2;
    margin-bottom: 24rpx;
    .logo {
      width: 105rpx;
      height: 92rpx;
    }
    .header-right-wrap {
      display: flex;
      flex-direction: column;
      margin-left: 24rpx;
      .top-title-box {
        display: flex;
        align-items: center;
        .title-text {
          font-size: 30rpx;
          color: #3b3c3b;
          font-weight: 600;
        }
        image {
          width: 13rpx;
          height: 10rpx;
          margin-left: 8rpx;
        }
      }
      .star-img {
        width: 146rpx;
        height: 27rpx;
      }
      .bottom-box {
        display: flex;
        align-items: center;
        margin-top: 10rpx;
        .bottom-tag-item {
          font-size: 17rpx;
          color: #fff;
          box-sizing: border-box;
          padding: 0 12rpx;
          background-color: #3bb0b9;
          border-radius: 8rpx;
          line-height: 40rpx;
          margin-top: -15rpx;
        }
      }
    }
  }
  :deep(.u-swiper-wrap) {
    position: relative;
    z-index: 1;
  }
  .index-nav-wrapper {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: space-around;
    margin-top: 40rpx;
    .nav-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 20%;
      .nav-image {
        width: 76rpx;
        height: 76rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 14rpx;
      }
      &:nth-child(-n + 5) {
        margin-bottom: 50rpx;
      }
    }
  }
  .index-tips-wrapper {
    width: 100%;
    height: 84rpx;
    border-radius: 14rpx;
    background-color: #fff;
    margin: 24rpx 0;
    box-sizing: border-box;
    padding: 0 30rpx;
    display: flex;
    align-items: center;
    .tips-img {
      width: 53rpx;
      height: 48rpx;
    }
    .tips-line {
      width: 4rpx;
      height: 34rpx;
      background-color: #3866ae;
      margin: -1rpx 0 0 24rpx;
    }
    .tips-content {
      font-size: 25rpx;
      color: #333;
      font-weight: 500;
      line-height: 40rpx;
    }
  }
  .index-tabs-wrapper {
    width: 100%;
    background-color: #fff;
    border-radius: 14rpx;
    box-sizing: border-box;
    padding: 22rpx;
    margin-bottom: 24rpx;
    .tab-station-wrap {
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-top: 24rpx;
      &.column {
        flex-direction: column;
      }
    }
  }
  .index-service-wrapper {
    margin-top: 24rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    :deep(.service-item-wrapper) {
      margin-bottom: 20rpx;
      &:nth-child(5) {
        margin-bottom: 0;
      }
      &:nth-child(6) {
        margin-bottom: 0;
      }
    }
  }
  .index-shop-wrapper {
    margin-top: 26rpx;
    display: flex;
    align-items: center;
    // justify-content: space-between;
    .shop-item {
      display: flex;
      flex-direction: column;
      margin-right: 28rpx;
      &:last-child {
        margin-right: 0;
      }
      .img-wrap {
        width: 104rpx;
        height: 104rpx;
        border-radius: 8rpx;
        background-color: #f0f6ff;
        image {
          width: 104rpx;
          height: 104rpx;
          border-radius: 8rpx;
        }
      }
      .item-text {
        width: 100rpx;
        text-align: center;
        margin-top: 12rpx;
        font-size: 24rpx;
      }
    }
  }
  .index-spot-wrapper {
    margin-top: 24rpx;
    .spot-item {
      display: flex;
      align-items: center;
      margin-bottom: 40rpx;
      &:last-child {
        margin-bottom: 0;
      }
      .spot-img-wrap {
        width: 196rpx;
        height: 151rpx;
        background-color: #f6f7fb;
        border-radius: 8rpx;
        image {
          width: 196rpx;
          height: 151rpx;
          border-radius: 8rpx;
        }
      }
      .spot-right-wrap {
        width: 100%;
        flex: 1;
        margin-left: 28rpx;
        .right-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .title {
            font-size: 28rpx;
            color: #333;
            font-weight: 600;
          }
          .price {
            font-size: 21rpx;
            color: #fc9b0d;
          }
        }
        .right-tag-box {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          margin-top: 6rpx;
          .s-tag-green {
            width: 125rpx;
            height: 32rpx;
            background-color: #e2f3e4;
            border-radius: 16rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 21rpx;
            color: #239450;
            margin-right: 16rpx;
            margin-bottom: 10rpx;
          }
        }
        .right-location-box {
          margin-top: 8rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .left {
            display: flex;
            align-items: center;
            .icon-address {
              width: 18rpx;
              height: 22rpx;
            }
            .address-text-wrap {
              font-size: 21rpx;
              color: #c3c3c3;
              margin-left: 8rpx;
              text {
                color: #fc9904;
              }
            }
          }
          .right-go-icon {
            width: 40rpx;
            height: 40rpx;
            image {
              width: 40rpx;
              height: 40rpx;
            }
          }
        }
      }
    }
  }
}
</style>
