<template>
  <div class="sidebar-logo-container" :class="{ 'collapse': collapse }">
    <div class="box_weather">
      <el-image style="height: 45px;" :src="getImageUrl(imgUrl)" fit="cover">
        <template #error>
          <div class="image-slot">
            <svg-icon icon-class="failure" className="failure_icon" color="rgb(248, 152.1, 152.1)" />
          </div>
        </template>
      </el-image>
      <div class="weather_title">
        <span>{{ weathers || '未知' }} {{ temperatures || '未知' }}℃</span>
        <span>{{ currentTime }} {{ hourMinuteSecond }}</span>
      </div>
    </div>
    <router-link key="expand" class="sidebar-logo-link" to="/">
      <div class="sidebar-logo">
        <div class="sidebar-title">{{ title }}</div>
        <div class="sidebar-title1"></div>
        <div class="sidebar-title2"></div>
      </div>
    </router-link>
    <div class="avatar-container">
      <Dropdown :name="name" :options="['退出登录']" @changeData="logout"></Dropdown>
      <div class="shiny-button" @click="expandFold">
        {{ appStore.expandFoldType ?'收起':'展开'}}
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import Dropdown from '@/components/Dropdown'
import { ElMessageBox } from 'element-plus'
import useSettingsStore from '@/store/modules/settings'
import variables from '@/assets/styles/variables.module.scss'
import useUserStore from '@/store/modules/user'
import useAppStore from '@/store/modules/app'
import { weatherList } from "./mockData";
defineProps({
  collapse: {
    type: Boolean,
    required: true
  }
})
const imgUrl = ref('')
const weathers = ref('')
const temperatures = ref('')
const userStore = useUserStore()
const appStore = useAppStore()
const name = userStore.name
const title = import.meta.env.VITE_APP_TITLE;
const settingsStore = useSettingsStore();
const sideTheme = computed(() => settingsStore.sideTheme);
const getImageUrl = (name) => {
  return new URL(`${name}`, import.meta.url).href
}
const timer = ref(null)
const hourMinuteSecond = ref('')
const currentTime = ref('')
timer.value = setInterval(() => {
  hourMinuteSecond.value = formatTime(new Date(), 'hh:mm:ss')
  currentTime.value = formatTime(new Date(), 'yyyy-MM-dd')
}, 1000);
function formatTime(str, format) {
  let time = new Date(str)
  let formatTime = {
    'y+': '0' + time.getFullYear(),
    'M+': '0' + (time.getMonth() + 1),
    'd+': '0' + time.getDate(),
    'h+': '0' + time.getHours(),
    'm+': '0' + time.getMinutes(),
    's+': '0' + time.getSeconds()
  }
  let result = format || 'yyyy-MM-dd hh:mm:ss'
  for (let i in formatTime) {
    let regexp = new RegExp('(' + i + ')', 'g')
    let replaceInfoObj = regexp.exec(result)
    if (replaceInfoObj) {
      let replaceInfoArr = Array.from(replaceInfoObj)
      result = result.replace(
        regexp,
        formatTime[i].substring(formatTime[i].length - replaceInfoArr[0].length),
        formatTime[i].length
      )
    }
  }
  return result
}
// 获取Logo背景色
const getLogoBackground = computed(() => {
  if (settingsStore.isDark) {
    return 'var(--sidebar-bg)';
  }
  return sideTheme.value === 'theme-dark' ? variables.menuBg : variables.menuLightBg;
});

// 获取Logo文字颜色
const getLogoTextColor = computed(() => {
  if (settingsStore.isDark) {
    return 'var(--sidebar-text)';
  }
  return sideTheme.value === 'theme-dark' ? '#fff' : variables.menuLightText;
});

function logout() {
  ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logOut().then(() => {
      location.href = '/index';
    })
  }).catch(() => { });
}
async function getIPCity() {
  try {
    // 使用高德API的IP定位服务获取IP省市信息
    const ipResponse = await axios.get(
      'https://restapi.amap.com/v3/ip?key=6bd1c2303f2ca454975738f8911a27ce'
    );
    if (ipResponse.data && ipResponse.data.rectangle) {
      const parts = ipResponse.data.rectangle.split(";");
      getAddressByLatLng(parts);//回调下方的函数
    }
  } catch (error) {
    console.error('IP定位失败', error);
  }
}

const getAddressByLatLng = async (ip) => {
  try {
    // 使用高德API的地理编码服务将经纬度转换成地址
    const lat = ip;
    const lng = ip;
    const latlng = `${lat},${lng}`;//将经度纬度拼接起来传给api地址
    const geoResponse = await axios.get(
      `https://restapi.amap.com/v3/geocode/regeo?key=6bd1c2303f2ca454975738f8911a27ce&location=${latlng}`
    );
    getWeather(geoResponse.data.regeocode.addressComponent)
  } catch (error) {
    console.error('地理编码失败', error);
  }
}
const getWeather = async (params) => {
  let city = params.adcode
  let apiKey = '6bd1c2303f2ca454975738f8911a27ce'
  try {
    const response = await axios.get(
      `https://restapi.amap.com/v3/weather/weatherInfo?city=${city}&key=${apiKey}`
    );
    if (response.status == 200) {
      let weatherArr = response.data.lives[0]
      weathers.value = weatherArr.weather
      temperatures.value = weatherArr.temperature
      weatherList.forEach(el => {
        if (el.name === weatherArr.weather) {
          imgUrl.value = el.url
        }
      });
    }
  } catch (error) {
    console.error('请求失败:', error);
  }
}
// 展开收起
const expandFold = () =>{
  let foldType = true
  if(appStore.expandFoldType){
    foldType = false
  }else{
    foldType = true
  }
  appStore.getExpandFold(foldType);
}
onMounted(() => {
  getIPCity()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.module.scss';

.failure_icon {
  width: 30px;
  height: 30px;
}

.sidebarLogoFade-enter-active {
  transition: opacity 1.5s;
}

.sidebarLogoFade-enter,
.sidebarLogoFade-leave-to {
  opacity: 0;
}

.sidebar-logo-container {
  width: 100%;
  text-align: center;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;


  & .sidebar-logo-link {
    position: absolute;
    height: 100%;
    left: calc(50% - 280px);
    width: 560px;


    & .sidebar-logo {
      display: inline-block;
      position: relative;
    }

    & .sidebar-title {
      letter-spacing: 5px;
      font-family: fangsong;
      font-style: italic;
      z-index: 3;
      color: v-bind(getLogoTextColor);
      font-weight: 600;
      font-size: 22px;
      padding: 10px 70px;
      background-image: linear-gradient(to right, #1da1d3 0%, #003aa5 20%, #003aa5 80%, #1da1d3 100%, );
      clip-path: polygon(0 0, 50px 100%, calc(100% - 50px) 100%, 100% 0);
      box-shadow: inset 0px -3px 30px #62d4ff;
      border-bottom: 1px solid #73caff;
    }

    & .sidebar-title1 {
      z-index: -1;
      position: absolute;
      top: 0;
      bottom: 10px;
      left: -30px;
      right: -30px;
      background: radial-gradient(circle, #0067ff, #002d5b);
      clip-path: polygon(0 0, 60px 100%, calc(100% - 60px) 100%, 100% 0);
      box-shadow: inset 0px -3px 30px rgb(0 186 255);
    }

    & .sidebar-title2 {
      z-index: -2;
      position: absolute;
      top: 0;
      bottom: 15px;
      left: -65px;
      right: -65px;
      background: radial-gradient(circle, rgb(203 203 203 / 76%), #0e4dae);
      clip-path: polygon(0 0, 70px 100%, calc(100% - 70px) 100%, 100% 0);
      box-shadow: inset 0px -3px 30px rgb(208 242 255);
    }
  }
}

.box_weather {
  display: flex;
  align-items: center;
  color: #fff;
  margin-left: 20px;
  font-size: 18px;
}

.weather_title {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  align-items: flex-start;

  span {
    margin: 2px 0px;
    font-size: 14px;
  }
}

.image-slot {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}

.avatar-container {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.shiny-button {
  user-select: none;
  margin-left: 20px;
  width: fit-content;
  position: relative;
  padding: 2px 20px;
  color: rgb(207, 248, 255);
  border: 3px solid transparent;
  border-radius: 60px;
  background-color: rgb(6, 69, 73);
  background-image: linear-gradient(to bottom right, rgb(10, 107, 115), rgb(2, 10, 14)), linear-gradient(125deg, rgba(255, 255, 255, 0) 45%, rgba(255, 255, 255, 0.6) 50%, rgba(255, 255, 255, 0) 53%);
  background-origin: border-box;
  background-clip: padding-box, border-box;
  background-size: 100%, 200%;
  background-position: 0px, -150px;
  animation: 4s border-glint linear backwards infinite;
  animation-delay: 1s;
  transition: box-shadow 0.25s, text-shaddw 0.25s;
  overflow: hidden;
}

.shiny-button:hover {
  cursor: pointer;
  background-image: linear-gradient(-60deg, rgb(40, 105, 160) 0%, rgb(186, 211, 229) 100%), linear-gradient(125deg, rgba(255, 255, 255, 0) 45%, rgba(255, 255, 255, 0.6) 50%, rgba(255, 255, 255, 0) 53%);
  color: rgb(250, 250, 255);
  box-shadow: rgba(0, 0, 0, 0.7) 5px 5px 5px;
  text-shadow: 0px 0px 3px rgba(255, 255, 255, 0.7);
  transition: box-shadow 0.25s, text-shaddw 0.25s;
}

.shiny-button::after {
  content: ' ';
  position: absolute;
  top: -50%;
  left: -120%;
  width: 200%;
  height: 200%;
  background-image: linear-gradient(125deg, rgba(255, 255, 255, 0) 30%, rgba(255, 255, 255, 0.4) 50%, rgba(255, 255, 255, 0) 52%);
  animation: 5s glint linear backwards infinite;
  animation-delay: -3s;
}

@keyframes glint {
  0% {
    left: -120%;
  }
  8% {
    left: 50%;
  }
  100% {
    left: 50%;
  }
}

@keyframes border-glint {
  0% {
    background-position: 0px, -250px;
  }
  25% {
    background-position: 0px, -200px;
  }
  75% {
    background-position: 0px, 50px;
  }
  100% {
    background-position: 0px, 50px;
  }
}
</style>