<script setup lang="ts">
import { MdPreview } from "md-editor-v3";
import { useRouter } from "vue-router";
import { useRequest } from "vue-request";
import { myRequest } from "@/requests/request.ts";
import { userinfo } from "@/store/store.ts";
import { ElMessage, ElMessageBox } from "element-plus";
import { formatError } from "@/utils/utils.ts";
import _ from "lodash";
import YlActionDiv from "@/components/yl-action-div.vue";

const router = useRouter();
const {
  data: noteList,
  loading,
  run,
} = useRequest(() => myRequest(`/api/notes`, userinfo.token), {
  refreshDeps: [() => userinfo.token],
});

const { runAsync: add } = useRequest(
  () =>
    myRequest(
      `/api/notes`,
      userinfo.token,
      { content: "# new note \n" },
      "post",
    ),
  { manual: true },
);
const { runAsync: del } = useRequest(
  (id: number) => myRequest(`/api/notes/${id}`, userinfo.token, {}, "delete"),
  { manual: true },
);

const toDetail = (id: number) => {
  router.push(`/notes/${id}`);
};
const toAdd = () => {
  add()
    .then((res) => toDetail(_.get(res, "data", -1)))
    .catch((res) => ElMessage.error(formatError(res)));
};
const toDelete = (id: number) => {
  ElMessageBox.confirm(`确认删除笔记--${id}?`, "确认操作", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    del(id)
      .then(() => {
        ElMessage.success("删除成功");
        run();
      })
      .catch((res) => ElMessage.error(formatError(res)));
  });
};
</script>

<template>
  <yl-action-div class-name="center">
    <el-button link @click="toAdd"
      ><el-icon><i class="bi-file-earmark-plus" /></el-icon
      ><span>新建笔记</span></el-button
    >
  </yl-action-div>
  <div v-loading="loading">
    <div class="note-div" v-for="item in noteList?.data">
      <el-icon class="del-icon" @click="() => toDelete(item.id)"
        ><i class="bi-x-circle"
      /></el-icon>
      <MdPreview
        :model-value="item.content"
        style="text-align: center; height: 100%"
        @click="toDetail(item.id)"
      />
    </div>
  </div>
</template>

<style scoped>
.note-div {
  position: relative;
  height: 250px;
  background-color: #2dcca730;
  padding: 10px 30px 10px 10px;
  margin-bottom: 10px;
}
.note-div:hover {
  .del-icon {
    display: block;
  }
}
.del-icon {
  display: none;
  right: 10px;
  position: absolute;
  color: #fab6b6;
  font-size: 16px;
  z-index: 9;
}
</style>
