<script lang="ts" setup>
import type { Dayjs } from 'dayjs';

import { ref } from 'vue';

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

import { DatePicker, Form, message } from 'ant-design-vue';
import dayjs from 'dayjs';

import { generateDepartmentFinanceReportApi } from '#/views/finance/department-finance/api';

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

/** 默认统计区间：当月1日 ~ 今天（与对账单一致） */
const searchTime = ref<[Dayjs, Dayjs]>([dayjs().startOf('month'), dayjs()]);

const [Modal, modalApi] = useVbenModal({
  title: '手动生成部门财务报表',
  draggable: true,
  onConfirm: async () => {
    if (!searchTime.value?.[0] || !searchTime.value?.[1]) {
      message.warning('请选择统计开始和结束时间');
      return;
    }
    if (searchTime.value[0].isAfter(searchTime.value[1], 'day')) {
      message.warning('开始时间不能晚于结束时间');
      return;
    }
    modalApi.setState({ confirmLoading: true });
    try {
      const res = await generateDepartmentFinanceReportApi({
        search_time: [
          searchTime.value[0].format('YYYY-MM-DD'),
          searchTime.value[1].format('YYYY-MM-DD'),
        ],
      });
      message.success(`生成成功：${res.report_no ?? ''}`);
      emit('success');
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      searchTime.value = [dayjs().startOf('month'), dayjs()];
    }
  },
});

function popupContainerBody() {
  return document.body;
}

defineExpose({
  open() {
    modalApi.open();
  },
});
</script>

<template>
  <Modal>
    <Form layout="vertical">
      <Form.Item label="统计时间范围" required>
        <DatePicker.RangePicker
          v-model:value="searchTime"
          format="YYYY-MM-DD"
          class="w-full"
          :get-popup-container="popupContainerBody"
        />
      </Form.Item>
      <p class="text-xs text-muted-foreground">
        将按所选区间汇总各诊所开票相关金额（供货价、代煎费、运费等），结束日期不能晚于今天。
      </p>
    </Form>
  </Modal>
</template>
