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

import { useAccess } from '@vben/access';
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 { getSimpleUserList } from '#/api/system/user';
import { $t } from '#/locales';

const { hasAccessByCodes } = useAccess();

// 表单数据
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: '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);
      message.success('更新成功');
    }
  } catch {}
}

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

// 加载用户列表
async function loadUserList() {
  try {
    // 参考部门管理界面的做法，使用getUserPage接口
    userOptions.value = await getSimpleUserList();
  } 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"
            v-if="hasAccessByCodes(['license:alert:update'])"
          >
            {{ $t('alert.save') }}
          </Button>
          <Button @click="handleReset"> {{ $t('alert.reset') }} </Button>
        </Space>
      </div>
      <template #title>
        <span class="text-lg font-semibold">{{ $t('alert.alerttitle') }} </span>
        <a-tooltip title="每天零点发送邮件提醒">
          <span class="icon-[mdi--information-outline] text-gray-500"></span>
        </a-tooltip>
      </template>
    </Card>
  </Page>
</template>
