<template>
  <Page>
    <VbenCard title="邮件设置">
      <template #extra>
        <Icon icon="lucide:mail" class="text-lg" />
      </template>
      
      <VbenTabs v-model:active-key="activeTab" type="card">
        <!-- SMTP配置 -->
        <VbenTabPane key="smtp" tab="SMTP配置">
          <VbenForm @submit="handleSubmitSmtp">
            <template #default="{ form }">
              <VbenFormItem name="smtp_host" label="SMTP服务器">
                <Input v-model:value="form.smtp_host" placeholder="请输入SMTP服务器地址" />
              </VbenFormItem>
              
              <VbenFormItem name="smtp_port" label="端口">
                <InputNumber 
                  v-model:value="form.smtp_port" 
                  :min="1" 
                  :max="65535" 
                  placeholder="请输入端口号" 
                />
              </VbenFormItem>
              
              <VbenFormItem name="smtp_username" label="用户名">
                <Input v-model:value="form.smtp_username" placeholder="请输入邮箱用户名" />
              </VbenFormItem>
              
              <VbenFormItem name="smtp_password" label="密码">
                <Input 
                  v-model:value="form.smtp_password" 
                  type="password" 
                  placeholder="请输入邮箱密码或授权码" 
                  show-password 
                />
              </VbenFormItem>
              
              <VbenFormItem name="smtp_from_email" label="发件人邮箱">
                <Input v-model:value="form.smtp_from_email" placeholder="请输入发件人邮箱" />
              </VbenFormItem>
              
              <VbenFormItem name="smtp_from_name" label="发件人名称">
                <Input v-model:value="form.smtp_from_name" placeholder="请输入发件人名称" />
              </VbenFormItem>
              
              <VbenFormItem name="smtp_encryption" label="加密方式">
                <Select v-model:value="form.smtp_encryption" placeholder="请选择加密方式">
                  <template #default>
                    <SelectOption value="">无</SelectOption>
                    <SelectOption value="ssl">SSL</SelectOption>
                    <SelectOption value="tls">TLS</SelectOption>
                  </template>
                </Select>
              </VbenFormItem>
              
              <VbenFormItem name="smtp_enabled" label="启用状态">
                <Switch v-model:checked="form.smtp_enabled" />
              </VbenFormItem>
            </template>
            
            <template #submit>
              <Space>
                <PrimaryButton html-type="submit" :loading="submitLoading">
                  <Icon icon="lucide:check" class="mr-1" />
                  保存设置
                </PrimaryButton>
                <DefaultButton @click="handleTestEmail" :loading="testLoading">
                  <Icon icon="lucide:send" class="mr-1" />
                  发送测试邮件
                </DefaultButton>
                <DefaultButton @click="handleResetSmtp">
                  <Icon icon="lucide:rotate-ccw" class="mr-1" />
                  重置
                </DefaultButton>
              </Space>
            </template>
          </VbenForm>
        </VbenTabPane>
        
        <!-- 邮件模板 -->
        <VbenTabPane key="template" tab="邮件模板">
          <VbenTabs v-model:active-key="templateTab" type="line">
            <!-- 注册验证模板 -->
            <VbenTabPane key="register" tab="注册验证">
              <VbenForm @submit="handleSubmitTemplate">
                <template #default="{ form }">
                  <VbenFormItem name="register_subject" label="邮件标题">
                    <Input 
                      v-model:value="form.register_subject" 
                      placeholder="请输入注册验证邮件标题" 
                    />
                  </VbenFormItem>
                  
                  <VbenFormItem name="register_content" label="邮件内容">
                    <Input 
                      v-model:value="form.register_content" 
                      type="textarea" 
                      :rows="6" 
                      placeholder="请输入注册验证邮件内容，可使用变量：{username}、{code}、{expire}" 
                    />
                  </VbenFormItem>
                  
                  <VbenFormItem name="register_enabled" label="启用状态">
                    <Switch v-model:checked="form.register_enabled" />
                  </VbenFormItem>
                </template>
                
                <template #submit>
                  <Space>
                    <PrimaryButton html-type="submit" :loading="submitLoading">
                      <Icon icon="lucide:check" class="mr-1" />
                      保存模板
                    </PrimaryButton>
                    <DefaultButton @click="handlePreviewTemplate('register')">
                      <Icon icon="lucide:eye" class="mr-1" />
                      预览模板
                    </DefaultButton>
                  </Space>
                </template>
              </VbenForm>
            </VbenTabPane>
            
            <!-- 找回密码模板 -->
            <VbenTabPane key="reset" tab="找回密码">
              <VbenForm @submit="handleSubmitTemplate">
                <template #default="{ form }">
                  <VbenFormItem name="reset_subject" label="邮件标题">
                    <Input 
                      v-model:value="form.reset_subject" 
                      placeholder="请输入找回密码邮件标题" 
                    />
                  </VbenFormItem>
                  
                  <VbenFormItem name="reset_content" label="邮件内容">
                    <Input 
                      v-model:value="form.reset_content" 
                      type="textarea" 
                      :rows="6" 
                      placeholder="请输入找回密码邮件内容，可使用变量：{username}、{code}、{expire}" 
                    />
                  </VbenFormItem>
                  
                  <VbenFormItem name="reset_enabled" label="启用状态">
                    <Switch v-model:checked="form.reset_enabled" />
                  </VbenFormItem>
                </template>
                
                <template #submit>
                  <Space>
                    <PrimaryButton html-type="submit" :loading="submitLoading">
                      <Icon icon="lucide:check" class="mr-1" />
                      保存模板
                    </PrimaryButton>
                    <DefaultButton @click="handlePreviewTemplate('reset')">
                      <Icon icon="lucide:eye" class="mr-1" />
                      预览模板
                    </DefaultButton>
                  </Space>
                </template>
              </VbenForm>
            </VbenTabPane>
            
            <!-- 通知邮件模板 -->
            <VbenTabPane key="notify" tab="通知邮件">
              <VbenForm @submit="handleSubmitTemplate">
                <template #default="{ form }">
                  <VbenFormItem name="notify_subject" label="邮件标题">
                    <Input 
                      v-model:value="form.notify_subject" 
                      placeholder="请输入通知邮件标题" 
                    />
                  </VbenFormItem>
                  
                  <VbenFormItem name="notify_content" label="邮件内容">
                    <Input 
                      v-model:value="form.notify_content" 
                      type="textarea" 
                      :rows="6" 
                      placeholder="请输入通知邮件内容，可使用变量：{username}、{title}、{content}" 
                    />
                  </VbenFormItem>
                  
                  <VbenFormItem name="notify_enabled" label="启用状态">
                    <Switch v-model:checked="form.notify_enabled" />
                  </VbenFormItem>
                </template>
                
                <template #submit>
                  <Space>
                    <PrimaryButton html-type="submit" :loading="submitLoading">
                      <Icon icon="lucide:check" class="mr-1" />
                      保存模板
                    </PrimaryButton>
                    <DefaultButton @click="handlePreviewTemplate('notify')">
                      <Icon icon="lucide:eye" class="mr-1" />
                      预览模板
                    </DefaultButton>
                  </Space>
                </template>
              </VbenForm>
            </VbenTabPane>
          </VbenTabs>
        </VbenTabPane>
      </VbenTabs>
    </VbenCard>
    
    <!-- 测试邮件对话框 -->
    <VbenModal v-model:open="testDialogVisible" title="发送测试邮件" width="500px">
      <VbenForm @submit="handleSendTest">
        <template #default="{ form }">
          <VbenFormItem name="test_email" label="收件人邮箱">
            <Input 
              v-model:value="form.test_email" 
              placeholder="请输入测试邮箱地址" 
            />
          </VbenFormItem>
          
          <VbenFormItem name="test_type" label="邮件类型">
            <Select v-model:value="form.test_type" placeholder="请选择邮件类型">
              <template #default>
                <SelectOption value="register">注册验证</SelectOption>
                <SelectOption value="reset">找回密码</SelectOption>
                <SelectOption value="notify">通知邮件</SelectOption>
              </template>
            </Select>
          </VbenFormItem>
        </template>
        
        <template #submit>
          <Space>
            <PrimaryButton html-type="submit" :loading="sendTestLoading">
              <Icon icon="lucide:send" class="mr-1" />
              发送
            </PrimaryButton>
            <DefaultButton @click="testDialogVisible = false">
              取消
            </DefaultButton>
          </Space>
        </template>
      </VbenForm>
    </VbenModal>
    
    <!-- 模板预览对话框 -->
    <VbenModal v-model:open="previewDialogVisible" title="模板预览" width="600px">
      <div class="template-preview">
        <div class="preview-item">
          <label>邮件标题：</label>
          <div class="preview-content">{{ previewData.subject }}</div>
        </div>
        <div class="preview-item">
          <label>邮件内容：</label>
          <div class="preview-content" v-html="previewData.content"></div>
        </div>
      </div>
      
      <template #footer>
        <DefaultButton @click="previewDialogVisible = false">
          关闭
        </DefaultButton>
      </template>
    </VbenModal>
  </Page>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Icon } from '@iconify/vue';
import { 
  Page, 
  VbenCard, 
  VbenTabs, 
  VbenTabPane,
  VbenModal
} from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import type { VbenFormSchema } from '#/adapter/form';
import { 
  getEmailConfigApi, 
  updateEmailConfigApi,
  testEmailApi,
  previewEmailTemplateApi
} from '#/api/common/email';

// 响应式数据
const activeTab = ref('smtp');
const templateTab = ref('register');
const submitLoading = ref(false);
const testLoading = ref(false);
const sendTestLoading = ref(false);
const testDialogVisible = ref(false);
const previewDialogVisible = ref(false);

// 预览数据
const previewData = reactive({
  subject: '',
  content: '',
});

// SMTP配置表单配置
const smtpFormSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'smtp_host',
    label: 'SMTP服务器',
    rules: 'required',
    componentProps: {
      placeholder: '请输入SMTP服务器地址',
    },
  },
  {
    component: 'InputNumber',
    fieldName: 'smtp_port',
    label: '端口',
    rules: 'required',
    componentProps: {
      min: 1,
      max: 65535,
      placeholder: '请输入端口号',
    },
  },
  {
    component: 'Input',
    fieldName: 'smtp_username',
    label: '用户名',
    rules: 'required',
    componentProps: {
      placeholder: '请输入邮箱用户名',
    },
  },
  {
    component: 'Input',
    fieldName: 'smtp_password',
    label: '密码',
    rules: 'required',
    componentProps: {
      type: 'password',
      placeholder: '请输入邮箱密码或授权码',
      showPassword: true,
    },
  },
  {
    component: 'Input',
    fieldName: 'smtp_from_email',
    label: '发件人邮箱',
    rules: 'required',
    componentProps: {
      placeholder: '请输入发件人邮箱',
    },
  },
  {
    component: 'Input',
    fieldName: 'smtp_from_name',
    label: '发件人名称',
    rules: 'required',
    componentProps: {
      placeholder: '请输入发件人名称',
    },
  },
  {
    component: 'Select',
    fieldName: 'smtp_encryption',
    label: '加密方式',
    componentProps: {
      placeholder: '请选择加密方式',
      options: [
        { label: '无', value: '' },
        { label: 'SSL', value: 'ssl' },
        { label: 'TLS', value: 'tls' },
      ],
    },
  },
  {
    component: 'Switch',
    fieldName: 'smtp_enabled',
    label: '启用状态',
  },
];

// 邮件模板表单配置
const templateFormSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'register_subject',
    label: '邮件标题',
    rules: 'required',
    componentProps: {
      placeholder: '请输入注册验证邮件标题',
    },
  },
  {
    component: 'Input',
    fieldName: 'register_content',
    label: '邮件内容',
    rules: 'required',
    componentProps: {
      type: 'textarea',
      rows: 6,
      placeholder: '请输入注册验证邮件内容，可使用变量：{username}、{code}、{expire}',
    },
  },
  {
    component: 'Switch',
    fieldName: 'register_enabled',
    label: '启用状态',
  },
];

// 测试邮件表单配置
const testFormSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'test_email',
    label: '收件人邮箱',
    rules: 'required',
    componentProps: {
      placeholder: '请输入测试邮箱地址',
    },
  },
  {
    component: 'Select',
    fieldName: 'test_type',
    label: '邮件类型',
    rules: 'required',
    componentProps: {
      placeholder: '请选择邮件类型',
      options: [
        { label: '注册验证', value: 'register' },
        { label: '找回密码', value: 'reset' },
        { label: '通知邮件', value: 'notify' },
      ],
    },
  },
];

// 创建表单实例
const [SmtpForm, smtpFormApi] = useVbenForm({
  schema: smtpFormSchema,
  showDefaultActions: false,
});

const [TemplateForm, templateFormApi] = useVbenForm({
  schema: templateFormSchema,
  showDefaultActions: false,
});

const [TestForm, testFormApi] = useVbenForm({
  schema: testFormSchema,
  showDefaultActions: false,
});

// 处理SMTP配置提交
const handleSubmitSmtp = async (values: Record<string, any>) => {
  try {
    submitLoading.value = true;
    await updateEmailConfigApi('smtp', values);
    // 显示成功消息
  } catch (error) {
    console.error('保存SMTP配置失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

// 处理模板提交
const handleSubmitTemplate = async (values: Record<string, any>) => {
  try {
    submitLoading.value = true;
    await updateEmailConfigApi('template', values);
    // 显示成功消息
  } catch (error) {
    console.error('保存邮件模板失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

// 处理测试邮件
const handleTestEmail = () => {
  testDialogVisible.value = true;
};

// 发送测试邮件
const handleSendTest = async (values: Record<string, any>) => {
  try {
    sendTestLoading.value = true;
    await testEmailApi(values.test_email, values.test_type);
    testDialogVisible.value = false;
    // 显示成功消息
  } catch (error) {
    console.error('发送测试邮件失败:', error);
  } finally {
    sendTestLoading.value = false;
  }
};

// 预览模板
const handlePreviewTemplate = async (type: string) => {
  try {
    const data = await previewEmailTemplateApi(type);
    previewData.subject = data.subject;
    previewData.content = data.content;
    previewDialogVisible.value = true;
  } catch (error) {
    console.error('预览模板失败:', error);
  }
};

// 重置SMTP配置
const handleResetSmtp = () => {
  smtpFormApi.resetForm();
};

// 初始化数据
const initData = async () => {
  try {
    const [smtpData, templateData] = await Promise.all([
      getEmailConfigApi('smtp'),
      getEmailConfigApi('template'),
    ]);
    
    smtpFormApi.setValues(smtpData);
    templateFormApi.setValues(templateData);
  } catch (error) {
    console.error('初始化数据失败:', error);
  }
};

// 组件挂载时初始化数据
onMounted(() => {
  initData();
});
</script>

<style scoped>
.template-preview {
  padding: 16px 0;
}

.preview-item {
  margin-bottom: 16px;
}

.preview-item label {
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
  display: block;
}

.preview-content {
  padding: 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>