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

import { Alert, DatePicker, InputNumber, message, Modal } from 'ant-design-vue';
import dayjs from 'dayjs';

import {
  batchGenerateByPeriod,
  generateBill,
} from '#/api/energy/bill';
import type { EnergyBillApi } from '#/api/energy/bill';

const emit = defineEmits(['success']);
const visible = ref(false);
const loading = ref(false);
const mode = ref<'batch' | 'single'>('single');

// Single mode fields
const customerId = ref<number>();
const contractId = ref<number>();
const stationId = ref<number>();
const billPeriod = ref<any>();

function open(m: 'batch' | 'single' = 'single') {
  mode.value = m;
  customerId.value = undefined;
  contractId.value = undefined;
  stationId.value = undefined;
  billPeriod.value = undefined;
  visible.value = true;
}

async function handleConfirm() {
  if (!billPeriod.value) {
    message.warning('请选择账单周期');
    return;
  }
  loading.value = true;
  try {
    const periodStr = dayjs(billPeriod.value).format('YYYY-MM');
    if (mode.value === 'single') {
      if (!customerId.value || !stationId.value) {
        message.warning('请填写完整信息');
        loading.value = false;
        return;
      }
      const data: EnergyBillApi.GenerateReq = {
        customerId: customerId.value,
        contractId: contractId.value!,
        stationId: stationId.value,
        billPeriodStart: dayjs(billPeriod.value).startOf('month').format('YYYY-MM-DD'),
        billPeriodEnd: dayjs(billPeriod.value).endOf('month').format('YYYY-MM-DD'),
      };
      await generateBill(data);
      message.success('账单生成成功');
    } else {
      const result = await batchGenerateByPeriod(periodStr);
      const generated = result.generatedCount ?? 0;
      const skipped = result.skippedCount ?? 0;
      message.success(`批量生成完成：成功 ${generated} 条，跳过 ${skipped} 条`);
    }
    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="mode === 'single' ? '生成账单' : '批量生成账单'"
    :confirm-loading="loading"
    @ok="handleConfirm"
    @cancel="visible = false"
  >
    <template v-if="mode === 'single'">
      <div class="mb-4">
        <label class="mb-1 block font-medium">
          客户 <span class="text-red-500">*</span>
        </label>
        <InputNumber
          v-model:value="customerId"
          placeholder="请输入客户ID"
          class="w-full"
        />
      </div>
      <div class="mb-4">
        <label class="mb-1 block font-medium">合同</label>
        <InputNumber
          v-model:value="contractId"
          placeholder="请输入合同ID"
          class="w-full"
        />
      </div>
      <div class="mb-4">
        <label class="mb-1 block font-medium">
          加氢站 <span class="text-red-500">*</span>
        </label>
        <InputNumber
          v-model:value="stationId"
          placeholder="请输入站点ID"
          class="w-full"
        />
      </div>
    </template>
    <div class="mb-4">
      <label class="mb-1 block font-medium">
        账单周期 <span class="text-red-500">*</span>
      </label>
      <DatePicker
        v-model:value="billPeriod"
        picker="month"
        class="w-full"
        placeholder="选择月份"
      />
    </div>
    <Alert
      v-if="mode === 'single'"
      type="info"
      show-icon
      message="系统将自动汇总该客户+合同+站点在所选周期内已审核且未出账的加氢明细，生成草稿账单。"
    />
    <Alert
      v-if="mode === 'batch'"
      type="info"
      show-icon
      message="系统将自动为所有有未出账明细的客户+合同+站点组合生成当月草稿账单。"
    />
  </Modal>
</template>
