<template>
  <ui-group-option class="sign" :class="{ active, search }">
    <div class="content">
      <span class="cover" @click="flyView(view)">
        <img :src="getResource(getFileUrl(view.cover))" alt="" />
      </span>
      <ui-input
        class="view-title-input"
        type="text"
        :modelValue="view.title"
        :maxlength="15"
        @update:modelValue="(title: string) => $emit('updateTitle', title.trim())"
        v-show="isEditTitle"
        ref="inputRef"
        height="28px"
      />
      <div class="title" v-show="!isEditTitle" @click="flyView(view)">
        <p>{{ view.title }}</p>
        <span> {{ getModelDesc(modelType as ModelType) }}</span>
      </div>
    </div>
    <div class="action" v-if="edit">
      <ui-icon type="order" ctrl />
      <ui-more
        :options="menus"
        style="margin-left: 20px"
        @click="(action: keyof typeof actions) => actions[action]()"
      />
    </div>
  </ui-group-option>
</template>

<script lang="ts" setup>
import { ref, computed, watchEffect } from "vue";
import { useFocus } from "bill/hook/useFocus";
import { custom, getResource } from "@/env";
import { deepIsRevise, getFileUrl } from "@/utils";
import { loadModel, getModelDesc, ModelType, currentModel } from "@/model";
import { viewToModelType } from "@/store";

import type { View } from "@/store";
import { Message } from "bill/expose-common";
import { flyView } from "@/hook/use-fly";

const props = withDefaults(
  defineProps<{ view: View; edit?: boolean; search?: boolean }>(),
  { edit: true }
);
const emit = defineEmits<{
  (e: "updateCover", cover: string): void;
  (e: "updateTitle", title: string): void;
  (e: "delete"): void;
}>();

const menus = [
  { label: "重命名", value: "rename" },
  { label: "删除", value: "delete" },
];

const inputRef = ref();
const isEditTitle = useFocus(computed(() => inputRef.value?.vmRef.root));

watchEffect(() => {
  if (!isEditTitle.value && !props.view.title.length) {
    isEditTitle.value = true;
    Message.warning("视图名称不可为空");
  }
});

const actions = {
  delete: () => emit("delete"),
  rename: () => (isEditTitle.value = true),
};
const modelType = viewToModelType(props.view);
const active = computed(() => {
  return (
    custom.currentView === props.view && !deepIsRevise(currentModel.value, modelType)
  );
});
</script>

<style lang="scss" src="./style.scss" scoped></style>

<style>
.view-title-input.ui-input .text.suffix input {
  padding-right: 50px;
}
</style>
