<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { Descriptions, Spin, Table } from 'ant-design-vue';

import { getSettlementLedgerDetail } from '#/views/finance/withdrawal/api/settlement';

const loading = ref(false);
const detail = ref<{
  items: Record<string, any>[];
  ledger_log: Record<string, any> | null;
  order_id: number;
  order_no: string;
  order_type: number;
  sum_money: string;
}>({
  items: [],
  ledger_log: null,
  order_id: 0,
  order_no: '',
  order_type: 0,
  sum_money: '0',
});

const columns = [
  { title: '费用类型', dataIndex: 'fee_type_txt', key: 'fee_type_txt' },
  { title: '分账金额', dataIndex: 'money', key: 'money' },
  { title: '结算状态', dataIndex: 'status_txt', key: 'status_txt' },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at' },
];

const [Drawer, drawerApi] = useVbenDrawer({
  onOpenChange(isOpen) {
    if (isOpen) {
      loadDetail();
    } else {
      detail.value = {
        items: [],
        ledger_log: null,
        order_id: 0,
        order_no: '',
        order_type: 0,
        sum_money: '0',
      };
    }
  },
});

async function loadDetail() {
  const data = drawerApi.getData<{
    ledger_log_id?: number;
    merged?: boolean;
    order_id?: number;
    order_type?: number;
  }>();
  if (!data) {
    return;
  }

  loading.value = true;
  try {
    const params =
      data.merged && data.order_id && data.order_type
        ? { order_id: data.order_id, order_type: data.order_type }
        : { ledger_log_id: data.ledger_log_id };
    const res = await getSettlementLedgerDetail(params);
    detail.value = res || detail.value;
  } finally {
    loading.value = false;
  }
}

defineExpose({
  open(row: Record<string, any>) {
    drawerApi.setData({
      ledger_log_id: row.id,
      merged: row.merged,
      order_id: row.order_id,
      order_type: row.order_type,
    });
    drawerApi.open();
  },
});
</script>

<template>
  <Drawer class="w-[720px]" title="结算明细">
    <Spin :spinning="loading">
      <Descriptions bordered :column="1" size="small" class="mb-4">
        <Descriptions.Item label="订单号">
          {{ detail.order_no || '-' }}
        </Descriptions.Item>
        <Descriptions.Item label="合计分账">
          {{ detail.sum_money }}
        </Descriptions.Item>
        <template v-if="detail.ledger_log">
          <Descriptions.Item label="费用类型">
            {{ detail.ledger_log.fee_type_txt }}
          </Descriptions.Item>
          <Descriptions.Item label="结算类型">
            {{ detail.ledger_log.type_txt }}
          </Descriptions.Item>
          <Descriptions.Item label="说明">
            {{ detail.ledger_log.content || '-' }}
          </Descriptions.Item>
        </template>
      </Descriptions>
      <Table
        :columns="columns"
        :data-source="detail.items"
        :pagination="false"
        row-key="id"
        size="small"
      />
    </Spin>
  </Drawer>
</template>
