<template>
  <view class="page-container">
    <!-- 轮播图区域（全屏顶部延伸） -->
    <view class="banner-wrapper">
      <view class="banner-container">
        <swiper
          class="banner-swiper"
          :style="bannerStyle"
          circular
          :indicator-dots="true"
          :autoplay="true"
          :interval="3000"
          :duration="500"
          indicator-color="rgba(255, 255, 255, 0.5)"
          indicator-active-color="#C6171E"
        >
          <swiper-item v-for="(item,idx) in state.swiperList" :key="idx">
            <image
              class="banner-image"
              :src="item"
              mode="aspectFill"
              @click="handleBannerClick(idx)"
            ></image>
          </swiper-item>
        </swiper>
      </view>
      <!-- 过渡层：跨轮播底部和内容顶部的渐变 -->
      <view class="banner-fade"></view>
    </view>

    <!-- 半透明导航栏（覆盖在轮播图上方） -->
    <view class="custom-navbar" :style="{paddingTop: statusBarHeight + 'px'}">
      <view class="navbar-content">
          <view class="navbar-title">
            <text class="title-text">Yeswash</text>
          </view>
      </view>
    </view>

    <!-- 微信公众号 -->
    <official-account
      @binderror="handleOAerror"
      @bindload="handleOAload"
      class="official-account"
    ></official-account>

    <!-- 公告栏 -->
    <view class="notice-bar" v-if="state.noticeList.length > 0" @click="handleNoticeClick">
      <view class="notice-icon">
        <text class="notice-icon-text">公告</text>
      </view>
      <swiper
        class="notice-swiper"
        vertical
        circular
        :autoplay="state.noticeList.length > 1"
        :interval="3000"
        :duration="600"
        :disable-touch="true"
      >
        <swiper-item v-for="(item, idx) in state.noticeList" :key="idx">
          <text class="notice-text">{{ item.title }}</text>
        </swiper-item>
      </swiper>
      <view class="notice-arrow" v-if="state.noticeList.length > 1">
        <text class="notice-arrow-text">丨</text>
      </view>
    </view>

    <!-- 优化后的菜单区域 -->
    <view class="menu-section">
      <view class="menu-card">
        <!-- <view class="menu-header">
          <view class="menu-title">
            <view class="title-icon"></view>
            <text>快捷服务</text>
          </view>
        </view> -->
        
        <view class="menu-grid">
          <view 
            class="menu-item" 
            v-for="(item,index) in state.menuList" 
            :key="index" 
            @click="handleMenuClick(item)"
          >
            <view class="menu-icon-wrapper">
              <image class="menu-icon" :src="item.icon" mode="aspectFit"></image>
            </view>
            <text class="menu-title-text">{{ item.title }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 站点列表区域 -->
    <view class="station-section" :style="stationSectionStyle">
      <!-- <view class="station-header">
        <view class="station-header-title">
          <view class="header-dot"></view>
          <text>附近站点</text>
        </view>
        <text class="station-header-count" v-if="state.stationList.length">{{ state.stationList.length }}个</text>
      </view> -->

      <scroll-view
        class="station-scroll"
        scroll-y="true"
        :show-scrollbar="true"
      >
        <view class="station-list" v-if="!isLoading">
          <WashStation
            v-for="item in state.stationList"
            :key="item.id"
            :item="item"
          ></WashStation>

          <uv-empty
            v-if="!state.stationList || state.stationList.length === 0"
            mode="list"
            text="附近暂无站点"
            :marginTop="60"
          ></uv-empty>
        </view>

        <view class="loading-wrapper" v-else>
          <uv-loading-icon mode="spinner" size="32" color="#C6171E" text="正在搜索附近站点..." textSize="13"></uv-loading-icon>
        </view>
      </scroll-view>
    </view>

    <!-- 客服按钮 -->
    <custom-service></custom-service>

    <!-- 停车券弹窗 -->
    <uv-popup ref="parking_popup_ref" mode="center" :round="16">
      <view class="parking-popup">
        <view class="popup-title">停车优惠</view>
        <view class="popup-content">
          <text class="popup-desc">长按识别二维码获取停车优惠</text>
          <text class="popup-warning">未满最低消费无法领取停车优惠</text>
          <image
            class="qrcode-image"
            show-menu-by-longpress
            src="/static/parking-qrcode.jpg"
          />
        </view>
      </view>
    </uv-popup>

    <!-- 公告详情弹窗 -->
    <view class="notice-popup-mask" v-if="noticePopupVisible" @click="closeNoticePopup">
      <view class="notice-popup" @click.stop>
        <view class="notice-popup-head">
          <view class="notice-popup-head-icon">
            <text class="head-icon-inner">!</text>
          </view>
          <text class="notice-popup-head-title">公告</text>
          <view class="notice-popup-close" @click="closeNoticePopup">
            <text class="close-icon">✕</text>
          </view>
        </view>
        <scroll-view class="notice-popup-body" scroll-y>
          <view class="notice-card" v-for="(item, idx) in state.noticeList" :key="idx">
            <text class="notice-card-title">{{ item.title }}</text>
            <view class="notice-card-divider"></view>
            <text class="notice-card-content">{{ item.content }}</text>
            <text class="notice-card-time" v-if="item.createTime">发布于 {{ formatDate(item.createTime) }}</text>
          </view>
        </scroll-view>
        <view class="notice-popup-foot">
          <view class="notice-popup-btn" @click="closeNoticePopup">我知道了</view>
        </view>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <tab-bar :index="0"></tab-bar>
  </view>
</template>

<script setup lang="ts">
import {computed, nextTick, reactive, ref} from 'vue'
import {onHide, onLoad, onShow} from "@dcloudio/uni-app";
import TabBar from "@/components/tab-bar/index.vue";
import WashStation from "@/components/station/index.vue"
import {get, post} from "@/utils/https";
import {calcMapDistance} from "@/utils/common"
import {checkLogin, fetchToken, loadUserInfo, tryLogin} from "@/utils/auth";

const parking_popup_ref = ref();
const noticePopupVisible = ref(false);
const isLogin = ref(false)
const isLoading = ref(true)
const statusBarHeight = ref(0)
const bannerHeight = ref(0)

const initState = () => ({
  bannerList: [],
  swiperList: [],
  noticeList: [],
  menuList: [
    {name: "wash", auth: false, title: "洗车", icon: '/static/iconfont/default/fastwash.svg'},
    {name: "charge", auth: true, title: "充值", icon: '/static/iconfont/default/recharge.svg'},
    {name: "coupon", auth: false, title: "消费券", icon: '/static/iconfont/default/coupon.svg'},
    {name: "parking", auth: false, title: "停车券", icon: '/static/iconfont/default/parking.svg'},
  ],
  stationList: [],
  location: {
    latitude: 0,
    longitude: 0,
  },
})

const state = reactive(initState())

// 轮播图高度计算（包含导航栏区域，实现全屏顶部延伸）
const bannerStyle = computed(() => {
  const windowInfo = uni.getWindowInfo();
  const navContentPx = 88 * windowInfo.windowWidth / 750;
  // 轮播图覆盖整个顶部区域：状态栏 + 导航栏内容 + 原图片比例区域
  const height = statusBarHeight.value + navContentPx + windowInfo.windowWidth * 0.35;
  bannerHeight.value = height;
  return {
    height: `${height}px`
  }
})

// 计算站点列表区域的高度
const stationSectionStyle = computed(() => {
  const windowInfo = uni.getWindowInfo();
  // 轮播图总高度（已包含导航栏区域）
  const bannerH = bannerHeight.value || 0;
  // 快捷服务区域预估高度（卡片padding + 标题 + 图标 + 间距，约280rpx转px）
  const menuH = 280 * windowInfo.windowWidth / 750;
  // 底部tabbar高度（约100rpx转px）
  const tabbarH = 100 * windowInfo.windowWidth / 750;
  // 公众号组件预估高度
  const oaH = 40 * windowInfo.windowWidth / 750;
  // 可用高度 = 窗口高度 - 固定区域高度
  const availableHeight = windowInfo.windowHeight - bannerH - menuH - tabbarH - oaH;

  return {
    height: `${availableHeight}px`
  }
})

onLoad((e: any) => {
  // 获取状态栏高度
  const systemInfo = uni.getSystemInfoSync();
  statusBarHeight.value = systemInfo.statusBarHeight || 0;

  let token = fetchToken();
  if (token) {
    getApp<any>().globalData.token = token;
    getApp<any>().globalData.isLogin = true;

    let gd = getApp<any>().globalData;
    if (!gd.user || !gd.user.id) {
      loadUserInfo();
    } else {
      isLogin.value = true;
    }
  } else {
    let manualLogout = getApp<any>().globalData.manualLogout;
    if (!manualLogout) {
      tryLogin().then(token => {
        getApp<any>().globalData.token = token;
        getApp<any>().globalData.isLogin = true;
        isLogin.value = true;
      })
    }
  }

  if (!isLogin.value) {
    addListener();
  }
})

onShow(() => {
  loadInitData()
});

onHide(() => {
  removeListener();
})


const loadInitData = () => {
  let locationData = getApp<any>().globalData.location;
  if (!locationData || !locationData.longitude) {
    loadCurrentLocation();
  } else {
    state.location = locationData;
    loadWashStationList();
  }

  loadBannerList();
  loadNoticeList();
}

const addListener = () => {
  uni.$on('login', function (data) {
    isLogin.value = data.isLogin;
  })

  uni.$on('logout', function (data) {
    isLogin.value = false;
  })
}

const removeListener = () => {
  uni.$off('logout');
  uni.$off('login');
}


const loadBannerList = () => {
  get(`/banner`).then((res: any) => {
    nextTick(() => {
      state.bannerList = res;
      state.swiperList = res.map(k => k.bannerUrl);
    })
  })
}

const loadNoticeList = () => {
  get(`/notice/client/list`).then((res: any) => {
    state.noticeList = res || [];
  }).catch((err: any) => {
    console.error('公告加载失败:', err);
    state.noticeList = [];
  })
}

const formatDate = (datetime: string) => {
  if (!datetime) return '';
  return datetime.split(' ')[0];
}

const handleNoticeClick = () => {
  noticePopupVisible.value = true;
}

const closeNoticePopup = () => {
  noticePopupVisible.value = false;
}

const handleBannerClick = (index: number) => {
  let ele = state.bannerList[index];
  if (ele && ele.linkUrl) {
    uni.navigateTo({url: ele.linkUrl})
  } else {
    uni.showToast({ icon: 'none', title: '暂无更多内容' })
  }
}

const gotoLogin = () => {
  uni.navigateTo({
    url: '/pages-user/login/index'
  })
}

const handleMenuClick = (menu: any) => {
  let {auth,name} = menu;
  if(auth){
    checkLogin().then((res) => {
      handleMenuItemNative(menu)
    }).catch(() => {
      uni.navigateTo({
        url: '/pages-user/login/index'
      })
    })
  }else{
    handleMenuItemNative(menu)
  }
}

const handleMenuItemNative = (menu:any) => {
  if (menu.name === 'wash') {
    uni.navigateTo({
      url: '/pages-wash/scan/index'
    })
  } else if (menu.name === 'charge') {
    uni.navigateTo({
      url: '/pages-user/wallet/recharge'
    })
  } else if (menu.name === 'parking') {
    parking_popup_ref.value?.open('center');
  } else {
    uni.showToast({
      icon: 'none',
      title: '敬请期待',
    })
  }
}

/**
 * 获取当前的地理位置
 */
const loadCurrentLocation = () => {
  uni.authorize({
    scope: 'scope.userLocation',
    success() {
      uni.getLocation({
        type: 'gcj02',
        success: res => {
          let location = {
            latitude: res.latitude,
            longitude: res.longitude
          }
          getApp<any>().globalData.location = location;
          state.location = location
          loadWashStationList();
        }
      });
    },
    fail(e) {
      loadWashStationList();
    }
  })
}

const loadWashStationList = () => {
  isLoading.value = true;
  post(`/wash-station/listStation`, {pageSize: 5}).then((res: any) => {
    let {list, total} = res;
    list.forEach((station: any) => {
      if (station.location) {
        let stationLocation = JSON.parse(station.location);
        station.distance = calcMapDistance(state.location.latitude, state.location.longitude, stationLocation.stationLat, stationLocation.stationLng);
      }
    })
    state.stationList = list;
  }).catch(() => {
    uni.showToast({ icon: 'none', title: '加载失败，下拉重试' })
  }).finally(() => {
    isLoading.value = false;
  })
}

const handleOAerror = () => {
  // 公众号组件加载失败，静默降级
}

const handleOAload = () => {
  // 公众号组件加载完成
}

</script>

<style scoped lang="scss">
page {
  background: $uni-bg-color-page;
}

.page-container {
  min-height: 100vh;
  background: $uni-bg-color-page;
  padding-bottom: 120rpx;
}

// 半透明导航栏（覆盖在轮播图上方）
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: linear-gradient(
    180deg,
    rgba(0, 0, 0, 0.45) 0%,
    rgba(0, 0, 0, 0.12) 70%,
    transparent 100%
  );
  pointer-events: none;

  .navbar-content {
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 32rpx;
    pointer-events: auto;

    .navbar-title {
      display: flex;
      align-items: center;
      gap: 12rpx;

      .title-text {
        color: $uni-text-color-inverse;
        font-size: 36rpx;
        font-weight: $uni-font-weight-semibold;
        letter-spacing: 2rpx;
        text-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.25);
      }
    }
  }
}

// 全屏顶部延伸轮播图区域
.banner-wrapper {
  position: relative;
}

.banner-container {
  position: relative;
  width: 100%;
  overflow: hidden;

  .banner-swiper {
    width: 100%;
  }

  .banner-image {
    width: 100%;
    height: 100%;
    display: block;
  }
}

// 过渡层：向上覆盖轮播底部形成渐变，向下融入页面背景
.banner-fade {
  height: 140rpx;
  margin-top: -100rpx;
  position: relative;
  z-index: 2;
  background: linear-gradient(
    to bottom,
    transparent 0%,
    rgba($uni-bg-color-page, 0.6) 50%,
    $uni-bg-color-page 100%
  );
  pointer-events: none;
}

// 公众号区域
.official-account {
  width: 100%;
  margin: 8rpx 0 16rpx;
}

// 公告栏
.notice-bar {
  display: flex;
  align-items: center;
  margin: 0 24rpx 16rpx;
  padding: 16rpx 20rpx;
  background: #FFF7F0;
  border-radius: 12rpx;
  border: 1rpx solid rgba(198, 23, 30, 0.08);

  .notice-icon {
    flex-shrink: 0;
    margin-right: 16rpx;

    .notice-icon-text {
      display: inline-block;
      background: linear-gradient(135deg, #C6171E, #E84545);
      color: #fff;
      font-size: 20rpx;
      font-weight: 600;
      padding: 4rpx 12rpx;
      border-radius: 6rpx;
      line-height: 1.4;
    }
  }

  .notice-swiper {
    flex: 1;
    height: 40rpx;
    overflow: hidden;
  }

  .notice-text {
    font-size: 26rpx;
    color: #333;
    line-height: 40rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .notice-arrow {
    flex-shrink: 0;
    margin-left: 12rpx;

    .notice-arrow-text {
      font-size: 24rpx;
      color: #ccc;
    }
  }
}

// 优化后的菜单区域
.menu-section {
  padding: 0 24rpx;
  margin-bottom: 28rpx;
}

.menu-card {
  @include card-interactive(24rpx);
  padding: 28rpx 24rpx 24rpx;

  .menu-header {
    margin-bottom: 28rpx;

    .menu-title {
      display: flex;
      align-items: center;
      gap: 12rpx;
      font-size: 30rpx;
      font-weight: $uni-font-weight-semibold;
      color: $uni-text-color-dark;

      .title-icon {
        @include section-dot;
      }
    }
  }

  .menu-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 8rpx;
  }

  .menu-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;
    padding: 16rpx 4rpx;
    border-radius: 16rpx;
    transition: all 0.15s ease;

    &:active {
      transform: scale(0.95);
      background: $uni-bg-color-hover;
    }

    .menu-icon-wrapper {
      width: 80rpx;
      height: 80rpx;
      border-radius: 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.15s ease;
    }

    &:nth-child(1) .menu-icon-wrapper {
      background: linear-gradient(135deg, rgba(198, 23, 30, 0.08), rgba(232, 69, 69, 0.04));
      box-shadow: 0 4rpx 12rpx rgba(198, 23, 30, 0.06);
    }

    &:nth-child(2) .menu-icon-wrapper {
      background: linear-gradient(135deg, rgba(232, 69, 69, 0.08), rgba(255, 152, 0, 0.05));
      box-shadow: 0 4rpx 12rpx rgba(232, 69, 69, 0.06);
    }

    &:nth-child(3) .menu-icon-wrapper {
      background: linear-gradient(135deg, rgba(76, 175, 80, 0.08), rgba(33, 150, 243, 0.05));
      box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.06);
    }

    &:nth-child(4) .menu-icon-wrapper {
      background: linear-gradient(135deg, rgba(33, 150, 243, 0.08), rgba(198, 23, 30, 0.04));
      box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.06);
    }

    &:active .menu-icon-wrapper {
      transform: scale(0.9);
    }

    .menu-icon {
      width: 48rpx;
      height: 48rpx;
    }

    .menu-title-text {
      font-size: 26rpx;
      color: $uni-text-color-secondary;
      font-weight: $uni-font-weight-medium;
      transition: color 0.2s ease;
    }

    &:active .menu-title-text {
      color: $uni-color-primary;
    }
  }
}

// 站点列表区域
.station-section {
  padding: 0 20rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.station-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  padding: 0 4rpx;

  .station-header-title {
    display: flex;
    align-items: center;
    gap: 12rpx;
    font-size: 30rpx;
    font-weight: $uni-font-weight-semibold;
    color: $uni-text-color-dark;
  }

  .header-dot {
    @include section-dot;
  }

  .station-header-count {
    font-size: 26rpx;
    color: $uni-text-color-hint;
  }
}

.station-scroll {
  width: 100%;
  height: 100%;
}

.station-list {
  display: flex;
  flex-direction: column;
  padding-bottom: 20rpx;
}

.loading-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
}

// 停车券弹窗
.parking-popup {
  width: 600rpx;
  background: $uni-bg-color-card;
  border-radius: 24rpx;
  overflow: hidden;

  .popup-title {
    background: linear-gradient(
      135deg,
      $uni-color-primary 0%,
      $uni-color-primary-light 100%
    );
    color: $uni-text-color-inverse;
    font-size: 32rpx;
    font-weight: $uni-font-weight-semibold;
    text-align: center;
    padding: 32rpx;
  }

  .popup-content {
    padding: 40rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 32rpx;

    .popup-desc {
      font-size: 28rpx;
      color: $uni-text-color-secondary;
      text-align: center;
      line-height: 1.6;
    }

    .popup-warning {
      font-size: 28rpx;
      color: #e53e3e;
      text-align: center;
      font-weight: 700;
    }

    .qrcode-image {
      width: 480rpx;
      height: 480rpx;
      border-radius: 16rpx;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
    }
  }
}

// 公告详情弹窗
.notice-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.45);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.notice-popup {
  width: 660rpx;
  max-height: 78vh;
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.12);
}

.notice-popup-head {
  display: flex;
  align-items: center;
  padding: 36rpx 32rpx 28rpx;
  flex-shrink: 0;
}

.notice-popup-head-icon {
  width: 44rpx;
  height: 44rpx;
  border-radius: 12rpx;
  background: linear-gradient(135deg, #C6171E, #E84545);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;

  .head-icon-inner {
    color: #fff;
    font-size: 28rpx;
    font-weight: 800;
    font-style: italic;
  }
}

.notice-popup-head-title {
  font-size: 34rpx;
  font-weight: 700;
  color: #1a1a1a;
  flex: 1;
}

.notice-popup-close {
  width: 52rpx;
  height: 52rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f2f2f2;

  .close-icon {
    font-size: 28rpx;
    color: #999;
    font-weight: 500;
  }
}

.notice-popup-body {
  flex: 1;
  overflow-y: auto;
  padding: 0 32rpx;
}

.notice-card {
  padding: 32rpx 32rpx 28rpx;
  margin-bottom: 20rpx;
  border-radius: 16rpx;
  background: #fff;
  border: 1rpx solid #eee;
  border-left: 6rpx solid #C6171E;
}

.notice-card-title {
  font-size: 30rpx;
  font-weight: 700;
  color: #1a1a1a;
  line-height: 1.5;
  display: block;
  padding-right: 8rpx;
}

.notice-card-divider {
  width: 48rpx;
  height: 4rpx;
  background: #C6171E;
  border-radius: 2rpx;
  margin: 18rpx 0;
  opacity: 0.45;
}

.notice-card-content {
  font-size: 27rpx;
  color: #666;
  line-height: 1.9;
  display: block;
  letter-spacing: 0.5rpx;
  padding-right: 8rpx;
}

.notice-card-time {
  display: block;
  margin-top: 20rpx;
  font-size: 22rpx;
  color: #bbb;
  letter-spacing: 0.3rpx;
  padding-right: 8rpx;
}

.notice-popup-foot {
  padding: 24rpx 32rpx 36rpx;
  flex-shrink: 0;
}

.notice-popup-btn {
  width: 100%;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #C6171E, #E84545);
  border-radius: 44rpx;
  color: #fff;
  font-size: 30rpx;
  font-weight: 600;
  letter-spacing: 2rpx;

  &:active {
    opacity: 0.85;
    transform: scale(0.98);
  }
}
</style>
