<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';
import { $t } from '#/locales';

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

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

// 提醒天数选项
const daysOptions = [
  { label: '15'+$t('alert.day'), value: 15 },
  { label: '7'+$t('alert.day'), value: 7 },
  { label: '2'+$t('alert.day'), value: 2 },
  { label: '1'+$t('alert.day'), value: 1 },
];

// 表单配置
const formSchema = computed(() => [
  {
    fieldName: 'id',
    component: 'Input',
    dependencies: {
      triggerFields: [''],
      show: () => false,
    },
  },
  {
    fieldName: 'users',
    label: $t('alert.Reminder'),
    rules: 'required',
    component: 'Select',
    componentProps: {
      placeholder: $t('alert.selectremind'),
      mode: 'multiple',
      allowClear: true,
      showSearch: true,
      filterOption: (input: string, option: any) => {
        return option?.label?.toLowerCase().includes(input.toLowerCase());
      },
      options: userOptions.value,
    },
  },
  {
    fieldName: 'days',
    label: $t('alert.reminderdays'),
    rules: 'required',
    component: 'Select',
    componentProps: {
      placeholder: $t('alert.selectday'),
      mode: 'multiple',
      allowClear: true,
      options: daysOptions,
    },
  },
  {
    fieldName: 'content',
    label: $t('alert.content'),
    rules: 'required',
    component: 'Textarea',
    componentProps: {
      placeholder: $t('alert.selectcontent'),
      rows: 4,
      showCount: true,
      maxlength: 500,
    },
  },
  {
    fieldName: 'status',
    label: $t('alert.status'),
    component: 'Switch',
    componentProps: {
      checkedChildren: $t('alert.enable'),
      unCheckedChildren: $t('alert.disable'),
      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);
    }
  } 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 :title="$t('alert.alerttitle')">
      <Form />
      <div class="mt-4 flex justify-end">
        <Space>
          <Button type="primary" @click="handleSubmit">{{$t('alert.save')}}</Button>
          <Button @click="handleReset">{{ $t('alert.reset') }}</Button>
        </Space>
      </div>
    </Card>
  </Page>
</template>
