<script setup lang="ts">
import { ref, watch, shallowRef } from "vue";
import apis from "./config/apis";
import { usePermission } from "/@/hooks/core";
import { httpRequsetExport } from "/@/utils/export";
import { isBeyondTime } from "/@/views/time/_utils";
import sourceSearchConfig from "./config/search.config";
import sourceContentConfig from "./config/content.config";
import { usePageSearch, type PageHooks } from "/@/hooks/page";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { PageContentInstance } from "/@/components/PageContent";
import { useBusinessSearch, useBusinessContent } from "./../../_hooks";
import { useUserStore } from "/@/store/modules/user";

const pageContentRef = ref<PageContentInstance | null>(null);
const loading = shallowRef(false);
const lockKey = "companyNo";

const pageName = "orderDiff";
const { hasPermissionWithCode } = usePermission(pageName);

const userStore = useUserStore();
const { searchConfig } = useBusinessSearch({
  sourceConfig: sourceSearchConfig,
  queryField: "companyNo"
});

const searchConfigRef = ref(searchConfig);

const { contentConfig } = useBusinessContent({
  sourceConfig: sourceContentConfig,
  apis: { httpList: apis.list }
});

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

watch(
  () => userStore.level,
  level => {
    const { formItems } = searchConfigRef.value;
    const index = formItems.findIndex(({ field }) => field === "depart_id");
    const { itemid = "" } = userStore.info || {};

    if (Number(level) === 2) {
      // searchConfigRef.value.formItems[index].disabled = Number(level) === 2;
      searchConfigRef.value.formItems[index].defaultValue = itemid;
    }
  },
  {
    immediate: true
  }
);

const callback = {
  onSuccess: () => (loading.value = false),
  onStart: () => (loading.value = true),
  onFail: () => (loading.value = false)
};


async function handleExportAllReport() {
  const params = pageContentRef.value.getBasicParams() || {};
  const { start, end } = params;
  const beyondTime = isBeyondTime({ start, end, len: 30 });

  if (beyondTime) return;

  await httpRequsetExport({
    isAdmin: false,
    name: "工差明细单.xlsx",
    fileType: "aplication/x-msexecl",
    url:"/purchease/sale/orderDiffListExport",
    ...callback,
    params
  });
}
</script>

<template>
  <PageContainer
    :hooks="hooks"
    :getContentRef="ref => (pageContentRef = ref)"
    :content-config="contentConfig"
    :search-config="searchConfig"
    lockKey="companyNo"
  >
    <template #content_header>
      <el-button
        v-if="hasPermissionWithCode('18')"
        :icon="useRenderIcon('arrow-up-line')"
        @click="handleExportAllReport"
        size="small"
        type="primary"
        >
        导出
      </el-button>
    </template>
  </PageContainer>
</template>
