<template>
  <div>
    <el-button @click="locate">定位</el-button>
    <span>{{ address || '未定位' }}</span>
    <div v-for="(store, index) in storeList" :key="index" class="store-container">
      <div>
       <p>店名: {{ store.branchName }}</p>
        <p>地址: {{ store.branchAddress }}</p>
        <p>电话: {{ store.branchPhone }}</p>
      </div>
      <div>
        <el-button @click="showConfirm(store)">选择</el-button>
        <el-button @click="navigateToMap(store)">导航</el-button>
      </div>
    </div>
    <el-dialog
      title="确认选择"
      v-model="confirmVisible"
      width="30%"
    >
      <template #content>
       <p>确认选择 {{ selectedStore?.branchName }} 吗？</p>
      </template>
      <template #footer>
        <el-button @click="confirmVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelection">选择</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup lang="ts">
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ref, onMounted } from 'vue'
// 模拟门店列表
interface Branch {
  branchId: number
  branchName: string
  branchAddress: string
  branchPhone: string
  latitude: number
  longitude: number
}
const storeList = ref<Branch[]>([]);
const currentLat = ref<number | null>(null)
const currentLng = ref<number | null>(null)

onMounted(() => {
  // 获取分店列表
  axios.get('/api/user/branch/list')//ok
    .then(res => {
      storeList.value = res.data;
    })
    .catch(err => {
      console.error('获取分店列表失败:', err);
    });
  // 恢复地址
  const savedAddress = localStorage.getItem('currentAddress');
  if (savedAddress) {
    address.value = savedAddress;
  }
  // 恢复选择的门店
  const savedStore = localStorage.getItem('selectedStore');
  if (savedStore) {
    selectedStore.value = JSON.parse(savedStore);
  }
  // 可选：恢复经纬度
  const savedLng = localStorage.getItem('currentLng');
  const savedLat = localStorage.getItem('currentLat');
  if (savedLng && savedLat) {
    currentLng.value = parseFloat(savedLng);
    currentLat.value = parseFloat(savedLat);
  }
});

const address = ref('');
// 调用后端接口获取地址
const getAddressFromCoordinate = (longitude: number, latitude: number): void => {
  axios.get('/api/user/map/convert', {//ok
    params: {
      longitude,
      latitude
    }
  })
  .then(response => {
    address.value = response.data;
    console.log('地址转换成功:', address.value);
    // 本地保存定位地址
    localStorage.setItem('currentAddress', address.value);
    localStorage.setItem('currentLng', longitude.toString());
    localStorage.setItem('currentLat', latitude.toString());
  })
  .catch(error => {
    console.error('地址转换失败:', error);
    address.value = '获取地址失败';
  });
};

// 在定位成功后调用地址转换
const locate = () => {
  navigator.geolocation.getCurrentPosition((position) => {
    const { latitude, longitude } = position.coords;

    currentLat.value = latitude;
    currentLng.value = longitude;

    getAddressFromCoordinate(longitude, latitude);
  }, (error) => {
    console.error('定位失败:', error);
    address.value = '定位失败，无法获取地址';
  },
  {
      enableHighAccuracy: true, // 启用高精度定位
      timeout: 10000,           // 可选：10秒超时限制
      maximumAge: 0             // 不使用缓存位置
    }
  );
};

// 控制确认弹窗的显示与隐藏
const confirmVisible = ref(false);
// 当前选中的门店
const selectedStore = ref<Branch | null>(null);
// 显示确认弹窗
const showConfirm = (store: Branch) => {
  selectedStore.value = store;
  confirmVisible.value = true;
};

const router = useRouter();
// 确认选择门店
const confirmSelection = () => {
  if (selectedStore.value) {
    console.log('已选择门店:', selectedStore.value.branchName);

    //保存到 localStorage
    localStorage.setItem('selectedStoreName', selectedStore.value.branchName);
    localStorage.setItem('selectedStoreId', selectedStore.value.branchId.toString());

    confirmVisible.value = false;

    // 跳转页面
   router.push({ name: 'UserHome', query: { storeName: selectedStore.value.branchName } }).then(() => {
  location.reload();
  });
  }
};

// 跳转到高德地图导航
const navigateToMap = (store: Branch) => {
if (currentLat.value !== null && currentLng.value !== null) {
    const fromName = '我的位置';
    const toName = store.branchAddress;

    const url = `https://uri.amap.com/navigation?from=${currentLng.value},${currentLat.value},${encodeURIComponent(fromName)}&to=${store.longitude},${store.latitude},${encodeURIComponent(toName)}&mode=car&src=mypage&coordinate=gaode`;

  window.open(url, '_blank');
  } else {
    alert('请先点击“定位”按钮获取当前位置');
  }
}

</script>

<style scoped>
.store-container {
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
}
.el-button {
  font-size: 18px !important;
  background-color: #fccc0a !important;
  border-color: #fccc0a !important;
  color: #000 !important;
}
.store-container {
  background-color: #fff8e1; /* 淡黄色底色 */
  padding: 10px; /* 建议加点内边距更好看 */
  border-radius: 4px; /* 可选圆角 */
  margin-bottom: 10px; /* 之间留点空间 */
}

</style>