<template>
  <div class="menus-search-modal">
    <el-dialog
      :model-value="visible"
      fullscreen
      :modal="false"
      destroy-on-close
      :show-close="false"
      @closed="handleClosed"
    >
      <div class="menus-search-modal-search-container">
        <el-autocomplete
          prefix-icon="el-icon-search"
          v-model="form.keyword"
          :fetch-suggestions="querySearch"
          placeholder="菜单搜索：支持中文、路由路径"
          @select="handleSelect"
          ref="autocompleteRef"
        >
          <template #default="{ item }">
            <div>
              <i :class="item.meta.icon" style="margin-right: 10px"></i>
              {{ item.meta.title }}
            </div>
          </template>
        </el-autocomplete>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  reactive,
  ref,
  computed,
  watch,
  onMounted,
} from "vue";
import { ElAutocomplete } from "element-plus";
import filter from "lodash/filter";
import store from "@/hooks/useStore";
import { RouteRecordRaw, useRouter } from "vue-router";

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
    },
  },

  setup(props, { emit }) {
    const autocompleteRef = ref<typeof ElAutocomplete | undefined>(undefined);
    const router = useRouter();
    const flatRouteList = computed(() => {
      return store.state.routeList.flatRouteList;
    });

    const form = reactive({
      keyword: "",
    });
    const querySearch = (queryString: string, cb: any) => {
      var results = queryString
        ? filter(
            flatRouteList.value,
            (rotue) =>
              rotue.path.toLowerCase().includes(queryString.toLowerCase()) ||
              (rotue.meta!.title as unknown as string).includes(queryString)
          )
        : flatRouteList.value;

      // 调用 callback 返回建议列表的数据
      results = results.filter((_, index) => index !== 0);
      cb(results);
    };

    const handleClosed = () => {
      emit("update:visible", false);
    };

    const handleSelect = (routeRecord: RouteRecordRaw) => {
      const { path } = routeRecord;
      router.push(path);
      handleClosed();
    };

    watch(
      () => props.visible,
      () => {
        setTimeout(() => {
          autocompleteRef.value!.focus();
        });
      }
    );

    return {
      querySearch,
      form,
      autocompleteRef,
      handleClosed,
      handleSelect,
    };
  },
});
</script>

<style lang="scss" scoped>
.menus-search-modal {
  &-search-container {
    width: 520px;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }
  ::v-deep(.el-dialog) {
    background-color: rgba(0, 0, 0, 0.5);
  }
  ::v-deep(.el-autocomplete) {
    width: 100%;
  }
}
</style>
