<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';

import { defineEmits, defineExpose, reactive, ref } from 'vue';

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

import { ElMessage } from 'element-plus';

import { useCouponApi } from '#/api/coupon/coupon1';
import { getCoupon2AuditDetailApi } from '#/api/coupon/coupon2';
import { getCustomerDetailApi } from '#/api/user';
import UploadFile from '#/components/upload-file/index.vue';

const emit = defineEmits(['finish', 'cancel']);

const localCoupon2sid = ref('');
const couponDetailData = ref<any>(null);
const merchantDetailData = ref<any>(null);
const loading = ref(false);

const formRef = ref<FormInstance>();
const formData = reactive({
  serialNumber: '', // SN号
  invoiceEpFiles: [] as any[], // 发票文件列表
  invoiceIds: [] as { id: string; name?: string; url: string }[], // 发票文件ID列表
});

const submitLoading = ref(false);

const formRules: FormRules = {
  serialNumber: [
    { required: true, message: '请输入SN号', trigger: 'blur' },
    { min: 3, message: 'SN号至少3位', trigger: 'blur' },
  ],
  invoiceIds: [
    {
      required: true,
      validator: (_rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请上传发票信息'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

// 获取优惠券详情信息
async function fetchCouponDetail(coupon2sid: string) {
  if (!coupon2sid) {
    couponDetailData.value = null;
    merchantDetailData.value = null;
    return;
  }

  try {
    loading.value = true;
    const detailData = await getCoupon2AuditDetailApi({ coupon2sid });
    couponDetailData.value = detailData;

    // 获取经销商详情
    if (detailData && detailData.coupon2merchantid) {
      try {
        const merchantData = await getCustomerDetailApi({
          usersid: detailData.coupon2merchantid,
        });
        merchantDetailData.value = merchantData;
      } catch (error) {
        console.error('获取经销商详情失败:', error);
        merchantDetailData.value = null;
      }
    }
  } catch (error) {
    console.error('获取优惠券详情失败:', error);
    ElMessage.error('获取优惠券详情失败');
    couponDetailData.value = null;
    merchantDetailData.value = null;
  } finally {
    loading.value = false;
  }
}

// 下单确认
async function handleSubmit(): Promise<boolean> {
  if (!formRef.value) return false;

  try {
    await formRef.value.validate();

    if (!couponDetailData.value) {
      ElMessage.error('优惠券信息未加载完成，请稍后重试');
      return false;
    }

    submitLoading.value = true;

    // 获取发票文件ID字符串
    const invoiceFileIdsString = formData.invoiceIds
      .map((f) => f.id)
      .filter(Boolean)
      .join(',');

    // 构建下单接口参数
    const orderParams = {
      filesid: invoiceFileIdsString, // 发票id
      orderscouponid: couponDetailData.value.coupon2code, // 优惠码
      ordersphone: couponDetailData.value.usersphone || '', // 手机号
      ordersproductid: couponDetailData.value.coupon2productids || '', // 产品id
      ordersproductsn: formData.serialNumber, // SN号
      ordersuserid1: couponDetailData.value.coupon2merchantid || '', // 销售网点id
    };

    // 调用真实的下单接口
    await useCouponApi(orderParams);

    ElMessage.success('下单提交成功');

    return true;
  } catch (error) {
    ElMessage.error(error || '下单失败，请重试');
    return false;
  } finally {
    submitLoading.value = false;
  }
}

// 下单弹窗
const [Modal, modalApi] = useVbenModal({
  class: 'w-[700px]',
  title: '优惠券下单',
  showCancelButton: true,
  fullscreenButton: false,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  async onConfirm() {
    const success = await handleSubmit();
    if (success) {
      modalApi.close();
      emit('finish', { orderId: `ORDER_${Date.now()}` });
    }
  },
  onCancel() {
    modalApi.close();
    emit('cancel');
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const modalData = modalApi.getData() as {
        coupon2sid?: string;
      };
      localCoupon2sid.value = modalData?.coupon2sid || '';

      // 重置表单数据
      formData.serialNumber = '';
      formData.invoiceEpFiles = [];
      formData.invoiceIds = [];
      couponDetailData.value = null;
      merchantDetailData.value = null;

      formRef.value?.resetFields();
      submitLoading.value = false;

      // 获取优惠券详情
      if (localCoupon2sid.value) {
        await fetchCouponDetail(localCoupon2sid.value);
      }
    }
  },
});

/**
 * 打开优惠券下单弹窗
 */
function openOrderCouponModal(data?: { coupon2sid?: string }) {
  modalApi.setData(data || {});
  modalApi.open();
}

defineExpose({
  openOrderCouponModal,
});
</script>

<template>
  <Modal>
    <div v-loading="loading" class="p-4">
      <!-- 优惠券详情信息展示 -->
      <div
        v-if="couponDetailData"
        class="mb-4 rounded-md border border-blue-600 bg-blue-50 p-4"
      >
        <div class="mb-2">
          <span class="text-lg font-semibold text-blue-800">
            {{ couponDetailData.coupon2mc }}
          </span>
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div class="space-y-2">
            <div class="flex">
              <span class="w-24 text-sm font-medium text-gray-600">
                优惠券代码:
              </span>
              <span class="text-sm text-gray-800">
                {{ couponDetailData.coupon2code }}
              </span>
            </div>
            <div class="flex">
              <span class="w-24 text-sm font-medium text-gray-600">
                产品名称:
              </span>
              <span class="text-sm text-gray-800">
                {{ couponDetailData.productsname }}
              </span>
            </div>
            <div class="flex">
              <span class="w-24 text-sm font-medium text-gray-600">
                经销商:
              </span>
              <span class="text-sm text-gray-800">
                {{
                  merchantDetailData?.usersname ||
                  couponDetailData.coupon2merchantid ||
                  '未知'
                }}
              </span>
            </div>
          </div>
          <div class="space-y-2">
            <div class="flex">
              <span class="w-24 text-sm font-medium text-gray-600">
                购机者:
              </span>
              <span class="text-sm text-gray-800">
                {{ couponDetailData.usersname }}
              </span>
            </div>
            <div class="flex">
              <span class="w-24 text-sm font-medium text-gray-600">
                联系电话:
              </span>
              <span class="text-sm text-gray-800">
                {{ couponDetailData.usersphone }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <div
        class="rounded-md border border-gray-200 bg-white px-4 py-4 shadow-sm"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
        >
          <el-form-item label="优惠券ID">
            <el-input
              :value="localCoupon2sid"
              placeholder="优惠券ID"
              disabled
            />
          </el-form-item>

          <el-form-item label="SN号" prop="serialNumber">
            <el-input
              v-model="formData.serialNumber"
              placeholder="请输入产品SN号"
              clearable
            />
          </el-form-item>

          <el-form-item label="发票信息" prop="invoiceIds">
            <UploadFile
              v-model:file-list="formData.invoiceEpFiles"
              v-model:file-ids="formData.invoiceIds"
              attmodel="coupon_invoice"
              attpath="/coupon_invoice/"
              :limit="3"
              list-type="text"
              tips="支持上传jpg、png、pdf格式，最多3个文件"
              accept="image/*,.pdf"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
  </Modal>
</template>

<style lang="scss" scoped>
.el-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
