<template>
  <div class="min-h-screen flow-root" style="background: #f9f9f9">
    <div style="height: 50px; margin-bottom: 20px"></div>
    <syHeaderNavBar
      class="fixed top-0 left-0 right-0"
      @close="handleClose"
      :showClose="false"
      @back="checkModifiedAndToast(router.back)"
    >
      <div class="flex items-center justify-between">
        <div>{{ headerTitle }}</div>
        <div class="mr-40" v-show="currentProof?.status === 0">
          <syButton
            mode="elementBtn"
            @click="() => syTraceProofEditRef?.SelectTemplate()"
            type="default"
          >
            选择模板</syButton
          >
          <syButton
            mode="elementBtn"
            @click="handleClickSaveProof"
            type="default"
          >
            仅保存</syButton
          >
          <syButton
            mode="elementBtn"
            @click="handleClickSaveAndUpper"
            type="primary"
          >
            保存并上链</syButton
          >
        </div>
      </div>
    </syHeaderNavBar>
    <div class="flex" style="height: calc(100vh - 70px)">
      <ProcessList
        v-if="proofList.length > 1"
        class="flex-shrink-0"
        :activeId="activeProofId"
        :list="proofList"
        v-loading="loading"
        @scroll-to-end="fetchNextPage"
        @clickItem="activeProofId = $event"
      ></ProcessList>
      <div style="height: calc(100vh - 70px)" class="overflow-hidden flex-grow">
        <syScrollBar
          v-show="currentProof?.status !== null && currentProof?.status !== undefined && 
                [1, 2, 3, 4, 5, 6].includes(currentProof?.status!)"
        >
          <div class="flex w-full">
            <div class="proofDetail-read flex-grow ml-10">
              <OnChainProofDetail
                :showIncrease="
                  currentProofIndex === 0 && currentProof?.status === 2
                "
                :display-data="currentProof?.detail"
                :name="currentProof?.name || ''"
                @increaseProof="increaseProof"
              ></OnChainProofDetail>
            </div>
            <div class="flex-shrink-0 mr-10" style="width: calc(228px + 29px)">
              &nbsp;
            </div>
          </div>
        </syScrollBar>
        <div v-if="currentProof?.status === 0" class="h-full">
          <TemplateEdit
            ref="syTraceProofEditRef"
            @change="change = true"
            :name="currentProof?.name"
            :navigate="navigate"
            :route="$route"
            :go="go"
            :showTip="showTip"
            :detail="currentProof?.detail"
            :note="currentProof?.note"
            :id="currentProof?.id"
            :increasementProof="currentProofIndex !== proofList.length - 1"
            :baseProofHash="baseProof?.hash"
            :baseProofName="baseProof?.name"
          ></TemplateEdit>
        </div>
      </div>
    </div>
    <syBusinessIncreaseProofDialog
      ref="syBusinessIncreaseProofDialogRef"
      :preHash="currentProof?.hash!"
      :base_id="baseProof?.id!"
      :base_hash="baseProof?.hash!"
      :localName="baseProof?.name!"
      :navigate="navigate"
      :cb="afterIncreaseProof"
    ></syBusinessIncreaseProofDialog>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import {
  GO_URLS,
  syHeaderNavBar,
  syScrollBar,
  syButton,
  syBusinessIncreaseProofDialog,
} from "cqk-sy-ui";
import { useTableData } from "@/components/Table/hooks";
import { useRoute } from "vue-router";
import { router } from "@/router";
import { $ajax } from "@/service";
import { showTip } from "@/components/GlobalMount/api";
import { iProof } from "./types";

import ProcessList from "./components/ProcessList.vue";
import OnChainProofDetail from "./components/OnChainProofDetail/index.vue";
import { ElMessage } from "element-plus";
import TemplateEdit from "@/components/TemplateEdit/TraceProofEdit/index.vue";

const syTraceProofEditRef = ref<any>();
const syBusinessIncreaseProofDialogRef =
  ref<InstanceType<typeof syBusinessIncreaseProofDialog>>();
const headerTitle = ref("");
const route = useRoute();
const navigate = router.push;
const go = router.go;
const change = ref(false);
const activeProofId = ref<string>(
  (route.query.activeProofId as string) || (route.query.id as string)
);
const baseProof = ref<iProof>();

const currentProof = computed(() => {
  return proofList.value.find((i) => i.id === activeProofId.value);
});

const currentProofIndex = computed(() => {
  return proofList.value.findIndex((i) => i.id === activeProofId.value);
});

watch(activeProofId, () => {
  change.value = false;
});

const checkModifiedAndToast = (cb: any) => {
  if (change.value) {
    showTip(
      "您还未做保存，确定要返回吗？",
      () => {
        cb();
      },
      () => {}
    );
  } else {
    cb();
  }
};

const handleClose = () => {
  checkModifiedAndToast(() => router.push("/tracingManagement"));
};
const initBaseProof = async () => {
  const ret = await $ajax({
    type: "get",
    url: GO_URLS.proof,
    params: {
      id: route.query.id,
    },
  });
  baseProof.value = ret?.data;
  headerTitle.value = ret?.data.name;
};

const handleClickSaveProof = async (toastSuccess = true) => {
  let res = null as any;
  if (currentProofIndex.value === proofList.value.length - 1) {
    res = await syTraceProofEditRef.value?.updateTemplate(
      currentProof.value!.id!
    );
  } else if (currentProofIndex.value !== proofList.value.length - 1) {
    res = syTraceProofEditRef.value?.updateIncremental(currentProof.value!.id!);
  }
  if (res && toastSuccess) {
    ElMessage.success("编辑成功");
    router.push({
      name: "tracingManagement",
    });
  }
};

const handleClickSaveAndUpper = async () => {
  await handleClickSaveProof(false);
  syTraceProofEditRef.value?.UpperChain();
};

const {
  tableData: proofList,
  loading,
  fetchNextPage,
  refetch,
} = useTableData({
  fetchData: async ({ page, page_size }) => {
    const dataList = [] as iProof[];
    let total = 1;
    if (!baseProof.value) {
      await initBaseProof();
    }
    if (baseProof.value?.hash) {
      const ret2 = await $ajax({
        type: "post",
        url: GO_URLS.incrementList,
        params: {
          page,
          page_size,
          base_hash: baseProof.value?.hash,
        },
      });
      dataList.push(...(ret2?.data.results || []));
      total += ret2?.data.total || 0;
      if (
        ret2?.data.total === 0 ||
        (page - 1) * page_size + (ret2?.data.results || []).length
      ) {
        baseProof.value && dataList.push(baseProof.value);
      }
    } else {
      baseProof.value && dataList.push(baseProof.value);
    }

    // 决定了页面加载时，所选中的流程是哪一个。
    if (page === 1 && !route.query.activeProofId) {
      activeProofId.value = dataList[0].id;
    }

    return {
      total: total,
      data: dataList,
    };
  },
});

const increaseProof = () => {
  console.log((syBusinessIncreaseProofDialogRef.value as any).show());
};

const afterIncreaseProof = (id: string) => {
  ElMessage.success("增量更新成功");
  activeProofId.value = id;
  refetch();
};
watch(activeProofId, () => {
  router.replace({
    query: {
      ...route.query,
      activeProofId: activeProofId.value,
    },
  });
});
</script>

<style lang="scss" scoped>
.proofDetail-read {
  background: #ffffff;
  border-radius: 20px;
}
</style>
