<template>
  <div class="footer-toolbar">
    <el-pagination
      background
      hide-on-single-page
      layout="prev, pager, next"
      :page-size="1"
      :current-page="pageInfo.pageNum"
      :total="pageInfo.total"
      @current-change="tryGotoNextAnno"
    />
    <div class="opration">
      <el-button type="primary" link @click="clearAction">清空</el-button>
      <el-button type="primary" plain @click="backAction">返回</el-button>
      <el-button v-auth="['article:anno:write']" type="primary" @click="submitAction">提交</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, defineEmits } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter, onBeforeRouteUpdate } from "vue-router";
import { AnnoLabeling } from "@/api/interface";
import { getPageNumInfo, clearAllAnno, annoSubmit } from "@/api/modules/annotation/labeling";

// hooks
const router = useRouter();
const route = useRoute();

// emit
const emit = defineEmits(["refreshAnno"]);

// ref
const articleId = ref<number>(Number(route.query.id));
const pageInfo = ref({} as AnnoLabeling.ResPageNumInfo);

// 清空标注
async function clearAction() {
  await clearAllAnno({ id: articleId.value });
  ElMessage.success("操作成功");
  emit("refreshAnno");
}

// 返回
function backAction() {
  router.back();
}

// 提交 （自动进入下一个，如果没有下一个就返回到列表页）
async function submitAction() {
  await annoSubmit({ ids: [articleId.value] });
  ElMessage.success("提交成功");

  const { pageNum, total } = pageInfo.value;
  if (total - 1 === 0) {
    router.back(); // 最后一个自动返回
  } else {
    tryGotoNextAnno(pageNum <= total - 1 ? pageNum : total - 1);
  }
}

// 根据索引进入下一个标注
async function tryGotoNextAnno(pageNum: number) {
  await loadPageNumInfo({ concurrent: pageNum });
  router.replace({
    query: {
      id: pageInfo.value.id
    }
  });
}

// 获取页码信息
async function loadPageNumInfo(params: AnnoLabeling.ReqPageNumInfoParams) {
  try {
    const res = await getPageNumInfo(params);
    pageInfo.value = res.data || {};
  } catch (error: any) {
    if (error?.code === 404) {
      router.back();
    }
    throw error;
  }
}

onBeforeMount(() => {
  if (route.meta.pageInfo) {
    pageInfo.value = route.meta.pageInfo as AnnoLabeling.ResPageNumInfo;
  } else {
    loadPageNumInfo({ id: articleId.value });
  }
});
onBeforeRouteUpdate(to => {
  to.meta.pageInfo = pageInfo.value;
});
</script>

<style lang="scss" scoped>
.footer-toolbar {
  position: relative;
  display: flex;
  justify-content: center;
  padding: 20px;
  background: #ffffff;
  .opration {
    position: absolute;
    top: 0;
    right: 40px;
    display: flex;
    align-items: center;
    height: 100%;
  }
}
</style>
