<template>
  <uv-navbar placeholder leftIcon="" title="iWash洗车"
             bg-color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"
             :border="false"></uv-navbar>
  <view class="content" :style="containerStyle">
    <!--    <image class="logo" src="/static/logo.png"/>
        <view class="text-area">
          <text class="title">{{ title }}</text>
        </view>-->
    <view style="width: 100%;" class="swiper-content">
      <uv-swiper
          class="swiper-item-1"
          style="width: 100%"
          :list="state.swiperList"
          @click="handleBannerClick"
          previousMargin="30"
          nextMargin="30"
          circular
          :autoplay="true"
          radius="5"
          bgColor="#ffffff">
      </uv-swiper>
    </view>
    <!--
        <view class="w100">
          <uv-notice-bar mode="closable" speed="50" url="/pages/coupon/index" :text="state.notice"></uv-notice-bar>
        </view>
    -->

    <view class="w100 gap"></view>


    <view class="menu-content w100">
      <uv-grid :border="false" :col="4">
        <uv-grid-item v-for="(item,index) in state.menuList" :key="index" @click="handleMenuClick(item)">
          <uv-icon :customStyle="{paddingTop:20+'rpx'}" :name="item.name" :size="22"></uv-icon>
          <text class="grid-text">{{ item.title }}</text>
        </uv-grid-item>
      </uv-grid>
    </view>

    <view class="w100 gap"></view>

    <!--    站点清单  start-->
    <view class="w100 content_station">
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
      <WashStation v-for="item in state.stationList" :key="item.id" :item="item"></WashStation>
    </view>
    <!--    站点清单  end-->

    <!--    <cover-view class="login_bar">
          <login-bar class="w100 text-center"></login-bar>
        </cover-view>-->
    <!--    <cover-view class="login_bar" v-show="!isLogin">-->
    <login-bar class="w100 text-center"></login-bar>
    <!--    </cover-view>-->
    <tab-bar :index="0"></tab-bar>
  </view>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue'
import {onHide, onShow, onLoad} from "@dcloudio/uni-app";
import TabBar from "@/components/tab-bar/index.vue";
import LoginBar from "@/components/login-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 title = ref('Hello')
const isLogin = ref(false)

const containerStyle = ref();
const change = () => {
  console.log("change")
}

const initState = () => ({
  bannerList: [],
  swiperList: [
    'https://cdn.uviewui.com/uview/swiper/swiper3.png',
    'https://cdn.uviewui.com/uview/swiper/swiper2.png',
    'https://cdn.uviewui.com/uview/swiper/swiper1.png'
  ],
  menuList: [
    {name: "photo", title: "洗车"},
    {name: "lock", title: "充值"},
    {name: "star", title: "卡券"},
    {name: "red-packet", title: "停车"},
  ],
  qrcodeOption: {
    style: 'round',
    size: 230,
    // 指定二维码前景，一般可在中间放logo
    foregroundImageSrc: 'https://www.uvui.cn/common/logo.png'
  },
  customStyle: {
    'margin-top': '40rpx',
    height: '80rpx',
    width: '80%',
    borderRadius: '40rpx',//圆角
  },
  notice: '中秋佳节，全场8折，快来洗车吧！',
  stationList: [],
  location: {
    latitude: 0,
    longitude: 0,
  }
})

const state = reactive(initState())

onLoad((e: any) => {
  const bound = uni.getMenuButtonBoundingClientRect();
  containerStyle.value = {
    top: `${bound.bottom + 10}px`,
  };
  /*  if (query) {
      uni.showToast({
        title: query,
        duration: 5000
      })
    }*/

})

onShow(() => {
  let token = fetchToken();
  if(token){
    getApp<any>().globalData.token = token;
    getApp<any>().globalData.isLogin = true;
    isLogin.value = true;
    loadUserInfo();
  }else{
    tryLogin().then(token=>{
      getApp<any>().globalData.token = token;
      getApp<any>().globalData.isLogin = true;
      isLogin.value = true;
    }).catch(e=>{
      console.error(e)
    })
  }
 /* const userData = getApp<any>().globalData.user;
  if (userData && userData.id) {
    isLogin.value = true;
  }*/

  console.log("show index>>>>", isLogin.value, state.stationList, state.location)
  let locationData = getApp<any>().globalData.location;
  if (!locationData || !locationData.longitude) {
    loadCurrentLocation();
  } else {
    state.location = locationData;
    loadWashStationList();
  }
  loadBannerList();
  uni.$on('loginEvent', function (data) {
    isLogin.value = data.isLogin;
  })

});

onHide(() => {
  Object.assign(state, initState());
})

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

const handleBannerClick = (index: number) => {
  let ele = state.bannerList[index];
  if (ele && ele.linkUrl) {
    uni.navigateTo({url: ele.linkUrl})
  }
}

const handleMenuClick = (menu: any) => {
  checkLogin().then((res) => {
    if (menu.title === '洗车') {
      uni.navigateTo({
        url: '/pages-wash/scan/index'
      })
    } else if (menu.title === '充值') {
      uni.navigateTo({
        url: '/pages-user/wallet/recharge'
      })
    }
  })
}

/**
 * 获取当前的地理位置
 */
const loadCurrentLocation = () => {
  uni.authorize({
    scope: 'scope.userLocation',
    success() {
      uni.getLocation({
        type: 'gcj02', //返回可以用于uni.openLocation的经纬度
        success: res => {
          let location = {
            latitude: res.latitude,
            longitude: res.longitude
          }
          getApp<any>().globalData.location = location;
          state.location = location
          loadWashStationList();
          console.log("loadCurrentLocation location", res)
        }
      });
    },
    fail(e) {
      loadWashStationList();
      console.log("authorize location fail", e)
    }
  })

}

const loadWashStationList = () => {
  post(`/wash-station/listStation`, {pageSize: 5}).then((res: any) => {
    console.log(res)
    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;
  })
}

const handleNavMap = (station: any) => {
  let location = JSON.parse(station.location)
  uni.openLocation({
    latitude: location.stationLat,
    longitude: location.stationLng,
    scale: 18,
    name: station.stationName,
    address: station.address,
  });
}

const handleNavStation = (station: any) => {
  getApp<any>().globalData.pageData = {station}
  uni.navigateTo({
    url: '/pages-wash/station/index?id=' + station.id
  })
  console.log(station)
}

</script>

<style scoped lang="scss">
.content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;

}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin: 200rpx auto 50rpx;
}

.menu-content {
  width: 100%;
  padding: 0 20rpx;
  border-radius: 8rpx;
}

.qrcode-content {
  margin-top: 40rpx;
  padding: 0 20rpx;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  align-content: center;
  justify-content: center;
}

.gap {
  width: 100%;
  height: 36rpx;
  background-color: #f5f3f3;
  margin-top: 10rpx;
  margin-bottom: 10rpx;
}

.swiper-content {
  height: 200rpx;
}

.guide-content {
  text-align: center;
}

.loginbar {
  position: fixed;
  bottom: 20rpx;
}

.content_station {
  height: calc(100vh - 700rpx);
  overflow: scroll;
}
</style>
