<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="配置名称" prop="configName">
        <el-input v-model="queryParams.configName" placeholder="请输入配置名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="邮箱类型" prop="mailType">
        <el-select v-model="queryParams.mailType" placeholder="请选择邮箱类型" clearable style="width: 200px">
          <el-option v-for="item in mailTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:mail:config:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['system:mail:config:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:mail:config:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:mail:config:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配置ID" align="center" prop="configId" width="80" />
      <el-table-column label="配置名称" align="center" prop="configName" :show-overflow-tooltip="true" />
      <el-table-column label="邮箱类型" align="center" prop="mailType" width="100">
        <template #default="scope">
          <el-tag :type="getMailTypeTag(scope.row.mailType)">{{ getMailTypeName(scope.row.mailType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发件人邮箱" align="center" prop="senderEmail" :show-overflow-tooltip="true" />
      <el-table-column label="发件人名称" align="center" prop="senderName" width="120" />
      <el-table-column label="是否默认" align="center" prop="isDefault" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.isDefault === '1' ? 'success' : 'info'">{{ scope.row.isDefault === '1' ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">{{ scope.row.status === '0' ? '正常' : '停用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:mail:config:edit']">修改</el-button>
          <el-button link type="primary" icon="Position" @click="handleTest(scope.row)" v-hasPermi="['system:mail:config:test']">测试</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:mail:config:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改邮箱配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="configRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="配置名称" prop="configName">
              <el-input v-model="form.configName" placeholder="请输入配置名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱类型" prop="mailType">
              <el-select v-model="form.mailType" placeholder="请选择邮箱类型" @change="handleMailTypeChange">
                <el-option v-for="item in mailTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="SMTP服务器" prop="host">
              <el-input v-model="form.host" placeholder="请输入SMTP服务器地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口" prop="port">
              <el-input-number v-model="form.port" :min="1" :max="65535" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名/发件邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="请输入密码/授权码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发件人邮箱" prop="senderEmail">
              <el-input v-model="form.senderEmail" placeholder="请输入发件人邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发件人名称" prop="senderName">
              <el-input v-model="form.senderName" placeholder="请输入发件人名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="加密方式" prop="encryption">
              <el-select v-model="form.encryption" placeholder="请选择加密方式">
                <el-option label="SSL" value="ssl" />
                <el-option label="TLS" value="tls" />
                <el-option label="无" value="none" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否默认" prop="isDefault">
              <el-radio-group v-model="form.isDefault">
                <el-radio value="1">是</el-radio>
                <el-radio value="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio value="0">正常</el-radio>
                <el-radio value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用收信" prop="enableReceive">
              <el-radio-group v-model="form.enableReceive" @change="handleEnableReceiveChange">
                <el-radio value="1">是</el-radio>
                <el-radio value="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- IMAP配置 -->
        <el-divider content-position="left" v-if="form.enableReceive === '1'">收信配置（IMAP）</el-divider>
        <template v-if="form.enableReceive === '1'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="IMAP服务器" prop="imapHost">
                <el-input v-model="form.imapHost" placeholder="如：imap.qiye.aliyun.com" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="IMAP端口" prop="imapPort">
                <el-input-number v-model="form.imapPort" :min="1" :max="65535" controls-position="right" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="IMAP加密" prop="imapEncryption">
                <el-select v-model="form.imapEncryption" placeholder="请选择加密方式">
                  <el-option label="SSL" value="ssl" />
                  <el-option label="TLS" value="tls" />
                  <el-option label="无" value="none" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 测试邮件对话框 -->
    <el-dialog title="发送测试邮件" v-model="testOpen" width="400px" append-to-body>
      <el-form ref="testRef" :model="testForm" :rules="testRules" label-width="100px">
        <el-form-item label="配置名称">
          <el-input v-model="testForm.configName" disabled />
        </el-form-item>
        <el-form-item label="测试邮箱" prop="testEmail">
          <el-input v-model="testForm.testEmail" placeholder="请输入接收测试邮件的邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTest" :loading="testLoading">发送测试</el-button>
          <el-button @click="testOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MailConfig">
import { listMailConfig, getMailConfig, addMailConfig, updateMailConfig, delMailConfig, testMailConfig } from "@/api/system/mail"

const { proxy } = getCurrentInstance()

const configList = ref([])
const open = ref(false)
const testOpen = ref(false)
const loading = ref(true)
const testLoading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 邮箱类型选项
const mailTypeOptions = ref([
  { value: 'aliyun', label: '阿里云企业邮箱' },
  { value: 'tencent', label: '腾讯企业邮箱' },
  { value: 'netease', label: '网易企业邮箱' },
  { value: 'custom', label: '自定义SMTP' }
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    configName: null,
    mailType: null,
    status: null
  },
  rules: {
    configName: [{ required: true, message: "配置名称不能为空", trigger: "blur" }],
    mailType: [{ required: true, message: "邮箱类型不能为空", trigger: "change" }],
    senderEmail: [
      { required: true, message: "发件人邮箱不能为空", trigger: "blur" },
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ]
  },
  testForm: {
    configId: null,
    configName: "",
    testEmail: ""
  },
  testRules: {
    testEmail: [
      { required: true, message: "测试邮箱不能为空", trigger: "blur" },
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules, testForm, testRules } = toRefs(data)

/** 查询邮箱配置列表 */
function getList() {
  loading.value = true
  listMailConfig(queryParams.value).then(response => {
    configList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 获取邮箱类型名称 */
function getMailTypeName(type) {
  const item = mailTypeOptions.value.find(i => i.value === type)
  return item ? item.label : type
}

/** 获取邮箱类型标签样式 */
function getMailTypeTag(type) {
  const map = { aliyun: 'warning', tencent: 'primary', netease: 'success', custom: 'info' }
  return map[type] || 'info'
}

/** 邮箱类型变更时设置默认值 */
function handleMailTypeChange(type) {
  const defaults = getMailTypeDefaults(type)
  if (defaults) {
    form.value.host = defaults.host
    form.value.port = defaults.port
    form.value.encryption = defaults.encryption
    form.value.imapHost = defaults.imapHost
    form.value.imapPort = defaults.imapPort
    form.value.imapEncryption = defaults.imapEncryption
  }
}

/** 获取邮箱类型默认配置 */
function getMailTypeDefaults(type) {
  const defaults = {
    aliyun: { host: 'smtp.qiye.aliyun.com', port: 465, encryption: 'ssl', imapHost: 'imap.qiye.aliyun.com', imapPort: 993, imapEncryption: 'ssl' },
    tencent: { host: 'smtp.exmail.qq.com', port: 465, encryption: 'ssl', imapHost: 'imap.exmail.qq.com', imapPort: 993, imapEncryption: 'ssl' },
    netease: { host: 'smtp.qiye.163.com', port: 465, encryption: 'ssl', imapHost: 'imap.qiye.163.com', imapPort: 993, imapEncryption: 'ssl' },
    custom: { host: '', port: 25, encryption: 'none', imapHost: '', imapPort: 993, imapEncryption: 'ssl' }
  }
  return defaults[type] || null
}

/** 启用收信变更时自动填充IMAP配置 */
function handleEnableReceiveChange(val) {
  if (val === '1' && form.value.mailType) {
    // 如果启用收信且IMAP配置为空，自动根据邮箱类型填充
    const defaults = getMailTypeDefaults(form.value.mailType)
    if (defaults) {
      if (!form.value.imapHost) {
        form.value.imapHost = defaults.imapHost
      }
      if (!form.value.imapPort) {
        form.value.imapPort = defaults.imapPort
      }
      if (!form.value.imapEncryption) {
        form.value.imapEncryption = defaults.imapEncryption
      }
    }
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    configId: null,
    configName: null,
    mailType: null,
    host: null,
    port: 465,
    username: null,
    password: null,
    senderEmail: null,
    senderName: null,
    encryption: 'ssl',
    imapHost: null,
    imapPort: 993,
    imapEncryption: 'ssl',
    enableReceive: '0',
    isDefault: '0',
    status: '0',
    remark: null
  }
  proxy.resetForm("configRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.configId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加邮箱配置"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const configId = row.configId || ids.value
  getMailConfig(configId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改邮箱配置"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["configRef"].validate(valid => {
    if (valid) {
      if (form.value.configId != null) {
        updateMailConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMailConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const configIds = row.configId || ids.value
  proxy.$modal.confirm('是否确认删除邮箱配置编号为"' + configIds + '"的数据项？').then(function() {
    return delMailConfig(configIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 测试按钮操作 */
function handleTest(row) {
  testForm.value.configId = row.configId
  testForm.value.configName = row.configName
  testForm.value.testEmail = ""
  testOpen.value = true
}

/** 发送测试邮件 */
function submitTest() {
  proxy.$refs["testRef"].validate(valid => {
    if (valid) {
      testLoading.value = true
      testMailConfig({
        configId: testForm.value.configId,
        remark: testForm.value.testEmail  // 临时使用remark传递测试邮箱
      }).then(response => {
        proxy.$modal.msgSuccess(response.msg || "测试邮件发送成功")
        testOpen.value = false
      }).finally(() => {
        testLoading.value = false
      })
    }
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/mail/config/export', {
    ...queryParams.value
  }, `mail_config_${new Date().getTime()}.xlsx`)
}

getList()
</script>
