<template>
  <div class="flex flex-wrap">
    <AlbumItem
      class="flex-shrink-0"
      :name="n.name"
      :time="n.update_time"
      :bg-url="n.m_img_url"
      v-for="(n, index) in list"
      @rename="renameAlbum(n)"
      @delete="deleteAlbum(n)"
      @click="$emit('clickAlbum', { id: n.id, name: n.name })"
    >
    </AlbumItem>
    <RenameDialog
      v-model:visible="renameShow"
      :old-name="oldName"
      placeholder="请输入专辑名"
      :confirm-rename="confirmRename"
    ></RenameDialog>
  </div>
</template>

<script setup lang="ts">
import { showTip } from "@/components/GlobalMount/api";
import { ElMessage } from "element-plus";
import AlbumItem from "./AlbumItem.vue";
import { ref } from "vue";
import RenameDialog from "./RenameDialog.vue";
import { $ajax } from "@/service";
import { URLS } from "@/service/URL";

const props = defineProps<{
  list: any[];
}>();

const renameShow = ref(false);
const oldName = ref("");
const currentId = ref("");

const emit = defineEmits(["clickAlbum", "update"]);

const renameAlbum = (albumMsg: any) => {
  renameShow.value = true;
  oldName.value = albumMsg.name;
  currentId.value = albumMsg.id;
};

const deleteAlbum = async (item: any) => {
  showTip(
    "确认删除此专辑及专辑内全部内容吗？删除后无法找回，请谨慎操作。",
    async () => {
      const ret = await $ajax({
        url: URLS.categories,
        type: "delete",
        params: {
          ids: [item.id],
        },
      });
      console.log(ret, "show ret");
      if (ret && ret!.code === 200) {
        ElMessage.success("删除成功");
        emit("update");
      }
    }
  );
};

const confirmRename = async (name: string) => {
  if (name === oldName.value) {
    return true;
  }
  const res = await $ajax({
    url: URLS.category,
    type: "put",
    params: {
      id: currentId.value,
      name,
    },
  });
  if (res && res.code === 200) {
    ElMessage.success("重命名成功");
    emit("update");
    return true;
  } else {
    return false;
  }
};
</script>

<style></style>
