<script setup lang="ts">
import { ref, computed, shallowRef, nextTick } from "vue";
import { useDetail } from "/@/hooks/core/useDetail";
import { DefaultApprovalNode } from "/@/components/ApprovalNode";
import { httpStatus, httpAdd, httpOldStatus } from "/@/api/purchase/orderRecord";
import ReconciliationForm from "/@/components/ReconciliationForm";
import { usePermission } from "/@/hooks/core/usePermission";
import { useUserInfo } from "/@/hooks/core/useUser";
import { useAsync } from "/@/hooks/core/useAsync";
import { useRouter, useRoute } from "vue-router";
import { httpRequsetExport } from "/@/utils/export";
import PrintOrderRecord from "/@/components/PrintOrderRecord";

import { PURCHASE_OLD_APPLY_DATE } from "/@/utils/constants"

const { push } = useRouter();
const { query } = useRoute();

const record = ref({})
const formRef = ref<InstanceType<typeof ReconciliationForm>>(null);
const status = computed(() => formRef.value?.detail.status || "");
const PrintOrderRecordRef = ref<InstanceType<typeof PrintOrderRecord> | null>(null);

const pageName = "orderRecordDetail";

const _loading = shallowRef(false);
// { code: "020", name: "买方公司业务审核" }

const { hasPermissionWithCode } = usePermission(pageName);
const { id, title, isDetail, collapses } = useDetail({
  baseName: "订单对账",
  collapseLen: 3
});

const { isSuperUser } = useUserInfo();


const isDisplay = ref(true)
const { run: approval } = useAsync({
  success: async () => {
    formRef.value.refresh();
    isDisplay.value = false
    nextTick(() => isDisplay.value = true)
  }
});

const { run: create, loading } = useAsync({
  success: () => push(`/purchase/${query.isQuery ? "orderRecordQuery" : "orderRecord"}`)
});

function handleApproval(data) {
  const params = { ...data, payNo: id.value };
  const date = id.value.slice(3, 9)
  const isOld = Number(date) < PURCHASE_OLD_APPLY_DATE
  approval(isOld ? httpOldStatus(params)  : httpStatus(params));
}

function handleCreate({ cids }: any) {
  const params = { cids: cids.join(",") };
  create(httpAdd(params));
}

async function onDownloadPayInfo() {
  await httpRequsetExport({
    url: "paycgdexport",
    name: "对账单明细表",
    onStart: () => (_loading.value = true),
    onSuccess: () => (_loading.value = false),
    onFail: () => (_loading.value = false),
    params: { payNo: id.value }
  });
}
</script>

<template>
  <div class="padding__container">
    <ElTabs>
      <ElTabPane :label="title">
        <ElCollapse v-model="collapses">
          <!-- 详情 or 创建 -->
          <ElCollapseItem name="1" :title="title">
            <ReconciliationForm 
              v-if="isDisplay"
              :id="id" 
              ref="formRef" 
              :loading="loading" 
              :readonly="isDetail" 
              @create="handleCreate"
              @get-record="_record => record = _record" 
              isPurch
            />
          </ElCollapseItem>

          <!-- 详情 - 审批节点 -->
          <template v-if="isDetail && !isSuperUser">
            <ElCollapseItem name="2" title="买方公司业务审核" v-if="String(status) === '1' && hasPermissionWithCode('039')">
              <DefaultApprovalNode approveValue="2" rejectValue="3" @approval="handleApproval" />
            </ElCollapseItem>
          </template>
        </ElCollapse>
      </ElTabPane>
    </ElTabs>
    <div style="position: absolute; top: 15px; right: 15px" v-if="isDetail">
       <ElButton
        v-if="hasPermissionWithCode('047')" 
        @click="PrintOrderRecordRef.print(true)"
        >
        打印出库单
      </ElButton>
      
      <ElButton 
        v-if="hasPermissionWithCode('046')" 
        @click="PrintOrderRecordRef.print()"
        >
        打印对账单
      </ElButton>

      <ElButton :loading="_loading" type="primary" v-if="hasPermissionWithCode('038')" @click="() => onDownloadPayInfo()">
        对账单明细导出
      </ElButton>
    </div>

    <PrintOrderRecord :record="record" ref="PrintOrderRecordRef" />
  </div>
</template>
