<template>
  <d-input
    :key="$route.path + $route.query?.val"
    id="golbalSearch"
    class="g-header-search"
    v-model.trim="searchStr"
    :placeholder="placeholder"
    clearable
    @keyup.enter="search"
    @focus="placeholder = '「开搜」：输入搜索内容...'"
    @blur="placeholder = '「开搜」：一搜即达，开发者的AI搜索'"
    autocomplete="off"
  >
    <template #prefix>
      <GIcon name="gt-search" class="g-header-search-icon" />
    </template>
  </d-input>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import microApp from '@micro-zoe/micro-app';

const route = useRoute();
const router = useRouter();
const searchStr = ref(route?.query?.val || '');

const placeholder = ref('「开搜」：一搜即达，开发者的AI搜索');

const search = () => {
  if (!searchStr.value) {
    document.querySelector('#golbalSearch').blur();
    return;
  }

  if (microApp.router.current.has('micoro-app-homeweb-app')) {
    microApp.router.push({
      name: 'micoro-app-homeweb-app',
      path: router.resolve({ name: 'search', query: { val: searchStr.value, type: route?.query?.type || 'repo' }}).href
    });
  } else {
    router.push({ name: 'search', query: { val: searchStr.value || '', type: route?.query?.type || 'repo' }});
  }
};

watch(() => route.query?.val, (newVal) => {
  microApp.setData('micoro-app-homeweb-app', { type: 'search', data: newVal || '' });
});

const handleDataChange = ({ name, type, data }) => {
  if (name === 'micoro-app-homeweb-app') {
    if (type === 'keyword-change') {
      searchStr.value = data;
    }
    if (type === 'route-change') {
      //
    }
  }
};

onMounted(() => {
  microApp.addDataListener('micoro-app-homeweb-app', handleDataChange, false);
});
onUnmounted(() => {
  microApp.removeDataListener('micoro-app-homeweb-app', handleDataChange);
});
</script>

<style lang="scss">
@import 'devui-theme/styles-var/devui-var.scss';

.g-header-search {
  background: #FFF;
  box-shadow: 0px 2px 5px 1px rgba(0, 0, 0, 0.05) inset;
  &-icon {
    opacity: .5;
    transition: opacity .5s ease;
  }
  .devui-input--focus {
    .g-header-search-icon {
      opacity: 1;
    }
  }
}
</style>
