<template>
  <div class="page-container">
    <div class="page-header">
      <el-button type="primary" link @click="handleBack">
        <el-icon><ArrowLeft /></el-icon>返回
      </el-button>
      <span class="page-title">对账单详情</span>
    </div>

    <div v-loading="loading">
      <el-descriptions title="基本信息" :column="2" border class="margin-bottom">
        <el-descriptions-item label="对账编号">{{ form.statementOrderNo }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ form.customerName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="对账金额(元)">¥{{ form.amount != null ? Number(form.amount).toFixed(2) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="对账日期">{{ parseTime(form.statementDate, '{y}-{m}-{d}') || '-' }}</el-descriptions-item>
        <el-descriptions-item label="对账人">{{ form.statementSelf || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ form.statementSelfPhone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="对账状态">
          {{ getDictLabel(statement_status, form.statementStatus) }}
        </el-descriptions-item>
        <el-descriptions-item label="开票状态">
          {{ getDictLabel(invoice_issuance_status, form.isInvoiceStatus) }}
        </el-descriptions-item>
        <el-descriptions-item label="支付状态">
          {{ getDictLabel(payment_status, form.isPaymentStatus) }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ form.remark || '-' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 订单明细列表 -->
      <div v-if="form.detailList && form.detailList.length > 0">
        <el-divider content-position="left">对账明细</el-divider>
        <el-table :data="form.detailList" border style="width: 100%; margin-bottom: 20px">
          <el-table-column prop="orderNo" label="订单编号" min-width="150" align="center" />
          <el-table-column prop="deliverCode" label="发货单号" min-width="150" align="center" />
          <el-table-column prop="amount" label="金额(元)" min-width="100" align="center">
            <template #default="{ row }"> ¥{{ row.amount != null ? Number(row.amount).toFixed(2) : '-' }} </template>
          </el-table-column>
          <el-table-column prop="orderTime" label="订单时间" min-width="150" align="center">
            <template #default="{ row }">
              <span>{{ parseTime(row.orderTime) || '-' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 商品明细列表 -->
      <div v-if="form.productList && form.productList.length > 0">
        <el-divider content-position="left">商品清单</el-divider>
        <el-table :data="form.productList" border style="width: 100%">
          <el-table-column prop="itemName" label="商品名称" min-width="150" align="center" show-overflow-tooltip />
          <el-table-column prop="productNo" label="商品编号" min-width="120" align="center" />
          <el-table-column prop="unitPrice" label="单价" min-width="90" align="center" />
          <el-table-column prop="quantity" label="数量" min-width="90" align="center" />
          <el-table-column prop="unitName" label="单位" min-width="60" align="center" />
        </el-table>
      </div>

      <!-- 对账附件 -->
      <div v-if="form.annexAddress">
        <el-divider content-position="left">对账附件</el-divider>
        <el-table :data="attachmentList" border style="width: 100%">
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="name" label="文件名称" min-width="200" align="center" />
          <el-table-column label="操作" width="150" align="center">
            <template #default="{ row }">
              <el-button type="primary" link @click="handlePreview(row.url)">预览</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, getCurrentInstance, toRefs, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { getStatementInfo } from '@/api/pc/enterprise/statement';
import type { StatementOrder } from '@/api/pc/enterprise/statementTypes';

const { proxy } = getCurrentInstance() as any;
const { statement_status, invoice_issuance_status, payment_status } = toRefs<any>(
  proxy?.useDict('statement_status', 'invoice_issuance_status', 'payment_status')
);

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const form = ref<Partial<StatementOrder>>({});

// 附件列表
const attachmentList = computed(() => {
  if (!form.value.annexAddress) return [];
  const urls = form.value.annexAddress.split(',').filter(Boolean);
  return urls.map((url, index) => {
    const fileName = url.split('/').pop() || `附件${index + 1}`;
    return {
      name: decodeURIComponent(fileName),
      url: url.trim()
    };
  });
});

const getDictLabel = (dictOptions: any[], value: string) => {
  if (!dictOptions || !value) return value;
  const dict = dictOptions.find((item) => item.value === value);
  return dict ? dict.label : value;
};

// 预览附件
const handlePreview = (url: string) => {
  if (!url) {
    ElMessage.warning('文件地址不存在');
    return;
  }
  window.open(url, '_blank');
};

const handleBack = () => {
  router.back();
};

const loadDetail = async (id: number | string) => {
  loading.value = true;
  try {
    const res = await getStatementInfo(id);
    if (res.code === 200) {
      form.value = res.data || {};
    } else {
      ElMessage.error(res.msg || '获取详情失败');
    }
  } catch (error) {
    console.error('获取对账单详情失败:', error);
    ElMessage.error('获取对账单详情失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  const id = route.query.id;
  if (id) {
    loadDetail(id as string);
  } else {
    ElMessage.error('缺少对账单ID');
    handleBack();
  }
});
</script>

<style scoped lang="scss">
.page-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
  flex: 1;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 25px;

  .page-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
}

.margin-bottom {
  margin-bottom: 20px;
}
</style>
