<script lang="ts" setup>
import { computed, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

import {
  Button,
  Descriptions,
  Image,
  Space,
  Spin,
  Table,
  Tabs,
  Tag,
  Timeline,
} from 'ant-design-vue';

import {
  getOrderLedgerDetailApi,
  getOrderReconciliationDetailApi,
  getOrderTraceApi,
} from '#/views/business/order/api/order-ops';
import PrescriptionDetail from '#/views/doctor/doctor-reception/components/PrescriptionDetail.vue';

import DetailModal from '../product-order/components/detail.vue';
import ReconciliationDetailTable from './reconciliation-detail-table.vue';

defineOptions({ name: 'OrderTraceDrawer' });

type LedgerScope = 'all' | 'platform' | 'store';

const router = useRouter();
const userStore = useUserStore();

const loading = ref(false);
const ledgerLoading = ref(false);
const reconciliationLoading = ref(false);
const activeTab = ref('timeline');
const ledgerScope = ref<LedgerScope>('all');
const ledgerSubTab = ref<'product' | 'register'>('product');
const traceData = ref<Record<string, any> | null>(null);
const ledgerProduct = ref<Record<string, any> | null>(null);
const ledgerRegister = ref<Record<string, any> | null>(null);
const reconciliationData = ref<Record<string, any> | null>(null);
const loadedTabs = ref(new Set<string>());

const isPlatformAdmin = computed(
  () => userStore?.userInfo?.roles?.user_type === 2,
);

const ledgerColumns = [
  { title: '费用类型', dataIndex: 'fee_type_txt', key: 'fee_type_txt' },
  { title: '药品图片', dataIndex: 'drug_image', key: 'drug_image', width: 80 },
  { title: '药品名称', dataIndex: 'drug_name', key: 'drug_name' },
  { title: '药品编号', dataIndex: 'drug_number', key: 'drug_number' },
  { title: '药品规格', dataIndex: 'specification', key: 'specification' },
  { title: '分账对象', dataIndex: 'user_type_txt', key: 'user_type_txt' },
  { title: '门店', dataIndex: ['store', 'name'], key: 'store_name' },
  { title: '分账金额', dataIndex: 'money', key: 'money' },
  { title: '结算状态', dataIndex: 'status_txt', key: 'status_txt' },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at' },
];

const currentLedgerData = computed(() =>
  ledgerSubTab.value === 'product' ? ledgerProduct.value : ledgerRegister.value,
);

function formatDrugCell(value?: string) {
  return value?.trim() ? value : '-';
}

function resetDrawerState() {
  traceData.value = null;
  ledgerProduct.value = null;
  ledgerRegister.value = null;
  reconciliationData.value = null;
  loadedTabs.value = new Set<string>();
  activeTab.value = 'timeline';
  ledgerScope.value = isPlatformAdmin.value ? 'all' : 'store';
  ledgerSubTab.value = 'product';
}

const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-[80%]',
  placement: 'right',
  showConfirmButton: false,
  showCancelButton: false,
  destroyOnClose: true,
  onOpenChange(isOpen) {
    if (isOpen) {
      ledgerScope.value = isPlatformAdmin.value ? 'all' : 'store';
      void loadTrace();
    } else {
      resetDrawerState();
    }
  },
});

const [PrescriptionDetailModal, PrescriptionDetailModalApi] = useVbenModal({
  connectedComponent: PrescriptionDetail,
});

const [OrderDetailModal, OrderDetailModalApi] = useVbenModal({
  connectedComponent: DetailModal,
});

async function loadTrace() {
  const data = drawerApi.getData<{
    order_id: number;
    order_no?: string;
    scene: 'product' | 'register';
  }>();
  if (!data?.order_id) {
    return;
  }

  loading.value = true;
  drawerApi.setState({ loading: true });
  try {
    traceData.value = await getOrderTraceApi({
      scene: data.scene,
      order_id: data.order_id,
    });
    if (traceData.value?.meta?.is_platform_admin === false) {
      ledgerScope.value = 'store';
    }
  } finally {
    loading.value = false;
    drawerApi.setState({ loading: false });
  }
}

async function loadLedgerDetail(force = false) {
  if (!force && loadedTabs.value.has(`ledger:${ledgerScope.value}`)) {
    return;
  }

  const productOrderId = traceData.value?.links?.product_order_id;
  const registerId = traceData.value?.links?.register_id;

  ledgerLoading.value = true;
  try {
    const requests: Promise<any>[] = [];
    if (productOrderId) {
      requests.push(
        getOrderLedgerDetailApi({
          order_id: productOrderId,
          order_type: 1,
          scope: ledgerScope.value,
        }).then((res) => {
          ledgerProduct.value = res;
        }),
      );
    } else {
      ledgerProduct.value = null;
    }

    if (registerId) {
      requests.push(
        getOrderLedgerDetailApi({
          order_id: registerId,
          order_type: 2,
          scope: ledgerScope.value,
        }).then((res) => {
          ledgerRegister.value = res;
        }),
      );
    } else {
      ledgerRegister.value = null;
    }

    await Promise.all(requests);
    loadedTabs.value.add(`ledger:${ledgerScope.value}`);
  } finally {
    ledgerLoading.value = false;
  }
}

async function loadReconciliationDetail() {
  if (loadedTabs.value.has('reconciliation')) {
    return;
  }

  const productOrderId = traceData.value?.links?.product_order_id;
  if (!productOrderId) {
    reconciliationData.value = {
      items: [],
      sum_sales_price: '0',
      sum_supply_price: '0',
      reconciliation_hint:
        traceData.value?.summary?.reconciliation_hint || '暂无关联商品订单',
    };
    loadedTabs.value.add('reconciliation');
    return;
  }

  reconciliationLoading.value = true;
  try {
    reconciliationData.value = await getOrderReconciliationDetailApi({
      product_order_id: productOrderId,
    });
    loadedTabs.value.add('reconciliation');
  } finally {
    reconciliationLoading.value = false;
  }
}

async function handleMainTabChange(key: string) {
  activeTab.value = key;
  if (key === 'ledger') {
    await loadLedgerDetail();
  } else if (key === 'reconciliation') {
    await loadReconciliationDetail();
  }
}

async function handleLedgerScopeChange(scope: LedgerScope) {
  ledgerScope.value = scope;
  loadedTabs.value.delete(`ledger:${scope}`);
  await loadLedgerDetail(true);
}

function openPrescriptionDetail() {
  const id = traceData.value?.links?.prescription_id;
  if (!id) {
    return;
  }
  PrescriptionDetailModalApi.setData({ values: id });
  PrescriptionDetailModalApi.open();
}

function openOrderDetail() {
  const id = traceData.value?.links?.product_order_id;
  if (!id) {
    return;
  }
  OrderDetailModalApi.setData({ id });
  OrderDetailModalApi.open();
}

function goAuditPrescription() {
  const id = traceData.value?.links?.prescription_id;
  if (!id) {
    return;
  }
  void router.push({
    path: '/pharmacist/review-prescription',
    query: { prescription_id: String(id) },
  });
}

function prescriptionStatusTag() {
  const summary = traceData.value?.summary;
  if (!summary?.prescription_id) {
    return null;
  }
  const auditNode = traceData.value?.timeline?.find(
    (n: Record<string, any>) =>
      n.key === 'prescription_audited' || n.key === 'prescription_rejected',
  );
  if (auditNode) {
    return auditNode.status;
  }
  return '待审核';
}

const reconciliationHint = computed(
  () =>
    reconciliationData.value?.reconciliation_hint ||
    traceData.value?.summary?.reconciliation_hint ||
    '',
);

watch(isPlatformAdmin, (val) => {
  if (!val) {
    ledgerScope.value = 'store';
  }
});
</script>

<template>
  <Drawer title="订单溯源">
    <Spin :spinning="loading">
      <div v-if="traceData" class="flex flex-col gap-4">
        <Descriptions bordered :column="2" size="small">
          <Descriptions.Item label="商品订单号">
            {{ traceData.summary?.product_order_no || '—' }}
          </Descriptions.Item>
          <Descriptions.Item label="挂号订单号">
            {{ traceData.summary?.register_order_no || '—' }}
          </Descriptions.Item>
          <Descriptions.Item label="处方号">
            {{ traceData.summary?.prescription_no || '—' }}
          </Descriptions.Item>
          <Descriptions.Item label="结算状态">
            {{ traceData.summary?.is_settled === 1 ? '已结算' : '未结算' }}
          </Descriptions.Item>
        </Descriptions>

        <Space wrap>
          <Button
            v-if="traceData.links?.prescription_id"
            size="small"
            type="primary"
            @click="openPrescriptionDetail"
          >
            处方详情
          </Button>
          <Button
            v-if="traceData.links?.product_order_id"
            size="small"
            @click="openOrderDetail"
          >
            订单详情
          </Button>
          <Button
            v-if="traceData.links?.prescription_id && prescriptionStatusTag() === '待审核'"
            size="small"
            danger
            @click="goAuditPrescription"
          >
            去审方
          </Button>
          <Tag v-else-if="prescriptionStatusTag()" color="green">
            审方：{{ prescriptionStatusTag() }}
          </Tag>
        </Space>

        <Tabs v-model:active-key="activeTab" @change="(key) => handleMainTabChange(String(key))">
          <Tabs.TabPane key="timeline" tab="溯源时间线">
            <Timeline v-if="traceData.timeline?.length">
              <Timeline.Item
                v-for="node in traceData.timeline"
                :key="node.key"
              >
                <div class="font-medium">{{ node.title }}</div>
                <div class="text-sm text-gray-500">{{ node.time }}</div>
                <div v-if="node.status" class="text-sm">
                  <Tag>{{ node.status }}</Tag>
                </div>
                <div v-if="node.extra" class="mt-1 text-sm text-gray-600">
                  {{ node.extra }}
                </div>
              </Timeline.Item>
            </Timeline>
            <div v-else class="py-6 text-center text-gray-500">暂无溯源记录</div>
          </Tabs.TabPane>

          <Tabs.TabPane key="ledger" tab="分账明细">
            <Spin :spinning="ledgerLoading">
              <Tabs
                v-if="isPlatformAdmin"
                v-model:active-key="ledgerScope"
                type="card"
                class="mb-3"
                @change="(key) => handleLedgerScopeChange(key as LedgerScope)"
              >
                <Tabs.TabPane key="all" tab="全部" />
                <Tabs.TabPane key="store" tab="门店" />
                <Tabs.TabPane key="platform" tab="平台" />
              </Tabs>

              <Tabs v-model:active-key="ledgerSubTab" type="card">
                <Tabs.TabPane key="product" tab="商品订单分账">
                  <div class="mb-2 text-sm">
                    合计分账：{{ ledgerProduct?.sum_money ?? '0' }}
                  </div>
                  <Table
                    :columns="ledgerColumns"
                    :data-source="ledgerProduct?.items ?? []"
                    :pagination="false"
                    row-key="id"
                    size="small"
                  >
                    <template #bodyCell="{ column, record, text }">
                      <template v-if="column.key === 'drug_image'">
                        <Image
                          v-if="record.drug_image"
                          :src="record.drug_image"
                          :width="48"
                          :height="48"
                          class="object-cover"
                        />
                        <span v-else>-</span>
                      </template>
                      <template
                        v-else-if="
                          column.key === 'drug_name' ||
                          column.key === 'drug_number' ||
                          column.key === 'specification'
                        "
                      >
                        {{ formatDrugCell(text) }}
                      </template>
                    </template>
                  </Table>
                  <div
                    v-if="!ledgerProduct?.items?.length && !ledgerLoading"
                    class="py-6 text-center text-gray-500"
                  >
                    暂无分账记录
                  </div>
                </Tabs.TabPane>
                <Tabs.TabPane key="register" tab="挂号订单分账">
                  <div class="mb-2 text-sm">
                    合计分账：{{ ledgerRegister?.sum_money ?? '0' }}
                  </div>
                  <Table
                    :columns="ledgerColumns"
                    :data-source="ledgerRegister?.items ?? []"
                    :pagination="false"
                    row-key="id"
                    size="small"
                  >
                    <template #bodyCell="{ column, record, text }">
                      <template v-if="column.key === 'drug_image'">
                        <Image
                          v-if="record.drug_image"
                          :src="record.drug_image"
                          :width="48"
                          :height="48"
                          class="object-cover"
                        />
                        <span v-else>-</span>
                      </template>
                      <template
                        v-else-if="
                          column.key === 'drug_name' ||
                          column.key === 'drug_number' ||
                          column.key === 'specification'
                        "
                      >
                        {{ formatDrugCell(text) }}
                      </template>
                    </template>
                  </Table>
                  <div
                    v-if="!ledgerRegister?.items?.length && !ledgerLoading"
                    class="py-6 text-center text-gray-500"
                  >
                    暂无分账记录
                  </div>
                </Tabs.TabPane>
              </Tabs>
            </Spin>
          </Tabs.TabPane>

          <Tabs.TabPane key="reconciliation" tab="对账明细">
            <Spin :spinning="reconciliationLoading">
              <ReconciliationDetailTable
                :items="reconciliationData?.items ?? []"
                :sum-sales-price="reconciliationData?.sum_sales_price"
                :sum-supply-price="reconciliationData?.sum_supply_price"
                :summary="reconciliationData?.summary"
                :hint="reconciliationHint"
              />
            </Spin>
          </Tabs.TabPane>
        </Tabs>
      </div>
    </Spin>
    <PrescriptionDetailModal />
    <OrderDetailModal />
  </Drawer>
</template>
