<template>
  <view class="container">
    <view class="selectSite card" @click="openCityPicker">
      <view class="left">
        <image src="/static/home/address.svg" mode="widthFix" class="icon"></image>
        <text class="address fontb">{{state.city}}{{state.district?'·'+state.district:''}}</text>
      </view>
      <view class="right">
        <text class="more fontb">更多分店</text>
        <image src="/static/home/jiantou.svg" style="width: 44rpx;height: 24rpx;" class="icon"></image>
      </view>
    </view>
    <view class="content">
      <view class="siteList card" v-for="(item,index) in siteData.list" :key="item.id" @click="toHome(item)">
         <view class="box">
          <view class="left">
            <view class="name font36 fontb">
             <view class="tuijian">推荐</view> <text>{{ item.name }}</text> <view v-if="item.distance&& index === 0" class="zuijin">距离最近</view>
            </view>
            <view class="tagsList">
               <view class="tag">随存随取</view>
                <!-- <view class="tag">随存随取</view> -->
            </view>
          </view>
          <view class="distance" v-if="item.distance" @click.stop="handleNavigate(item)">
            <view class="icon">
               <image src="/static/site/map.svg"></image>
            </view>
            <view class="m" v-if="item.distance">
                {{ item.distance }} KM
            </view>
          </view>
         </view>
         <view class="box2">
           <view class="address fontb font28 textGary">{{ item.city }}{{ item.district }}{{ item.address }}</view>
           <view class="time adress fontb font28 textGary">
            营业: 00:00-24:00
           </view>
           <view class="phone adress fontb font28 textGary">
             <text @click.stop="makePhoneCall">电话: 400-818-1813</text>
           </view>
         </view>
      </view>
    </view>
    <uvPickerSlef ref="cityPicker" confirmColor="#FB322E" round="24px" title="选择城市" :columns="[state.cityData]" @confirm="cityConfirm"></uvPickerSlef>
    <view class="footer">
      <view @click="toHome">
        返回主页
      </view>
      <view @click="openCityPicker">
        选择城市
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref,reactive } from "vue";
import { onLoad, onShow, onShareAppMessage } from "@dcloudio/uni-app";
import { getDistance,mergeFiveGoatStores,makePhoneCall} from "@/utils/common.js";
import { useSiteApi } from "@/Apis/site.js";
import { useLoginApi } from "@/Apis/login.js";
import { ClientSite } from "@/Apis/book.js";
import uvPickerSlef from "@/components/uv-pickerself/components/uv-picker/uv-picker.vue";
// 主题色配置
import { useMainStore } from "@/store/index.js";
// 国际化配置
import { useI18n } from "vue-i18n";
import { useLocation } from "@/hooks/useLocation";
const { t } = useI18n();
// const getLockApi = useLockApi();
const { locationState, getLocation } = useLocation();
const { themeInfo, getUserInfo, storeState } = useMainStore();
const getApi = ClientSite();
const getLoginApi = useLoginApi();
const cityPicker = ref(null);
const state = ref({
  city: "全部",
  district: "",
  cityData: [],
  areaData: [],
  firstLoad: false,
});
let siteData = reactive({
		list: [],
		isLoading: false,
	});

// 点击路线跳转
const handleNavigate = (item) => {
    SFUIP.openLocation({
        latitude: Number(item.latitude),
        longitude: Number(item.longitude),
        name: item.name,
        address: item.address,
    });
};

const toHome = (item) => {
  uni.$emit('homeSiteId', { id: item.id }); // 触发事件
  uni.switchTab({
    url: `/pages/index/index`,
  });
}
const cityConfirm = (e) => {
  console.log(e, "confirm");
  state.value.city = e.value[0];
  getSiteDetail();

}
const openCityPicker = () => {
  cityPicker.value.open();
}
const closeCityPicker = () => {
  cityPicker.value.close();
}

onLoad((params) => {
  state.firstLoad = true;
  getCityData();
});
const getCityData = () => {
		getApi.GetCityAll().then(res => {
			if(res.code === 200) {
				state.value.cityData = res.data.filter(item=>item.indexOf("广州") !== -1);
				state.value.cityData.unshift("全部");
				// 首次直接选择全部
				state.value.city = state.value.cityData[0];
			}
		})
	}

  // 首次只显示距离最近的城市  noLocation 沒有定位的情况下顯示深圳
	const filterSiteData = (noLocation) => {
		state.firstLoad = false;
		if (!siteData.list.length) return;
		let city = siteData.list[0]['city'];
		// 如果是金刚的appid，默认显示深圳的门店
		if(noLocation){
			city = siteData.list.find(item => item.city.indexOf("广州") !== -1)?.city;
		}
		siteData.list = siteData.list.filter((item) => item.city.indexOf(city) !== -1);
		state.value.city = city;
		getApi.GetDistrictByCity(city).then(res => {
			if (res.code === 200) {
				state.value.areaData = res.data;
				state.value.areaData.unshift("全部");
				// state.value.district = state.value.areaData[0];
			}
		});
	}

  // 获取门店信息
	const getSiteDetail = () => {
		uni.showLoading();
    let city = state.value.city === "全部" ? "" : state.value.city;
    let district = state.value.district  === "全部" ? "" : state.value.district;
		siteData.list = []
		getApi.getSiteDetailsAll({
			city,
			district,
		}).then(res => {
			if (res.code === 200) {
				siteData.list = mergeFiveGoatStores(res.data.filter(item => !item.isSoldOut && item.city.indexOf("广州") !== -1));
				if (locationState?.latitude && locationState?.longitude) {
					const { latitude, longitude } = locationState;
					siteData.list.forEach(item => {
						const { distance, number } = getDistance(latitude, longitude, item.latitude, item.longitude);
						item.distance = distance;
						item.distanceNumber = number;
					});
					siteData.list.sort((a, b) => a.distanceNumber - b.distanceNumber);
					if (state.firstLoad) filterSiteData();
				}else {
					// 如果是金刚就不是显示全部
					if(AppId === 'wxb20921dfdd0b94f4' || AppId === 'wx3c4ab696101d77d1') {
				    if (state.firstLoad) filterSiteData(true);
				}
				}
			}
			siteData.isLoading = false;
		}).catch(err => {
			
			siteData.isLoading = false;
		}).finally(() => {
		  uni.hideLoading();
		})
		;
	}

onShow(() => {
   uni.showLoading({
        mask: true,
      })
   getLocation().finally(() => {
    uni.hideLoading();
			getSiteDetail();
		});
});
</script>

<style scoped lang="scss">
@import "@/static/style/theme.scss";
.container {
 height: 100vh;
 padding-bottom: 100rpx;
 position: relative;
 .content{
  padding-bottom: 200rpx;
 }

}
.selectSite {
  height: 75rpx; // 整体高度
  display: flex;
  justify-content: space-between; // 左右分布
  align-items: center; // 垂直居中
  background: linear-gradient(90deg, #FFE8C4 0%, #FFFFFF 100%);
  width: 100%;
  font-size: 30rpx;
}

.selectSite .left {
  display: flex;
}

.selectSite .left .icon {
  width: 30rpx; // 图片大小，可根据实际调整
  height: 30rpx;
  margin-right: 20rpx; // 图片和文字间距
}

.selectSite .left .address {
  font-size: 28rpx;
  word-wrap: break-word;
  word-break: break-all;
  flex: 1;
}

.selectSite .right {
  display: flex;
  align-items: center; // 右侧垂直居中
}

.selectSite .right .more {
  font-size: 28rpx;
  color: #000;
  margin-right: 8rpx; // text 和 icon 间距
}


.siteList{
  display: flex;
  flex-direction: column;
.box2{
  display: flex;
  flex-direction: column;
  .address{
    margin-bottom: 10rpx;
    word-wrap: break-word;
    word-break: break-all;
  }
  .time{
    margin-bottom: 10rpx;
  }
}
.box{
  display: flex;
  width: 100%;
  margin-bottom: 20rpx;
  
    .left{
    flex: 1;
    align-items: center;
    .name{
      display: flex;
      align-items: center;
      line-height: 1;
      :deep(span){
      }
      .tuijian{
        color: #FFFFFF;
        padding: 8rpx 20rpx;
        border-radius: 8rpx;
        background-color:#334E80;
        font-size: 24rpx;
        margin-right: 20rpx;
      }
      .zuijin{
        color: #000000;
        padding: 10rpx;
        border-radius: 8rpx;
        margin-left: 10rpx;
        font-size: 16rpx;
        background-color: #F2F3F8;
      }
    }
    .tagsList{
      display: flex;
      flex-wrap: wrap;
      margin-top: 10rpx;
      .tag{
        color: #D2021B;
        background-color: #FBE8EB;
        padding: 0rpx 12rpx;
        height: 32rpx;
        min-width: 94rpx;
        line-height: 32rpx;
        border-radius: 8rpx;
        font-size: 18rpx;
        margin-right: 10rpx;
        margin-top: 10rpx;
      }
    }
    }
    .distance{
      display: flex;
      flex-direction: column;
      font-size: 20rpx;
      .icon{
        text-align: center;
      }
      image{
        width: 40rpx;
        height: 40rpx;
        padding: 6px;
        border-radius: 999rpx;
        background-color: #F2F3F8;
      }

    }
 }
}

.footer{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: #fff;
  view{
    width: 50%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    color: #000;
    font-size: 30rpx;
    font-weight: bold;
  }
}
</style>
