<!-- 确认线下收款弹窗 -->
<template>
  <a-modal
    :visible="visible"
    title="确认线下收款"
    :width="520"
    :confirm-loading="loading"
    ok-text="确认收款"
    @update:visible="updateVisible"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-alert
      type="info"
      show-icon
      message="确认已收到该订单的线下付款（微信转账/银行汇款等），确认后订单将进入待发货状态。"
      style="margin-bottom: 16px"
    />

    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 18 }"
    >
      <!-- 订单号 -->
      <a-form-item label="订单号">
        <span style="color: #999">{{ form.orderNo || '-' }}</span>
      </a-form-item>

      <!-- 支付凭证 -->
      <a-form-item label="支付凭证" name="paymentVoucher">
        <a-upload
          list-type="picture-card"
          :max-count="1"
          :file-list="fileList"
          :custom-request="handleUpload"
          :before-upload="beforeUpload"
          @remove="handleRemove"
          @preview="handlePreview"
        >
          <div v-if="!fileList.length">
            <PlusOutlined />
            <div class="ant-upload-text">上传凭证</div>
          </div>
        </a-upload>
        <div class="voucher-tip">支持 jpg/png 图片，单张不超过 10MB</div>
      </a-form-item>

      <!-- 备注 -->
      <a-form-item label="备注" name="remarks">
        <a-textarea
          v-model:value="form.remarks"
          placeholder="可填写备注（如：微信转账已收到）"
          :rows="3"
          :maxlength="200"
          show-count
        />
      </a-form-item>
    </a-form>

    <!-- 图片预览 -->
    <a-modal
      :visible="previewVisible"
      :footer="null"
      title="凭证预览"
      @cancel="previewVisible = false"
    >
      <img :src="previewImage" alt="支付凭证" style="width: 100%" />
    </a-modal>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import type { UploadFile, UploadProps } from 'ant-design-vue';
  import { ShopOrder } from '@/api/shop/shopOrder/model';
  import { confirmOfflinePayment } from '@/api/shop/shopOrder';
  import { uploadOss } from '@/api/system/file';
  import { getUrl } from '@/utils/common';

  const useForm = Form.useForm;

  const props = defineProps<{
    visible: boolean;
    data?: ShopOrder | null;
  }>();

  const emit = defineEmits<{
    (e: 'update:visible', visible: boolean): void;
    (e: 'done'): void;
  }>();

  // 表单数据
  const form = reactive({
    orderId: undefined as number | undefined,
    orderNo: '' as string,
    paymentVoucher: '' as string,
    remarks: '' as string
  });

  // 表单验证规则
  const rules = {
    paymentVoucher: [
      { required: true, message: '请上传支付凭证' }
    ]
  };

  const formRef = ref();
  const { resetFields, validate } = useForm(form, rules);

  // 状态
  const loading = ref(false);
  const fileList = ref<UploadFile[]>([]);
  const previewVisible = ref(false);
  const previewImage = ref('');

  // 上传前校验
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    const isImage = ['image/jpeg', 'image/png', 'image/jpg'].includes(
      file.type
    );
    if (!isImage) {
      message.error('仅支持 jpg/png 格式图片');
      return false;
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('图片大小不能超过 10MB');
      return false;
    }
    return true;
  };

  // 自定义上传
  const handleUpload: UploadProps['customRequest'] = (options) => {
    const { file, onSuccess, onError } = options;
    uploadOss(file as File)
      .then((data) => {
        // 存储返回的 path（与项目 UploadCert 组件约定一致）
        form.paymentVoucher = data.path || '';
        fileList.value = [
          {
            uid: String(data.id || Date.now()),
            name: data.name || '支付凭证',
            status: 'done',
            url: data.url || getUrl(data.path || '')
          }
        ];
        onSuccess?.(data, file as any);
        // 触发表单校验清除错误
        formRef.value?.validateFields(['paymentVoucher']);
      })
      .catch((e) => {
        message.error(e.message || '上传失败');
        onError?.(e as any);
      });
  };

  // 删除凭证
  const handleRemove = () => {
    form.paymentVoucher = '';
    fileList.value = [];
    return true;
  };

  // 预览凭证
  const handlePreview = (file: UploadFile) => {
    previewImage.value = file.url || '';
    previewVisible.value = true;
  };

  // 更新弹窗显示状态
  const updateVisible = (visible: boolean) => {
    emit('update:visible', visible);
  };

  // 取消
  const handleCancel = () => {
    updateVisible(false);
  };

  // 提交确认收款
  const handleSubmit = async () => {
    try {
      await validate();
      if (!form.orderId) {
        message.error('订单信息缺失');
        return;
      }
      loading.value = true;
      await confirmOfflinePayment(
        form.orderId,
        form.remarks || undefined,
        form.paymentVoucher || undefined
      );
      message.success('确认收款成功，订单已进入待发货状态');
      emit('done');
      updateVisible(false);
    } catch (error: any) {
      if (error?.errorFields) return; // 表单校验失败，不弹错误
      message.error(error.message || '确认收款失败');
    } finally {
      loading.value = false;
    }
  };

  // 监听弹窗显示状态
  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        // 初始化表单
        form.orderId = props.data?.orderId;
        form.orderNo = props.data?.orderNo || '';
        form.paymentVoucher = '';
        form.remarks = '';
        fileList.value = [];
      } else {
        resetFields();
        fileList.value = [];
      }
    }
  );
</script>

<style scoped>
  .voucher-tip {
    color: #999;
    font-size: 12px;
    margin-top: 4px;
  }

  .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>
