<template>
  <div class="p-4">
    <VbenForm
      ref="formRef"
      :schema="formSchema"
      :form-options="{
        layout: 'vertical',
        labelCol: { span: 24 },
        wrapperCol: { span: 24 },
      }"
      @submit="handleSave"
    >
      <template #submitButton>
        <div class="flex gap-2">
          <VbenButton type="primary" :loading="saveLoading" @click="handleSave">
            保存配置
          </VbenButton>
          <VbenButton @click="handleTest">
            测试发送
          </VbenButton>
          <VbenButton @click="handleReset">
            重置配置
          </VbenButton>
        </div>
      </template>
    </VbenForm>

    <!-- 测试短信发送对话框 -->
    <VbenModal
      v-model:open="testDialogVisible"
      title="测试短信发送"
      width="500px"
      @ok="handleSendTest"
    >
      <VbenForm
        ref="testFormRef"
        :schema="testFormSchema"
        :form-options="{
          layout: 'vertical',
          labelCol: { span: 24 },
          wrapperCol: { span: 24 },
        }"
      />
    </VbenModal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { VbenForm, VbenButton, VbenModal } from '@vben/components'
import { message } from 'ant-design-vue'
import type { FormSchema } from '@vben/types'
import {
  getSmsConfigApi,
  updateSmsConfigApi,
  testSmsApi,
  resetSmsConfigApi,
  type SmsConfig,
} from '@/api/common/sms'

const formRef = ref()
const testFormRef = ref()
const saveLoading = ref(false)
const testDialogVisible = ref(false)

// 表单配置
const formSchema: FormSchema[] = [
  {
    field: 'provider',
    label: '短信服务商',
    component: 'Select',
    required: true,
    componentProps: {
      options: [
        { label: '阿里云短信', value: 'aliyun' },
        { label: '腾讯云短信', value: 'tencent' },
      ],
    },
  },
  {
    field: 'access_key_id',
    label: 'AccessKey ID',
    component: 'Input',
    required: true,
    show: ({ values }) => values.provider === 'aliyun',
  },
  {
    field: 'access_key_secret',
    label: 'AccessKey Secret',
    component: 'InputPassword',
    required: true,
    show: ({ values }) => values.provider === 'aliyun',
  },
  {
    field: 'sign_name',
    label: '签名名称',
    component: 'Input',
    required: true,
    show: ({ values }) => values.provider === 'aliyun',
  },
  {
    field: 'region',
    label: '地域',
    component: 'Select',
    required: true,
    show: ({ values }) => values.provider === 'aliyun',
    componentProps: {
      options: [
        { label: '华东1（杭州）', value: 'cn-hangzhou' },
        { label: '华北2（北京）', value: 'cn-beijing' },
        { label: '华东2（上海）', value: 'cn-shanghai' },
        { label: '华南1（深圳）', value: 'cn-shenzhen' },
      ],
    },
  },
  {
    field: 'secret_id',
    label: 'SecretId',
    component: 'Input',
    required: true,
    show: ({ values }) => values.provider === 'tencent',
  },
  {
    field: 'secret_key',
    label: 'SecretKey',
    component: 'InputPassword',
    required: true,
    show: ({ values }) => values.provider === 'tencent',
  },
  {
    field: 'app_id',
    label: '应用ID',
    component: 'Input',
    required: true,
    show: ({ values }) => values.provider === 'tencent',
  },
  {
    field: 'sign_content',
    label: '签名内容',
    component: 'Input',
    required: true,
    show: ({ values }) => values.provider === 'tencent',
  },
  {
    field: 'enabled',
    label: '启用状态',
    component: 'Switch',
    defaultValue: true,
  },
  {
    field: 'debug_mode',
    label: '调试模式',
    component: 'Switch',
    defaultValue: false,
    helpMessage: '开启后将记录详细的发送日志',
  },
  {
    field: 'templates',
    label: '短信模板',
    component: 'FormList',
    componentProps: {
      copyIconProps: false,
      deleteIconProps: false,
      addButtonProps: {
        text: '添加模板',
      },
    },
    children: [
      {
        field: 'type',
        label: '模板类型',
        component: 'Select',
        required: true,
        componentProps: {
          options: [
            { label: '验证码', value: 'verify_code' },
            { label: '通知', value: 'notification' },
            { label: '营销', value: 'marketing' },
          ],
        },
      },
      {
        field: 'template_id',
        label: '模板ID',
        component: 'Input',
        required: true,
      },
      {
        field: 'content',
        label: '模板内容',
        component: 'Textarea',
        required: true,
      },
      {
        field: 'variables',
        label: '可用变量',
        component: 'Input',
        helpMessage: '多个变量用逗号分隔，如：code,name',
      },
    ],
  },
  {
    field: 'rate_limit',
    label: '发送限制',
    component: 'FormGroup',
    children: [
      {
        field: 'per_minute',
        label: '每分钟限制',
        component: 'InputNumber',
        defaultValue: 10,
        componentProps: {
          min: 1,
          max: 100,
        },
      },
      {
        field: 'per_hour',
        label: '每小时限制',
        component: 'InputNumber',
        defaultValue: 100,
        componentProps: {
          min: 1,
          max: 1000,
        },
      },
      {
        field: 'per_day',
        label: '每日限制',
        component: 'InputNumber',
        defaultValue: 1000,
        componentProps: {
          min: 1,
          max: 10000,
        },
      },
    ],
  },
]

// 测试表单配置
const testFormSchema: FormSchema[] = [
  {
    field: 'mobile',
    label: '手机号码',
    component: 'Input',
    required: true,
    rules: [
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号码',
      },
    ],
  },
  {
    field: 'template_type',
    label: '模板类型',
    component: 'Select',
    required: true,
    componentProps: {
      options: [
        { label: '验证码', value: 'verify_code' },
        { label: '通知', value: 'notification' },
      ],
    },
  },
  {
    field: 'content',
    label: '短信内容',
    component: 'Textarea',
    required: true,
    componentProps: {
      rows: 3,
      placeholder: '请输入测试短信内容',
    },
  },
]

// 加载配置
const loadConfig = async () => {
  try {
    const data = await getSmsConfigApi()
    formRef.value?.setFieldsValue(data)
  } catch (error) {
    message.error('加载配置失败')
  }
}

// 保存配置
const handleSave = async () => {
  try {
    const values = await formRef.value?.validate()
    if (!values) return

    saveLoading.value = true
    await updateSmsConfigApi(values as SmsConfig)
    message.success('保存成功')
  } catch (error) {
    message.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 测试发送
const handleTest = () => {
  testDialogVisible.value = true
}

// 发送测试短信
const handleSendTest = async () => {
  try {
    const values = await testFormRef.value?.validate()
    if (!values) return

    await testSmsApi(values)
    message.success('测试短信发送成功')
    testDialogVisible.value = false
  } catch (error) {
    message.error('测试短信发送失败')
  }
}

// 重置配置
const handleReset = async () => {
  try {
    await resetSmsConfigApi()
    message.success('重置成功')
    await loadConfig()
  } catch (error) {
    message.error('重置失败')
  }
}

onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.p-4 {
  padding: 16px;
}

.flex {
  display: flex;
}

.gap-2 {
  gap: 8px;
}
</style>