<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import contentConfig from "./config/content.config";
import { usePageSearch, type PageHooks, type PageEvents } from "/@/hooks/page";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { usePermission } from "/@/hooks/core/usePermission";
import { httpStatus } from "/@/api/purchase/orderRecord";
import { httpRequsetExport } from "/@/utils/export";
import { useAsync } from "/@/hooks/core/useAsync";
import searchConfig from "./config/search.config";

const PageName = "orderRecord";
const baseUrl = "/purchase/orderRecordDetail";
const selectlist = ref<any[]>([]);
const loading = ref(false);

const { push } = useRouter();
const contentRef = ref<any>(null);

const { run: revoke } = useAsync({
  success: () => contentRef.value.onSearch()
});

const { hasPermissionWithCode } = usePermission("orderRecord");

const hooks: PageHooks = {
  pageSearchHook: () => usePageSearch(undefined, undefined, searchConfig)
};

const handleRevoke = payNo => {
  revoke(
    httpStatus({
      payNo,
      status: "4"
    })
  );
};

const events: PageEvents = {
  content: {
    create: () => push(baseUrl),
    preview: ({ payNo }) => push(`${baseUrl}?id=${payNo}`)
  }
};

async function onDownloadPayInfo() {
  if (selectlist.value.length === 0) {
    ElMessage.warning("请选择一条对账单");
    return;
  }

  if (selectlist.value.length > 1) {
    ElMessage.warning("只能选择一条对账单");
    return;
  }

  await httpRequsetExport({
    url: "paycgdexport",
    name: "对账单明细表",
    onStart: () => (loading.value = true),
    onSuccess: () => (loading.value = false),
    onFail: () => (loading.value = false),
    params: {
      payNo: selectlist.value[0].payNo
    }
  });
}
</script>

<template>
  <PageAuth :pageName="PageName">
    <PageContainer
      :hooks="hooks"
      :events="events"
      :contentConfig="contentConfig"
      :search-config="searchConfig"
      :get-content-ref="ref => (contentRef = ref)"
      @content-select-change="items => (selectlist = items)"
    >
      <template #content_header>
        <ElButton
          size="small"
          v-if="hasPermissionWithCode('038')"
          :loading="loading"
          @click="() => onDownloadPayInfo()"
        >
          对账单明细导出
        </ElButton>
      </template>

      <template #content_action="row">
        <ElTooltip placement="top" content="撤销对账申请">
          <ElButton
            v-if="
              (String(row.status) === '1' || String(row.status) === '2') &&
              hasPermissionWithCode('006')
            "
            type="primary"
            link
            text
            :icon="useRenderIcon('refresh-right')"
            @click="() => handleRevoke(row.payNo)"
          />
        </ElTooltip>
      </template>
    </PageContainer>
  </PageAuth>
</template>
