<script lang="ts" setup>
import type { ExtendedFormApi } from '@vben/common-ui';
import type { OrdersEntity } from '@vben/types';

import { computed, h, ref } from 'vue';

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

import { ElImage, ElMessage } from 'element-plus';

import { useVbenForm, z } from '#/adapter/form';
import { getDictListApi } from '#/api/dict';
import { getAttachmentListApi } from '#/api/file';
import { addOrdersApi, editOrdersApi, getOrdersDetailApi } from '#/api/orders';

const emit = defineEmits(['finish']);
const data = ref();
const formType = ref<'create' | 'detail' | 'edit'>('create');

const titleMap = {
  create: '新增订单',
  detail: '订单详情',
  edit: '编辑订单',
} as const;

const getTitle = computed(() => titleMap[formType.value]);

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

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 140,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1 lg:grid-cols-2',
  schema: [
    // { title: '订单号', field: 'ordersnumber' },
    // { title: '订单关联用户id', field: 'ordersuserid' },
    // { title: '订单关联产品id', field: 'ordersproductid' },
    // { title: '产品名称', field: 'ordersproductname' },
    // { title: '产品sn', field: 'ordersproductsn' },
    // { title: '订单总金额', field: 'orderstotalprice' },
    // { title: '订单优惠后金额', field: 'ordersdiscountprice' },
    // { title: '优惠金额', field: 'ordersyhprice' },
    // { title: '优惠卷id', field: 'orderscouponid' },
    // { title: '订单状态', field: 'ordersorderstatus' },
    {
      component: 'Input',
      fieldName: 'ordersnumber',
      label: '订单号',
      componentProps: {
        placeholder: '请输入订单号',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入订单号' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersuserid',
      label: '订单关联用户id',
      componentProps: {
        placeholder: '请输入订单关联用户id',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入订单关联用户id' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersproductid',
      label: '订单关联产品id',
      componentProps: {
        placeholder: '请输入订单关联产品id',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入订单关联产品id' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersproductname',
      label: '产品名称',
      componentProps: {
        placeholder: '请输入产品名称',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入产品名称' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersproductsn',
      label: '产品sn',
      componentProps: {
        placeholder: '请输入产品sn',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入产品sn' }),
    },
    {
      component: 'Input',
      fieldName: 'productsmodel',
      label: '产品型号',
      componentProps: {
        placeholder: '请输入产品型号',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入产品型号' }),
    },
    {
      component: 'Input',
      fieldName: 'jxsname',
      label: '经销商',
      componentProps: {
        placeholder: '请输入经销商',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入经销商' }),
    },
    {
      component: 'Input',
      fieldName: 'orderstotalprice',
      label: '订单总金额',
      componentProps: {
        placeholder: '请输入订单总金额',
        allowClear: true,
      },
      rules: z.number().min(0, { message: '请输入有效的订单总金额' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersdiscountprice',
      label: '订单优惠后金额',
      componentProps: {
        placeholder: '请输入订单优惠后金额',
        allowClear: true,
      },
      rules: z.number().min(0, { message: '请输入有效的订单优惠后金额' }),
    },
    {
      component: 'Input',
      fieldName: 'ordersyhprice',
      label: '优惠金额',
      componentProps: {
        placeholder: '请输入优惠金额',
        allowClear: true,
      },
      rules: z.number().min(0, { message: '请输入有效的优惠金额' }),
    },
    {
      component: 'Input',
      fieldName: 'orderscouponid',
      label: '优惠券id',
      componentProps: {
        placeholder: '请输入优惠券id',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入优惠券id' }),
    },
    {
      component: 'Select',
      fieldName: 'ordersorderstatus',
      label: '订单状态',
      componentProps: {
        placeholder: '请选择订单状态',
        options: [
          { label: '待审核', value: 0 },
          { label: '已支付', value: 1 },
          { label: '已完成', value: 2 },
        ],
      },
      rules: z.number().min(0, { message: '请选择订单状态' }),
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  class: 'w-7/12',
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    // 校验输入的数据
    const validate = await baseFormApi.validate();
    if (!validate.valid) {
      return;
    }

    try {
      // 调用新增或编辑接口
      const apiMap = {
        create: () => addOrdersApi(validate.values as OrdersEntity),
        edit: () =>
          editOrdersApi({
            ...validate.values,
            'ordersid.value': data.value.row.ordersid,
          } as any),
      };

      if (formType.value === 'detail') {
        modalApi.close();
        return;
      }

      await apiMap[formType.value]();
      ElMessage.success('操作成功');

      emit('finish');
      modalApi.close();
    } catch {}
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      data.value = modalApi.getData();

      formType.value = data.value.formType;

      baseFormApi.setState({
        commonConfig: { disabled: formType.value === 'detail' },
      });

      if (data.value.formType === 'create') {
        return;
      }

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

        invoiceDataList.value = [];
        certificateDataList.value = [];
        buyerPhotoDataList.value = [];

        // 去掉schema中invoiceAttachments和certificateAttachments字段，避免页面不更新
        baseFormApi.setState({
          schema: baseFormApi
            .getState()
            ?.schema?.filter(
              (item) =>
                item.fieldName !== 'invoiceAttachments' &&
                item.fieldName !== 'certificateAttachments' &&
                item.fieldName !== 'buyerPhotoAttachments',
            ),
        });

        const filePrefix = await getFilePrefix();

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

        // 订单详情获取完成后，再并行执行剩余3个函数
        const results = await Promise.allSettled([
          getOrderInvoice(data.value.row.ordersid, filePrefix),
          getOrderCertificate(coupon2sid.value, filePrefix),
          getOrderBuyerPhoto(coupon2sid.value, filePrefix),
        ]);

        // 更新schema
        const schema = baseFormApi.getState()?.schema ?? [];

        // 检查schema中是否已存在invoiceAttachments字段
        const hasInvoiceAttachments = schema.some(
          (item) => item.fieldName === 'invoiceAttachments',
        );

        // 检查schema中是否已存在certificateAttachments字段
        const hasCertificateAttachments = schema.some(
          (item) => item.fieldName === 'certificateAttachments',
        );

        // 检查schema中是否已存在buyerPhotoAttachments字段
        const hasBuyerPhotoAttachments = schema.some(
          (item) => item.fieldName === 'buyerPhotoAttachments',
        );

        // 首先添加购机者照片
        // 如果不存在，则添加购买人自拍附件字段
        if (!hasBuyerPhotoAttachments && buyerPhotoDataList.value.length > 0) {
          baseFormApi.setState({
            schema: [
              ...(baseFormApi.getState()?.schema ?? []),
              {
                component: h(
                  'div',
                  { class: 'grid-cols-1 lg:grid-cols-2 flex flex-wrap gap-3' },
                  buyerPhotoDataList.value.map((item) => {
                    return h(ElImage, {
                      src: item.url,
                      previewSrcList: buyerPhotoDataList.value.map(
                        (i) => i.url,
                      ),
                      fit: 'cover',
                      style: 'width: 100px; height: 100px;',
                      class: 'border rounded',
                      previewTeleported: true,
                    });
                  }),
                ),
                fieldName: 'buyerPhotoAttachments',
                label: '购机者照片',
                // formItemClass: 'lg:col-span-2',
              },
            ],
          });
        } else {
          baseFormApi.setState({
            schema: [
              ...(baseFormApi.getState()?.schema ?? []),
              {
                component: h(
                  'div',
                  {
                    class:
                      'grid-cols-1 lg:grid-cols-2 flex flex-wrap gap-3 text-sm',
                  },
                  '暂无',
                ),
                fieldName: 'buyerPhotoAttachments',
                label: '购机者照片',
                // formItemClass: 'lg:col-span-2',
              },
            ],
          });
        }

        // 然后添加证件附件
        // 如果不存在，则添加证件附件字段
        if (
          !hasCertificateAttachments &&
          certificateDataList.value.length > 0
        ) {
          baseFormApi.setState({
            schema: [
              ...(baseFormApi.getState()?.schema ?? []),
              {
                component: h(
                  'div',
                  { class: 'grid-cols-1 lg:grid-cols-2 flex flex-wrap gap-3' },
                  certificateDataList.value.map((item) => {
                    return h(ElImage, {
                      src: item.url,
                      previewSrcList: certificateDataList.value.map(
                        (i) => i.url,
                      ),
                      fit: 'cover',
                      style: 'width: 100px; height: 100px;',
                      class: 'border rounded',
                      previewTeleported: true,
                    });
                  }),
                ),
                fieldName: 'certificateAttachments',
                label: '证件附件',
                // formItemClass: 'lg:col-span-2',
              },
            ],
          });
        } else {
          baseFormApi.setState({
            schema: [
              ...(baseFormApi.getState()?.schema ?? []),
              {
                component: h(
                  'div',
                  {
                    class:
                      'grid-cols-1 lg:grid-cols-2 flex flex-wrap gap-3 text-sm',
                  },
                  '暂无',
                ),
                fieldName: 'certificateAttachments',
                label: '证件附件',
                // formItemClass: 'lg:col-span-2',
              },
            ],
          });
        }

        // 最后添加发票附件展示
        // 如果不存在，则添加发票附件字段
        if (!hasInvoiceAttachments) {
          baseFormApi.setState({
            schema: [
              ...(baseFormApi.getState()?.schema ?? []),
              {
                component: h(
                  'div',
                  { class: 'flex flex-wrap gap-3' },
                  invoiceDataList.value.length > 0
                    ? invoiceDataList.value.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: invoiceDataList.value
                                  .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}`,
                                ],
                              );
                        }
                      })
                    : [
                        h(
                          'span',
                          {
                            class: 'text-sm text-gray-500',
                          },
                          '暂无发票附件',
                        ),
                      ],
                ),
                fieldName: 'invoiceAttachments',
                label: '发票附件',
                // formItemClass: 'lg:col-span-2',
              },
            ],
          });
        }

        // 可以选择处理失败的请求
        results.forEach((result, index) => {
          if (result.status === 'rejected') {
            console.warn(`请求 ${index} 失败:`, result.reason);
          }
        });
      } catch (error) {
        console.error(error);
      }

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

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

  formApi.setValues(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 '';
};
</script>

<template>
  <Modal :title="getTitle">
    <BaseForm />
  </Modal>
</template>
