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

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

import {
  ElCard,
  ElDescriptions,
  ElDescriptionsItem,
  ElImage,
  ElTag,
} from 'element-plus';

import { getDictListApi } from '#/api/dict';
import { getAttachmentListApi } from '#/api/file';
import { getOrdersDetailApi } from '#/api/orders';

const data = ref();
const orderDetail = ref<any>({});

const invoiceDataList = ref<any[]>([]);
const certificateDataList = ref<any[]>([]);
const buyerPhotoDataList = ref<any[]>([]);
const coupon2sid = ref(''); // 优惠券id

const [Modal, modalApi] = useVbenModal({
  class: 'w-2/3',
  onCancel() {
    modalApi.close();
  },
  onConfirm() {
    modalApi.close();
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      data.value = modalApi.getData();

      try {
        modalApi.setState({ loading: true });

        // 清空数据
        invoiceDataList.value = [];
        certificateDataList.value = [];
        buyerPhotoDataList.value = [];
        orderDetail.value = {};

        const filePrefix = await getFilePrefix();

        // 先获取订单详情
        await getOrderDetail(data.value.row.ordersid);

        // 并行获取附件信息
        await Promise.allSettled([
          getOrderInvoice(data.value.row.ordersid, filePrefix),
          getOrderCertificate(coupon2sid.value, filePrefix),
          getOrderBuyerPhoto(coupon2sid.value, filePrefix),
        ]);
      } catch (error) {
        console.error('加载订单详情失败:', error);
      }

      modalApi.setState({ loading: false });
    }
  },
});

// 获取订单详情
const getOrderDetail = async (ordersid: string) => {
  const detailData = await getOrdersDetailApi({
    ordersid,
  });

  orderDetail.value = detailData;
  coupon2sid.value = detailData.coupon2sid;
};

// 获取发票附件
const getOrderInvoice = async (ordersid: string, filePrefix: string) => {
  const invoiceData = await getAttachmentListApi({
    attlsh: ordersid,
    attmodel: 'coupon_invoice',
    pageindex: 1,
    rows: 10,
  });

  if (invoiceData.Data.length > 0) {
    invoiceData.Data.forEach((item: any) => {
      item.url = `${filePrefix}${item.attpath}${item.attname}.${item.atttype}`;
    });
  }

  invoiceDataList.value = invoiceData.Data;
};

// 获取购机者证件附件
const getOrderCertificate = async (coupon2sid: string, filePrefix: string) => {
  const certificateData = await getAttachmentListApi({
    attlsh: coupon2sid,
    attmodel: 'coupon_identity',
    pageindex: 1,
    rows: 10,
  });

  if (certificateData.Data.length > 0) {
    certificateData.Data.forEach((item: any) => {
      item.url = `${filePrefix}${item.attpath}${item.attname}.${item.atttype}`;
    });
  }

  certificateDataList.value = certificateData.Data;
};

// 获取购机者自拍附件
const getOrderBuyerPhoto = async (coupon2sid: string, filePrefix: string) => {
  const buyerPhotoData = await getAttachmentListApi({
    attlsh: coupon2sid,
    attmodel: 'coupon_buyer',
    pageindex: 1,
    rows: 10,
  });

  if (buyerPhotoData.Data.length > 0) {
    buyerPhotoData.Data.forEach((item: any) => {
      item.url = `${filePrefix}${item.attpath}${item.attname}.${item.atttype}`;
    });
  }

  buyerPhotoDataList.value = buyerPhotoData.Data;
};

// 获取文件前缀地址
const getFilePrefix = async () => {
  const filePrefixData = await getDictListApi({
    groupname: 'fileheadurl',
    pageindex: 1,
    rows: 999,
  });

  if (filePrefixData.Data.length > 0) {
    return filePrefixData.Data[0].substance;
  }

  return '';
};

// 订单状态映射
const getOrderStatusTag = (status: number) => {
  const statusMap = {
    0: { text: '待审核', type: 'info' },
    1: { text: '已支付', type: 'success' },
    2: { text: '已完成', type: 'warning' },
    3: { text: '审核不通过', type: 'danger' },
  } as const;
  return (
    statusMap[status as keyof typeof statusMap] || {
      text: '未知',
      type: 'info',
    }
  );
};

// 渲染附件
const renderAttachments = (attachments: any[], emptyText: string) => {
  if (attachments.length === 0) {
    return h('div', { class: 'text-gray-500 text-sm' }, emptyText);
  }

  return h(
    'div',
    { class: 'flex flex-wrap gap-3' },
    attachments.map((item) => {
      // 判断文件类型，根据atttype进行不同展示
      if (item.atttype === 'pdf') {
        // PDF文件显示为链接
        return h(
          'a',
          {
            href: item.url,
            target: '_blank',
            class:
              'inline-flex items-center px-3 py-2 text-sm font-medium text-blue-600 bg-blue-50 border border-blue-200 rounded-lg hover:bg-blue-100 hover:text-blue-700 transition-colors',
            title: item.attorginname || item.attname,
          },
          [
            h('i', { class: 'fas fa-file-pdf mr-2 text-red-500' }),
            item.attorginname || `${item.attname}.${item.atttype}`,
          ],
        );
      } else {
        // 图片文件使用ElImage展示
        const imageExtensions = new Set([
          'bmp',
          'gif',
          'jpeg',
          'jpg',
          'png',
          'webp',
        ]);
        return imageExtensions.has(item.atttype.toLowerCase())
          ? h(ElImage, {
              src: item.url,
              previewSrcList: attachments
                .filter((i) => imageExtensions.has(i.atttype.toLowerCase()))
                .map((i) => i.url),
              fit: 'cover',
              style: 'width: 100px; height: 100px;',
              class: 'border rounded',
              previewTeleported: true,
            })
          : // 其他文件类型显示为普通链接
            h(
              'a',
              {
                href: item.url,
                target: '_blank',
                class:
                  'inline-flex items-center px-3 py-2 text-sm font-medium text-gray-600 bg-gray-50 border border-gray-200 rounded-lg hover:bg-gray-100 hover:text-gray-700 transition-colors',
                title: item.attorginname || item.attname,
              },
              [
                h('i', { class: 'fas fa-file mr-2 text-gray-500' }),
                item.attorginname || `${item.attname}.${item.atttype}`,
              ],
            );
      }
    }),
  );
};
</script>

<template>
  <Modal title="订单详情" :show-cancel-button="false" confirm-text="关闭">
    <div class="space-y-6">
      <!-- 订单信息 -->
      <ElCard>
        <template #header>
          <div class="card-header">
            <span class="font-semibold">订单信息</span>
          </div>
        </template>
        <ElDescriptions :column="3" border label-width="220">
          <ElDescriptionsItem label="订单号">
            {{ orderDetail.ordersnumber }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="下单时间">
            {{ orderDetail.ordersorderdate }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="订单总金额">
            ¥{{ orderDetail.orderstotalprice }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="优惠金额">
            ¥{{ orderDetail.ordersyhprice }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="订单优惠后金额">
            ¥{{ orderDetail.ordersdiscountprice }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="订单状态">
            <ElTag
              :type="getOrderStatusTag(orderDetail.ordersorderstatus).type"
            >
              {{ getOrderStatusTag(orderDetail.ordersorderstatus).text }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="经销商">
            {{ orderDetail.jxsname }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="优惠券名称">
            {{ orderDetail.coupon2mc }}
          </ElDescriptionsItem>
        </ElDescriptions>
      </ElCard>

      <!-- 产品信息 -->
      <ElCard>
        <template #header>
          <div class="card-header">
            <span class="font-semibold">产品信息</span>
          </div>
        </template>
        <ElDescriptions :column="3" border label-width="220">
          <ElDescriptionsItem label="产品名称">
            {{ orderDetail.ordersproductname }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="产品型号">
            {{ orderDetail.productsmodel }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="产品SN">
            {{ orderDetail.ordersproductsn }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="生产企业">
            {{ orderDetail.scqyinfomc }}
          </ElDescriptionsItem>
        </ElDescriptions>
      </ElCard>

      <!-- 购机者信息 -->
      <ElCard>
        <template #header>
          <div class="card-header">
            <span class="font-semibold">购机者信息</span>
          </div>
        </template>
        <ElDescriptions :column="3" border label-width="220">
          <ElDescriptionsItem label="购机者姓名">
            {{ orderDetail.usersname }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="购机者电话">
            {{ orderDetail.usersphone }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="购机者地址" :span="2">
            {{ orderDetail.usersaddress || '-' }}
          </ElDescriptionsItem>
        </ElDescriptions>
      </ElCard>

      <!-- 附件列表 -->
      <ElCard>
        <template #header>
          <div class="card-header">
            <span class="font-semibold">附件列表</span>
          </div>
        </template>
        <div class="flex items-start space-x-10">
          <!-- 购机者照片 -->
          <div>
            <h4 class="mb-2 text-sm font-medium text-gray-700">购机者照片</h4>
            <div class="min-h-[60px] rounded-lg bg-gray-50 p-3">
              <component
                :is="renderAttachments(buyerPhotoDataList, '暂无购机者照片')"
              />
            </div>
          </div>

          <!-- 证件附件 -->
          <div>
            <h4 class="mb-2 text-sm font-medium text-gray-700">证件附件</h4>
            <div class="min-h-[60px] rounded-lg bg-gray-50 p-3">
              <component
                :is="renderAttachments(certificateDataList, '暂无证件附件')"
              />
            </div>
          </div>

          <!-- 发票附件 -->
          <div>
            <h4 class="mb-2 text-sm font-medium text-gray-700">发票附件</h4>
            <div class="min-h-[60px] rounded-lg bg-gray-50 p-3">
              <component
                :is="renderAttachments(invoiceDataList, '暂无发票附件')"
              />
            </div>
          </div>
        </div>
      </ElCard>
    </div>
  </Modal>
</template>

<style scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
