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

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

import { Button, Card, message, Space } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { getAlertPage, updateAlert } from '#/api/alert/alert';
import { getUserPage } from '#/api/system/user';

// 表单数据
const formData = ref({
  users: [],
  days: [],
  content: '',
  status: 1,
});

// 用户列表选项
const userOptions = ref([]);

// 提醒天数选项
const daysOptions = [
  { label: '15天', value: 15 },
  { label: '7天', value: 7 },
  { label: '2天', value: 2 },
  { label: '1天', value: 1 },
];

// 表单配置
const formSchema = computed(() => [
  {
    fieldName: 'id',
    component: 'Input',
    dependencies: {
      triggerFields: [''],
      show: () => false,
    },
  },
  {
    fieldName: 'users',
    label: '提醒人',
    rules: 'required',
    component: 'Select',
    componentProps: {
      placeholder: '请选择提醒人',
      mode: 'multiple',
      allowClear: true,
      showSearch: true,
      filterOption: (input: string, option: any) => {
        return option?.label?.toLowerCase().includes(input.toLowerCase());
      },
      options: userOptions.value,
    },
  },
  {
    fieldName: 'days',
    label: '提醒天数',
    rules: 'required',
    component: 'Select',
    componentProps: {
      placeholder: '请选择提醒天数',
      mode: 'multiple',
      allowClear: true,
      options: daysOptions,
    },
  },
  {
    fieldName: 'content',
    label: '提醒内容',
    rules: 'required',
    component: 'Textarea',
    componentProps: {
      placeholder: '请输入提醒内容',
      rows: 4,
      showCount: true,
      maxlength: 500,
    },
  },
  {
    fieldName: 'status',
    label: '启用状态',
    component: 'Switch',
    componentProps: {
      checkedChildren: '启用',
      unCheckedChildren: '禁用',
      checkedValue: 1,
      unCheckedValue: 2,
      style: { width: 'auto' },
    },
    defaultValue: 1,
  },
]);

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    labelWidth: 120,
  },
  layout: 'horizontal',
  schema: formSchema,
  showDefaultActions: false,
});

// 提交处理函数
async function handleSubmit() {
  const { valid } = await formApi.validate();

  if (!valid) {
    return;
  }

  try {
    const values = await formApi.getValues();

    // 添加必需的templateCode参数
    const submitData = {
      ...values,
      templateCode: 'expiration_reminder',
    };

    // 根据实际需要调用创建或更新接口
    if (values.id) {
      await updateAlert(submitData);
      message.success('更新成功');
    }
  } catch {}
}

// 重置处理函数
function handleReset() {
  loadUserList();
  loadAlertConfig();
}

// 加载用户列表
async function loadUserList() {
  try {
    // 参考部门管理界面的做法，使用getUserPage接口
    const { list } = await getUserPage({
      pageNo: 1,
      pageSize: 100, // 获取前100个用户
    });

    userOptions.value = list.map((user) => ({
      label: user.nickname || user.username,
      value: user.id,
    }));
  } catch {}
}

// 加载现有配置
async function loadAlertConfig() {
  try {
    // 使用getAlertPage接口获取告警配置
    const { list } = await getAlertPage({
      pageNo: 1,
      pageSize: 1,
    });

    // 如果有配置数据，则加载第一个配置
    if (list && list.length > 0) {
      const config = list[0];
      formData.value = config;
      await formApi.setValues(config);
    }
  } catch {}
}

onMounted(async () => {
  await loadUserList();
  await loadAlertConfig();
});
</script>

<template>
  <Page auto-content-height>
    <Card>
      <Form />
      <div class="mt-4 flex justify-end">
        <Space>
          <Button type="primary" @click="handleSubmit">保存</Button>
          <Button @click="handleReset">重置</Button>
        </Space>
      </div>
      <template #title>
        <span class="text-lg font-semibold">告警配置 </span>
        <a-tooltip title="每天零点发送邮件提醒">
          <span class="icon-[mdi--information-outline] text-gray-500"></span>
        </a-tooltip>
      </template>
    </Card>
  </Page>
</template>
