<script setup lang="ts">
import { ref, computed, nextTick } from "vue";
import { useDetail } from "/@/hooks/core/useDetail";
import { useAsync } from "/@/hooks/core/useAsync";
import { httpInfo, httpAdd, httpStatus, httpSupplierInfo } from "/@/api/purchase/invoiceRelation";
import BasicDescriptions from "/@/components/BasicDescriptions";
import ReconciliationForm from "/@/components/ReconciliationForm";
import ReturnTicketForm from "./components/return-form.vue";
import { useRouter } from "vue-router";
import { DefaultApprovalNode } from "/@/components/ApprovalNode";
import { useUserInfo } from "/@/hooks/core/useUser";
import { usePermission } from "/@/hooks/core/usePermission";
import { createTicketReturnColumns } from "/@/utils/details/_purchase";
import OrderRelation from "/@/components/OrderRelation/src/index.vue";
import InvoiceModal from "./components/invoice-modal.vue";


const pageName = "supplierInvoiceRelationDetail";


const { push } = useRouter();
const showApproval = ref(true)
const { isSuperUser } = useUserInfo();
const { hasPermissionWithCode, permissions } = usePermission(pageName);
const invoiceModalRef = ref<InstanceType<typeof InvoiceModal>>(null);
const formRef = ref<InstanceType<typeof ReconciliationForm> | null>(null);

const { id, isDetail, title, collapses } = useDetail({ baseName: "买入发票关联", collapseLen: 14 });


const isSupplierClient = ref(false)
const { run: detail, data } = useAsync<Record<string, string>>({
  initalData: {},
  success: async (data = {}) => {
    const { supplierName } = data
    const result = await httpSupplierInfo({ name: supplierName })
    const [ supplier = {} ] = (result?.data?.list || [])
    isSupplierClient.value = supplier.has_account
  }
});

const { run: create } = useAsync({ success: () => push("/supply/supplierInvoiceRelation") });

const { run: approval, loading: approvalLoading } = useAsync({
  success: () => refresh()
});

function refresh() {
  requestDetail();
  formRef.value && formRef.value.refresh();
  showApproval.value = false
  nextTick(() => showApproval.value = true)
}

const requestDetail = () => detail(httpInfo({ hpNo: id.value }));
const handleCreate = data => create(httpAdd(data));

function handleApproval(data) {
  const params = { ...data, hpNo: id.value };
  approval(httpStatus(params));
}

if (isDetail.value) requestDetail();
</script>

<template>
  <div class="padding__container">
    <ElTabs>
      <ElTabPane :label="title">
        <ElCollapse v-model="collapses">
          <ElCollapseItem name="1" :title="title">
            <!-- 回票详情 -->
            <BasicDescriptions
              :data="data"
              v-if="isDetail"
              :columns="createTicketReturnColumns((context) => invoiceModalRef?.onDisplay(context))"
            />
            <!-- 创建回票 -->
            <ReturnTicketForm v-else @create="handleCreate" />
          </ElCollapseItem>

          <div v-if="isDetail">
            <ElCollapseItem title="关联信息" name="10" v-if="data && ['2','3','4','6','12'].includes(String(data.status)) && showApproval">
              <OrderRelationApproval readonly :code="data.hpNo" />
            </ElCollapseItem>

            <InvoiceModal ref="invoiceModalRef" />
            <!-- 审批节点 -->
            <template v-if="!isSuperUser">
              <ElCollapseItem title="待发票与订单关联" name="8" v-if="data && data.status == '11'  && hasPermissionWithCode('063')">
                <!-- v-if="!isSupplierClient"  -->
                <OrderRelation
                  :code="data.hpNo" 
                  :payNo="data.payNo" 
                  @refresh="requestDetail"
                  :companyNo="data.companyNo"
                  :supplierNo="data.supplierNo"
                  :multiplePayNos="true"
                />
                <!-- <ElAlert v-else :closable="false" type="warning"  title="当前供应商已开通供应商端,请到供应商端操作" /> -->
              </ElCollapseItem>
              
              <ElCollapseItem title="待财务审核关联信息" name="9" v-loading="approvalLoading" v-if="data.status == '12'  && hasPermissionWithCode('065')">
                <OrderRelationApproval 
                  :rejectCode="13" 
                  :successCode="3" 
                  :code="data.hpNo" 
                  @submit="handleApproval"
                />
              </ElCollapseItem>

              <ElCollapseItem
                v-if="String(data.status) === '2' && hasPermissionWithCode('020')"
                title="买方公司业务审核"
                name="4"
              >
                <DefaultApprovalNode
                  approve-value="3"
                  reject-value="6"
                  @approval="handleApproval"
                />
              </ElCollapseItem>

              <ElCollapseItem
                v-if="String(data.status) === '3' && hasPermissionWithCode('021')"
                title="买方公司认证"
                name="5"
              >
                <DefaultApprovalNode
                  approve-value="4"
                  reject-value="7"
                  @approval="handleApproval"
                />
              </ElCollapseItem>
            </template>
          </div>
        </ElCollapse>
      </ElTabPane>
    </ElTabs>
  </div>
</template>
