<template>
  <LayoutVue>
    <div class="flex flex-col w-full h-full">
      <div class="flex items-center">
        <Search v-model="searchValue" placeholder="搜索名称/备案号"></Search>
        <Avatar class="ml-7"></Avatar>
      </div>
      <div
        class="flex items-center justify-between flex-shrink-0"
        style="margin-top: 26px"
      >
        <Title>版权列表</Title>
        <div class="flex items-center">
          <syButton
            style="width: 128px"
            mode="elementBtn"
            size="large"
            @click="
              () => {
                $router.push('/filingPersonManagement');
              }
            "
            type="default"
          >
            <img
              src="@/assets/img/filingPersonManage.png"
              style="margin-right: 3px"
              class="h-5"
            />
            备案人管理</syButton
          >
          <syButton
            style="width: 113px"
            mode="elementBtn"
            size="large"
            @click="
              () => {
                $router.push('/draftBox');
              }
            "
            type="default"
          >
            <img
              src="@/assets/img/draftBox.png"
              style="margin-right: 3px"
              class="h-5"
            />
            草稿箱</syButton
          >
          <syButton
            style="width: 113px"
            mode="elementBtn"
            size="large"
            @click="
              $router.push({
                name: 'addCopyRight',
              })
            "
            type="primary"
            >添加版权</syButton
          >
        </div>
      </div>
      <div class="flex-grow overflow-hidden mt-4">
        <CopyrightTable
          ref="CopyrightTableRef"
          v-show="activedMenu === eTableTab.going"
          :data="tableData"
          :loading="loading"
          :show-state-filter-icon="true"
          height="100%"
          @scrollToEnd="fetchNextPage"
          @clickStatusFilter="handleClickStatusFilter"
          @view-certificates="
            ({ url }) => {
              imgUrl = url;
              imageDisplayVisible = true;
            }
          "
          @download-cert="
            ({ url }) => {
              saveAs(url);
            }
          "
          @refresh="handleRefetch"
        >
        </CopyrightTable>
      </div>
    </div>
    <CopyRightNotify v-model:visible="copyRightNotifyVisible"></CopyRightNotify>
    <ImageDisplay :url="imgUrl" v-model:visible="imageDisplayVisible">
      <div class="flex mt-7">
        <div class="imgBtn mr-2.5" @click="saveAs(imgUrl)">保存证书</div>
        <div
          class="imgBtn"
          @click="
            printJS({
              printable: imgUrl,
              type: 'image',
              style: 'width: 100%; padding: 0px;margin: 0',
            })
          "
        >
          打印证书
        </div>
      </div>
      <div class="flex-grow"></div>
    </ImageDisplay>
  </LayoutVue>
</template>
<script lang="ts" setup>
import LayoutVue from "@/components/Layout.vue";
import { ref, watch } from "vue";
import Search from "@/components/Search/index.vue";
import Avatar from "@/components/Avatar/index.vue";
import Title from "@/components/Title.vue";
import { syButton } from "cqk-sy-ui";
import Icon from "@/components/Icon/index.vue";
import { eStatusOfCopyright } from "@/components/ApproveStatus/status";
import CopyrightTable from "./CopyrightTable.vue";
import { eTableTab } from "./types";
import { useTableData } from "@/components/Table/hooks";
import { debounce } from "lodash";
import CopyRightNotify from "@/components/Dialogs/CopyRightNotify/index.vue";
import { getCopyRights } from "@/service/copyrightService";
import { iCopyRight } from "@/types/copyright";
import ImageDisplay from "@/components/ImageDisplay/index.vue";
import { saveAs } from "file-saver";
import printJS from "print-js";

const copyRightNotifyVisible = ref(false);
const searchValue = ref("");
const imgUrl = ref("");
const imageDisplayVisible = ref(false);
const activedMenu = ref(eTableTab.going);
const currentStatusForGoing = ref(eStatusOfCopyright.ALL); // 进行中的表格的状态

const CopyrightTableRef = ref<InstanceType<typeof CopyrightTable>>();

const fetchTableData = async ({
  page,
  page_size,
  currentStatus,
}: {
  page: number;
  page_size: number;
  currentStatus: eStatusOfCopyright;
}) => {
  page;
  page_size;
  currentStatus;

  const statuslist = [];
  if (currentStatus === eStatusOfCopyright.ALL) {
    statuslist.push(
      ...[
        eStatusOfCopyright.WAITING_CHECK,
        eStatusOfCopyright.RECORD_SUCCESS,
        eStatusOfCopyright.NOT_PASSED,
      ]
    );
  } else {
    statuslist.push(currentStatus);
  }

  const isBA = searchValue.value.match(/^BA\d*$/);

  const res = await getCopyRights({
    record_work_name: isBA ? "" : searchValue.value,
    record_no: isBA ? searchValue.value : "",
    record_work_status: statuslist,
    page,
    page_size,
  });
  return {
    total: res?.data.total,
    data: (res?.data.results as iCopyRight[]) || [],
  };
};

const generateFetchTableData = (getCurrentStatus: () => eStatusOfCopyright) => {
  return ({ page, page_size }: { page: number; page_size: number }) => {
    return fetchTableData({
      page,
      page_size,
      currentStatus: getCurrentStatus(),
    });
  };
};

const {
  fetchNextPage: fetchNextPage,
  tableData: tableData,
  refetch: refetch,
  loading: loading,
} = useTableData({
  fetchData: generateFetchTableData(() => currentStatusForGoing.value),
});

const refetchDebounce = debounce(() => {
  handleRefetch();
}, 500);

function handleRefetch() {
  CopyrightTableRef.value?.tableRef?.scrollTo(0, 0);
  refetch();
}

const handleClickStatusFilter = (status: eStatusOfCopyright) => {
  currentStatusForGoing.value = status;
  handleRefetch();
};

watch(searchValue, () => {
  refetchDebounce();
});
</script>
<style lang="scss" scoped>
.imgBtn {
  width: 100px;
  height: 40px;
  border-radius: 4px;
  border: 1px solid #ffffff;
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
  line-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
</style>
