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

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

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

import {
  getDepartmentFinanceConfigApi,
  saveDepartmentFinanceConfigApi,
} from '#/views/finance/department-finance/api';

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

const generateDay = ref(14);
const generateHour = ref(2);

const [Modal, modalApi] = useVbenModal({
  title: '部门财务报表生成配置',
  draggable: true,
  onConfirm: async () => {
    modalApi.setState({ confirmLoading: true });
    try {
      await saveDepartmentFinanceConfigApi({
        generate_day: generateDay.value,
        generate_hour: generateHour.value,
      });
      message.success('配置已保存');
      emit('saved');
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      loadConfig();
    }
  },
});

/** 读取当前生成配置 */
async function loadConfig() {
  const res = await getDepartmentFinanceConfigApi();
  generateDay.value = Number(res.generate_day ?? 14);
  generateHour.value = Number(res.generate_hour ?? 2);
}

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

<template>
  <Modal>
    <Form layout="vertical">
      <Form.Item label="每月生成日（1-28）">
        <InputNumber v-model:value="generateDay" :min="1" :max="28" class="w-full" />
      </Form.Item>
      <Form.Item label="生成小时（0-23）">
        <InputNumber v-model:value="generateHour" :min="0" :max="23" class="w-full" />
      </Form.Item>
    </Form>
  </Modal>
</template>
