<script lang="ts" setup>
import type { EnergyHydrogenDetailApi } from '#/api/energy/hydrogen-detail';

import { computed, ref } from 'vue';

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

import { auditHydrogenDetail } from '#/api/energy/hydrogen-detail';

const emit = defineEmits(['success']);

const visible = ref(false);
const loading = ref(false);
const records = ref<EnergyHydrogenDetailApi.Detail[]>([]);
const approved = ref(true);
const remark = ref('');

const isBatch = computed(() => records.value.length > 1);
const totalAmount = computed(() =>
  records.value.reduce((sum, r) => sum + (r.customerAmount || 0), 0),
);

function open(data: EnergyHydrogenDetailApi.Detail[]) {
  records.value = data;
  approved.value = true;
  remark.value = '';
  visible.value = true;
}

async function handleConfirm() {
  loading.value = true;
  try {
    let successCount = 0;
    for (const record of records.value) {
      await auditHydrogenDetail(
        record.id!,
        approved.value,
        remark.value || undefined,
      );
      successCount++;
    }
    message.success(`审核完成，共 ${successCount} 条`);
    visible.value = false;
    emit('success');
  } catch (e: any) {
    message.error(e.message || '审核失败');
  } finally {
    loading.value = false;
  }
}

defineExpose({ open });
</script>

<template>
  <Modal
    v-model:open="visible"
    title="审核"
    :confirm-loading="loading"
    @ok="handleConfirm"
    @cancel="visible = false"
  >
    <!-- Single record summary -->
    <Descriptions
      v-if="!isBatch && records[0]"
      :column="2"
      bordered
      size="small"
      class="mb-4"
    >
      <Descriptions.Item label="车牌号">{{
        records[0].plateNumber
      }}</Descriptions.Item>
      <Descriptions.Item label="加氢站">{{
        records[0].stationName
      }}</Descriptions.Item>
      <Descriptions.Item label="加氢日期">{{
        records[0].hydrogenDate
      }}</Descriptions.Item>
      <Descriptions.Item label="对客金额"
        >¥{{ records[0].customerAmount }}</Descriptions.Item
      >
    </Descriptions>

    <!-- Batch summary -->
    <div v-if="isBatch" class="mb-4 rounded bg-gray-50 p-4">
      <p>已选中 <strong>{{ records.length }}</strong> 条记录</p>
      <p>合计金额：<strong>¥{{ totalAmount.toFixed(2) }}</strong></p>
    </div>

    <div class="mb-4">
      <label class="mb-2 block font-medium">审核结果</label>
      <Radio.Group v-model:value="approved">
        <Radio :value="true">通过</Radio>
        <Radio v-if="!isBatch" :value="false">驳回</Radio>
      </Radio.Group>
    </div>

    <div>
      <label class="mb-2 block font-medium">审核备注</label>
      <Input.TextArea
        v-model:value="remark"
        :rows="3"
        placeholder="请输入审核备注（选填）"
      />
    </div>
  </Modal>
</template>
