<template>
  <div class="logo">
    <!--    <img src="~@/assets/images/logo.png" alt="" :class="{ 'mr-2': !collapsed }" />-->
    <!--    <h2 v-show="!collapsed" :style="logoCSS"> {{ title }} </h2>-->

    <n-popselect :options="servers" size="large" scrollable @update:value="handleUpdateValue">
      <n-button :style="logoCSS" :bordered="false"
        >{{ selectedServer }}
        <n-icon :component="SafetyCertificateOutlined" style="margin-left: 8px" />
      </n-button>
    </n-popselect>
  </div>
</template>

<script lang="ts">
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { SelectOption, useMessage } from 'naive-ui';
  import { ref, computed } from 'vue';
  import { GetServiceList, SelectSystem } from '@/api/service/service';
  import { SwapHorizontalOutline } from '@vicons/ionicons5';
  import {storage} from "@/utils/Storage";
  import {ACCESS_TOKEN} from "@/store/mutation-types";

  interface server {
    id: number;
    name: string;
    path: string;
    label: string;
    value: string;
    is_selected: boolean;
  }

  export default {
    name: 'Index',
    props: {
      collapsed: {
        type: Boolean,
      },
    },
    setup(_props) {
      const useUserStore = useUserStoreWidthOut();
      const title = ref(useUserStore.config.admin_web_title);
      const logoCSS = computed(() => {
        return useUserStore.config.mode === 'release'
          ? {
              color: `#e74d4d`,
              'font-size': `18px`,
              'font-weight': `bold`,
              'margin-bottom': `0`,
            }
          : {
              color: `#ffffff`,
              'font-size': `18px`,
              'font-weight': `bold`,
              'margin-bottom': `0`,
            };
      });
      const message = useMessage();
      return {
        title,
        logoCSS,
        message,
      };
    },
    data() {
      return {
        servers: ref<server[]>([]),
        selectedServer: ref<string>(''),
      };
    },
    computed: {
      SafetyCertificateOutlined() {
        return SwapHorizontalOutline;
      },
    },
    mounted() {
      this.loadServers();
    },

    methods: {
      isSameOrigin(url1: string, url2: string): boolean {
        try {
          const a = new URL(url1);
          const b = new URL(url2);
          return a.hostname === b.hostname && a.port === b.port;
        } catch (e) {
          // 如果URL解析失败，则认为不同源
          return false;
        }
      },

      async loadServers() {
        try {
          const res = await GetServiceList();
          res.forEach((server: server) => {
            server.label = server.name;
            server.value = server.name;
            if (server.is_selected) {
              this.selectedServer = server.name;
              // const origin = window.location.origin;
              // if (!this.isSameOrigin(origin, server.path)) {
              //   const path = server.path.replace('{access-token}', storage.get(ACCESS_TOKEN));
              //   window.open(path, '_self');
              // }
            }
          });
          console.log('Loaded servers:', res);
          this.servers = res;
        } catch (error) {
          console.error('Failed to load servers:', error);
        }
      },

      handleUpdateValue(system_id: string, option: SelectOption) {
        // await SelectSystem({
        //   ...{ system_id: option.id },
        // })
        //   .then((res) => {
        //     console.log('_res:' + JSON.stringify(res));
        // const ex = 7 * 24 * 60 * 60 * 1000;
        // storage.set(ACCESS_TOKEN, res.token, ex);
        const url: string = option.path + '';
        const path = url.replace('{access-token}', storage.get(ACCESS_TOKEN));
        window.open(path, '_self');
        // })
        // .catch((e: Error) => {
        //   this.message.error(e.message ?? '操作失败');
        // });
      },
    },
  };
</script>

<style lang="less" scoped>
  .logo {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 64px;
    line-height: 64px;
    overflow: hidden;
    white-space: nowrap;

    img {
      width: auto;
      height: 32px;
    }

    .title {
      margin-bottom: 0;
    }
  }
</style>
