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

import { Input, Modal, message } from 'ant-design-vue';

import UploadImage from '#/components/form/components/upload-image.vue';

export interface SettlementPreviewInfo {
  record_count: number;
  order_count?: number;
  amount: string;
}

const props = defineProps<{
  confirmFn: (data: Record<string, any>) => Promise<unknown>;
}>();

const emit = defineEmits<{
  success: [];
}>();

const visible = ref(false);
const confirmLoading = ref(false);
const modalTitle = ref('确认结算');
const preview = ref<SettlementPreviewInfo | null>(null);
const settleParams = ref<Record<string, any>>({});
const proofImages = ref<string[]>([]);
const remark = ref('');

function open(
  title: string,
  previewInfo: SettlementPreviewInfo,
  params: Record<string, any>,
) {
  modalTitle.value = title;
  preview.value = previewInfo;
  settleParams.value = { ...params };
  proofImages.value = [];
  remark.value = '';
  visible.value = true;
}

function close() {
  visible.value = false;
}

async function handleOk() {
  if (!proofImages.value.length) {
    message.warning('请上传至少 1 张结算凭证（如转账截图）');
    return Promise.reject();
  }
  confirmLoading.value = true;
  try {
    await props.confirmFn({
      ...settleParams.value,
      proof_images: proofImages.value,
      remark: remark.value.trim(),
    });
    message.success('结算成功');
    close();
    emit('success');
  } finally {
    confirmLoading.value = false;
  }
}

defineExpose({ open });
</script>

<template>
  <Modal
    v-model:open="visible"
    :confirm-loading="confirmLoading"
    :title="modalTitle"
    ok-text="确认结算"
    width="560"
    @ok="handleOk"
  >
    <div v-if="preview" class="mb-4 text-sm text-gray-600">
      <p>共 {{ preview.record_count }} 条明细</p>
      <p v-if="preview.order_count != null">{{ preview.order_count }} 个订单</p>
      <p class="font-medium text-gray-900">合计 ¥{{ preview.amount }}</p>
    </div>
    <div class="mb-4">
      <div class="mb-2 text-sm">
        <span class="text-red-500">*</span> 结算凭证（转账截图等，最多 9 张）
      </div>
      <UploadImage v-model="proofImages" :max-count="9" />
    </div>
    <div>
      <div class="mb-2 text-sm text-gray-600">备注（选填）</div>
      <Input.TextArea
        v-model:value="remark"
        :maxlength="255"
        :rows="2"
        placeholder="可填写转账说明等"
        show-count
      />
    </div>
  </Modal>
</template>
