<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useDetail } from "/@/hooks/core/useDetail";
import { httpAdd } from "/@/api/purchase/orderRecord";
import ReconciliationForm from "/@/components/ReconciliationForm";
import { useAsync } from "/@/hooks/core/useAsync";
import { useRouter, useRoute } from "vue-router";
import { httpRequsetExport } from "/@/utils/export";
import { usePermission } from "/@/hooks/core/usePermission";
import PrintOrderRecord from "/@/components/PrintOrderRecord";

const { push } = useRouter();
const { query } = useRoute();
const formRef = ref<InstanceType<typeof ReconciliationForm>>(null);
  const PrintOrderRecordRef = ref<InstanceType<typeof PrintOrderRecord> | null>(null);

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

const record = ref({})
const _loading = ref(false);
const { hasPermissionWithCode, permissions } = usePermission("supplyOrderRecordDetail");

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

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

onMounted(() => { 
  console.log(permissions.value);
})

async function onDownloadPayInfo() {
  await httpRequsetExport({
    url: "paycgdexport",
    name: "对账单明细表",
    onFail: () => (_loading.value = false),
    onStart: () => (_loading.value = true),
    onSuccess: () => (_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
              :id="id"
              ref="formRef"
              :loading="loading"
              :readonly="isDetail"
              @create="handleCreate"
              @get-record="_record => record = _record" 
            />
          </ElCollapseItem>
        </ElCollapse>
      </ElTabPane>
    </ElTabs>

    <div v-if="isDetail" style="position: absolute; top: 15px; right: 15px">
      <ElButton 
        v-if="hasPermissionWithCode('047')"   
        @click="PrintOrderRecordRef.print(true)"
        >
        打印出库单
      </ElButton>

      <ElButton 
        v-if="hasPermissionWithCode('046')"   
        @click="PrintOrderRecordRef.print()"
      >
        打印对账单
      </ElButton>

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

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