<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useAsync, useResponseHandle } from "/@/hooks";
import { examRecord } from "/@/components/examRecord";
import Invoice from "/@/components/Invoice";
import { approvalProcess } from "./components/approval-process";
import InvoiceDetailVue from "./components/invoice-detail/index.vue";
import AddEditForm from "./components/add-edit-form/add-edit-form.vue";
import { useUserInfo } from "/@/hooks/core/useUser";
import { usePermission } from "/@/hooks/core/usePermission";

import {
  httpCompanyList,
  httpSetPost,
  httpStatus,
  httpDetail,
  httpList
} from "/@/api/InvoiceSales/invoiceApply";

const { query } = useRoute();
const responseHandle = useResponseHandle();
const { isSuperUser } = useUserInfo();

const PageName = "invoiceApplyDetail";
//   { code: "025", name: "财务审核" },
const { hasPermissionWithCode } = usePermission(PageName);

//是否支持金税
const isSupport = ref(false);

const examCode = ref("");
const activeName = computed(() => (isCreate.value ? "0" : "1"));
const collapseItem = ref(["0", "1", "2", "3", "4"]);

const id = computed(() => query.id);
const isCreate = computed(() => !id.value);

const { push } = useRouter();

const {
  loading,
  data: invoiceDetail,
  run: invoiceDetailRun
} = useAsync<Record<string, string>>({
  initalData: {},
  success: () =>
    invoiceDetail.value &&
    companyRun(httpCompanyList({ companyNo: invoiceDetail.value.inv_out }))
});

const { data: list, run: listRun } = useAsync<Array<Record<string, string>>>({
  isList: true,
  initalData: []
});

const { data: companylist, run: companyRun } = useAsync<
  Array<Record<string, string>>
>({
  isList: true,
  initalData: [],
  success: () => {
    const [company] = companylist.value || [];
    if (!company) return;
    const { input_ticket } = company;
    isSupport.value = input_ticket === "1";
  }
});

const showApproval = computed(() => {
  return (
    (String(invoiceDetail.value.status) === "1" &&
      hasPermissionWithCode("025")) ||
    String(invoiceDetail.value.status) === "2"
  );
});

//最大开票金额
const showInvStatus = computed(() => {
  const { status } = invoiceDetail.value;
  return ["4", "6"].includes(String(status));
});

//是否电子票
const isElectronic = computed(() => {
  const { inv_type } = invoiceDetail.value;
  return inv_type === "3" || inv_type === "4";
});

//是否电子专票
const isSpecialTicket = computed(() => {
  const { inv_type } = invoiceDetail.value;
  return inv_type === "4";
});

//是否普票
const isPlain = computed(() => {
  const { inv_type } = invoiceDetail.value;
  return inv_type === "2" || inv_type === "3";
});

//当前的审批流程 ->
const currentProcess = computed(() => {
  const { status } = invoiceDetail.value;
  return approvalProcess[String(status)] || {};
});

//设置状态/物流
async function handleChangeStatus({ status, ...otherParmas }) {
  let response: any;
  if (!status) {
    //设置物流
    response = await httpSetPost({ invNo: id.value, ...otherParmas });
  } else {
    //设置状态
    response = await httpStatus({ invNo: id.value, status, ...otherParmas });
  }
  const { code, message } = response;
  responseHandle({
    code,
    message,
    handler: () => push("/InvoiceSales/invoiceApply")
  });
}

const requesetlist = () => {
  listRun(httpList({ invNo: id.value }));
};

const requesetInvoiceDetail = () => {
  invoiceDetailRun(httpDetail({ invNo: id.value }));
};

onMounted(() => {
  if (!isCreate.value) {
    requesetInvoiceDetail();
    requesetlist();
  }
});
</script>

<template>
  <div class="main bg-white" v-loading="loading">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="新建发票申请" name="0" v-if="isCreate">
        <AddEditForm />
      </el-tab-pane>

      <el-tab-pane label="业务详情" name="1" v-if="!isCreate">
        <el-collapse v-model="collapseItem">
          <el-collapse-item title="发票申请详情" name="2">
            <InvoiceDetailVue v-loading="loading" :detail="invoiceDetail" />
          </el-collapse-item>

          <el-collapse-item
            name="3"
            title="发票详情"
            v-if="list.length > 0 && list[0].inv_number && showInvStatus"
          >
            <Invoice :inv-number="list[0].inv_number" type="sale" />
          </el-collapse-item>

          <template v-if="!isSuperUser">
            <el-collapse-item
              :title="currentProcess.title"
              name="4"
              v-if="Object.keys(currentProcess).length && showApproval"
            >
              <component
                :is="currentProcess.component"
                :is-electronic="isElectronic"
                :is-support="isSupport"
                :is-special-ticket="isSpecialTicket"
                :is-plain="isPlain"
                :inv-type="invoiceDetail.inv_type"
                @change-status="handleChangeStatus"
              />
            </el-collapse-item>
          </template>
        </el-collapse>
      </el-tab-pane>
      <el-tab-pane label="审批记录" name="2" v-if="!isCreate">
        <examRecord :examCode="examCode" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}
</style>
