<template>
  <Layout class="flex flex-col">
    <div class="flex items-center flex-shrink-0">
      <Search placeholder="搜索" v-model="searchStr"></Search>
      <Avatar class="ml-7"></Avatar>
    </div>
    <div class="flex justify-between flex-shrink-0" style="margin-top: 26px">
      <Title>{{ debouncedSearchStr !== "" ? "搜索结果" : "溯源管理" }}</Title>
      <div class="flex items-center" v-if="debouncedSearchStr === ''">
        <syButton
          style="width: 113px"
          mode="elementBtn"
          size="large"
          type="default"
          @click="$router.push('/templateManagement')"
        >
          <img
            src="@/assets/img/templateIcon.svg"
            style="margin-right: 3px"
            alt=""
            srcset=""
          />
          模板管理</syButton
        >
        <syButton
          style="width: 113px"
          mode="elementBtn"
          @click="addProofVisible = true"
          size="large"
          type="primary"
        >
          新建</syButton
        >
      </div>
    </div>
    <div v-show="debouncedSearchStr === ''">
      <syMoreOperate
        :teleport="true"
        :list="sortList"
        :width="170"
        @click-item="(v) => handleClickSortList(v)"
      >
        <div class="flex items-center">
          <div style="font-size: 13px; font-weight: 400; color: #717171">
            {{ sortList.find((i) => i.value === sortBy)?.name }}
          </div>
          <img src="@/assets/img/filterIcon.svg" style="margin-left: 4px" />
        </div>
      </syMoreOperate>
    </div>
    <div class="flex-grow overflow-hidden -mr-2">
      <div class="h-full pr-2">
        <IntroCard
          v-if="debouncedSearchStr === ''"
          style="margin-top: 14px"
          class="flex-shrink-0"
        ></IntroCard>
        <ProofTable
          style="margin-top: 22px"
          ref="proofTableRef"
          :data="tableData"
          :loading="loading"
          @scroll-to-end="fetchNextPage"
          @delete="handleDeleteGoodsShow"
          @duplicate="
            (e) => {
              isShowCopy = true;
              focusedProofDetail = e;
            }
          "
          @privacy="handlePrivacy"
          @increment="handleIncrement"
        ></ProofTable>
      </div>
    </div>
    <syCommonDialog
      :visible="isShowCopy"
      @closePopup="isShowCopy = false"
      showMask
      :elementDialogProps="{
        title: '创建副本',
      }"
      type="element"
      :btnConfig="{
        type: 'noBorder',
        btns: btns,
        btnFunctions: [
          {
            name: '取消',
            click: async () => {
              return copyGoodsRef.closeDialog();
            },
          },
          {
            name: '确定',
            click: handleConfirmCopy,
          },
        ],
      }"
    >
      <CopyGoods
        v-if="isShowCopy"
        ref="copyGoodsRef"
        @close="isShowCopy = false"
        :Copydetails="focusedProofDetail"
        @update=""
      ></CopyGoods>
    </syCommonDialog>
    <syCommonDialog
      :visible="showDeleteDialog"
      @closePopup="showDeleteDialog = false"
      showMask
      type="element"
      :elementDialogProps="{
        title: focusedProofDetail?.status === 0 ? '提示' : '删除',
      }"
      :btnConfig="{
        type: 'noBorder',
        btns: btns,
        btnFunctions: [
          {
            name: '取消',
            async click() {
              return true;
            },
          },
          {
            name: '确定',
            click: async () => {
              await deleteGoodsRef2.Determine();
              refetch();
              return true;
            },
          },
        ],
      }"
    >
      <DeleteGoods
        v-if="showDeleteDialog"
        ref="deleteGoodsRef2"
        @CloseDg="showDeleteDialog = false"
        :id="focusedProofDetail.id"
        :status="focusedProofDetail.status"
        @deleteSuccess="handleDeleteSuccess"
      >
      </DeleteGoods>
    </syCommonDialog>
    <DeleteGoods
      v-show="false"
      ref="deleteGoodsRef"
      @CloseDg="showDeleteDialog = false"
      :id="focusedProofDetail?.id"
      :status="focusedProofDetail?.status"
      @deleteSuccess="handleDeleteSuccess"
    />
    <syCommonDialog
      :visible="addProofVisible"
      @closePopup="addProofVisible = false"
      showMask
      type="element"
      :elementDialogProps="{
        title: '添加存证',
      }"
      :btnConfig="{
        type: 'noBorder',
        btns: btns,
        btnFunctions: [
          {
            name: '取消',
            async click() {
              return true;
            },
          },
          {
            name: '确定',
            click: () => {
              return addProofRef.determine();
            },
          },
        ],
      }"
    >
      <AddProof
        v-if="addProofVisible"
        ref="addProofRef"
        @cancel="addProofVisible = false"
        :navigate="navigate"
      >
      </AddProof>
    </syCommonDialog>
    <syCommonDialog
      type="element"
      :visible="showIncrements"
      @closePopup="showIncrements = false"
      showMask
      :elementDialogProps="{
        title: '增量更新',
      }"
      :btnConfig="{
        type: 'noBorder',
        btns,
        btnFunctions: [
          {
            name: '取消',
            async click() {
              return true;
            },
          },
          {
            name: '确定',
            click: () => incrementRef.checkForm(),
          },
        ],
      }"
    >
      <Increment
        v-if="showIncrements"
        ref="incrementRef"
        :pre_hash="preHash"
        :evidenceName="baseProof?.name"
        :baseProof="baseProof"
        :navigate="navigate"
        @close="showIncrements = false"
      ></Increment>
    </syCommonDialog>
  </Layout>
</template>
<script lang="ts" setup>
import { router } from "@/router";
import { ref, watch } from "vue";

import Search from "@/components/Search/index.vue";
import Layout from "@/components/Layout.vue";
import Avatar from "@/components/Avatar/index.vue";
import Title from "@/components/Title.vue";
import IntroCard from "@/views/Tracing/tracingManagement/components/IntroCard.vue";
import AddProof from "@/views/Tracing/tracingManagement/components/AddProof.vue";
import ProofTable from "./components/ProofTable/index.vue";
import CopyGoods from "./components/CopyGoods/index.vue";
import DeleteGoods from "./components/DeleteGoods/index.vue";
import Increment from "./components/Increment/index.vue";

import {
  syButton,
  syMoreOperate,
  syCommonDialog,
  GO_URLS,
  syScrollBar,
} from "cqk-sy-ui";
import { btns } from "@/config/btns";
import { useTableData } from "@/components/Table/hooks";
import { $ajax } from "@/service";
import { watchDebounced } from "@vueuse/core";
import { watchStrChangeDebounceTime } from "@/config/time";
import { showTip } from "@/components/GlobalMount/api";
import { ElMessage } from "element-plus";
import { iProof } from "../tracingDetail/types";
import Icon from "@/components/Icon/index.vue";

const proofTableRef = ref<InstanceType<typeof ProofTable> | null>(null);
const copyGoodsRef = ref<any>();
const addProofRef = ref<any>();
const addProofVisible = ref(false);
const isShowCopy = ref(false);
const showDeleteDialog = ref(false);
const showIncrements = ref(false);
const searchStr = ref("");
const debouncedSearchStr = ref("");
const deleteGoodsRef = ref<any>();
const deleteGoodsRef2 = ref<any>();
const incrementRef = ref<any>();
const sortBy = ref("modified");
const focusedProofDetail = ref<any>();

const baseProof = ref<iProof>();
const preHash = ref("");

const sortList = [
  {
    name: "最新修改",
    value: "modified",
    click() {
      sortBy.value = "modified";
    },
  },
  {
    name: "最早创建",
    value: "created",
    click() {
      sortBy.value = "created";
    },
  },
];

const navigate = router.push;

const handleClickSortList = (v: string) => {
  sortList.find((i) => i.value === v)?.click();
};
const handleConfirmCopy = async () => {
  const res = await copyGoodsRef.value.checkForm();
  if (res) {
    refetch();
    return true;
  } else {
    return false;
  }
};
const handleDeleteGoodsShow = (item: any) => {
  focusedProofDetail.value = item;
  if (item.status === 0) {
    // 提示
    showTip("此操作将永久删除该文件, 是否继续?", () => {
      deleteGoodsRef.value.Determine();
    }),
      () => {};
  } else {
    showDeleteDialog.value = true;
  }
};

const handlePrivacy = (item: any) => {
  const PromptID = item.id;
  showTip(
    "确定要隐藏该条记录吗",
    () => {
      hiddenCertificate();
    },
    () => {
      return true;
    }
  );

  async function hiddenCertificate() {
    const res = await $ajax({
      type: "post",
      url: GO_URLS.deleteBlockChainProof,
      params: {
        id: PromptID,
      },
    });
    if (res) {
      refetch();
      ElMessage({
        type: "success",
        message: "隐藏成功!",
      });
    }
  }
};
const handleIncrement = async (item: iProof) => {
  baseProof.value = item;
  if (item.status === 2 && item.increment_num === 0) {
    // 对已上链的存证进行增量更新
    preHash.value = item.hash;
    showIncrements.value = true;
  } else if (item.status === 2 && item.increment_num > 0) {
    const ret = await $ajax({
      type: "post",
      url: GO_URLS.incrementList,
      params: {
        page: 1,
        page_size: 10,
        base_hash: item.hash,
      },
    });
    if (ret) {
      const inc = ret.data.results[0] as iProof;
      if (inc.status === 2) {
        showIncrements.value = true;
        preHash.value = inc.hash;
      } else {
        ElMessage({
          message: "增量数据未上链，无法继续增量",
          type: "warning",
        });
      }
    }
  } else {
    ElMessage({
      message: "增量数据未上链，无法继续增量",
      type: "warning",
    });
  }
};

const handleDeleteSuccess = () => {
  ElMessage.success("删除成功");
  refetch();
};

watchDebounced(
  searchStr,
  () => {
    proofTableRef.value?.tableRef?.scrollTo(0, 0);
    refetch().then(() => {
      debouncedSearchStr.value = searchStr.value;
    });
  },
  { debounce: watchStrChangeDebounceTime }
);

watch(sortBy, () => {
  proofTableRef.value?.tableRef?.scrollTo(0, 0);
  refetch();
});

const { tableData, refetch, loading, fetchNextPage } = useTableData({
  fetchData: async (pageConfig: { page: number; page_size: number }) => {
    const res = await $ajax({
      type: "post",
      url: GO_URLS.list,
      params: {
        status: [],
        is_valid: 0,
        page: pageConfig.page,
        key_words: searchStr.value,
        page_size: pageConfig.page_size,
        create_time_sort: sortBy.value === "created" ? 2 : 0,
        update_time_sort: sortBy.value === "modified" ? 2 : 0,
      },
    });
    return {
      total: res?.data.total || 0,
      data: res?.data.results || [],
    };
  },
});
</script>
<style lang="scss">
.syScrollBarInTraceManagement {
  .el-scrollbar__view {
    height: 100%;
  }
}
</style>
