<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧表单 -->
      <el-col :span="12">
        <el-card class="mail-compose-card">
          <template #header>
            <div class="card-header">
              <span>发送邮件</span>
            </div>
          </template>
          
          <el-form ref="mailRef" :model="mailForm" :rules="rules" label-width="100px">
            <el-form-item label="发件配置" prop="configId">
              <el-select v-model="mailForm.configId" placeholder="请选择发件配置" style="width: 100%">
                <el-option v-for="item in configList" :key="item.configId" :label="item.configName + ' (' + item.senderEmail + ')'" :value="item.configId" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="收件人" prop="to">
              <el-input v-model="mailForm.to" placeholder="多个收件人用逗号分隔" />
            </el-form-item>
            
            <el-form-item label="抄送">
              <el-input v-model="mailForm.cc" placeholder="多个抄送人用逗号分隔（可选）" />
            </el-form-item>
            
            <el-form-item label="密送">
              <el-input v-model="mailForm.bcc" placeholder="多个密送人用逗号分隔（可选）" />
            </el-form-item>

            <el-divider content-position="left">邮件内容</el-divider>

            <el-form-item label="发送方式">
              <el-radio-group v-model="sendMode" @change="handleSendModeChange">
                <el-radio value="template">使用模板</el-radio>
                <el-radio value="custom">自定义内容</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 模板模式 -->
            <template v-if="sendMode === 'template'">
              <el-form-item label="选择模板" prop="templateId">
                <el-select v-model="selectedTemplateId" placeholder="请选择邮件模板" style="width: 100%" @change="handleTemplateChange">
                  <el-option v-for="item in templateList" :key="item.templateId" :label="item.templateName" :value="item.templateId" />
                </el-select>
              </el-form-item>

              <!-- 模板变量填写 -->
              <template v-if="templateVariables.length > 0">
                <el-divider content-position="left">模板参数</el-divider>
                <el-form-item v-for="varName in templateVariables" :key="varName" :label="varName">
                  <el-input v-model="variableValues[varName]" :placeholder="'请输入 ' + varName" @input="updatePreview" />
                </el-form-item>
              </template>
            </template>

            <!-- 自定义内容模式 -->
            <template v-else>
              <el-form-item label="邮件主题" prop="subject">
                <el-input v-model="mailForm.subject" placeholder="请输入邮件主题" />
              </el-form-item>

              <el-form-item label="内容格式">
                <el-radio-group v-model="mailForm.isHtml">
                  <el-radio :value="true">HTML</el-radio>
                  <el-radio :value="false">纯文本</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="邮件内容" prop="content">
                <el-input v-model="mailForm.content" type="textarea" :rows="10" placeholder="请输入邮件内容" />
              </el-form-item>
            </template>
            
            <el-form-item>
              <el-button type="primary" icon="Position" :loading="sending" @click="handleSend">发送邮件</el-button>
              <el-button icon="Refresh" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧预览 -->
      <el-col :span="12">
        <el-card class="preview-card">
          <template #header>
            <div class="card-header">
              <span>邮件预览</span>
              <el-button v-if="sendMode === 'template' && selectedTemplateId" type="primary" link @click="refreshPreview">刷新预览</el-button>
            </div>
          </template>
          
          <div class="preview-content" v-if="previewSubject || previewContent">
            <div class="preview-subject">
              <strong>主题：</strong>{{ previewSubject }}
            </div>
            <el-divider />
            <div class="preview-body" v-if="mailForm.isHtml || (currentTemplate && currentTemplate.contentType === 'html')" v-html="previewContent"></div>
            <div class="preview-body text-content" v-else>{{ previewContent }}</div>
          </div>
          <el-empty v-else description="请填写内容或选择模板后查看预览" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="MailSend">
import { getEnabledConfigList, getTemplateSelectList, getMailTemplate, sendMail, sendMailByTemplate } from "@/api/system/mail"
import { useRoute } from 'vue-router'

const route = useRoute()
const { proxy } = getCurrentInstance()

const configList = ref([])
const templateList = ref([])
const selectedTemplateId = ref(null)
const currentTemplate = ref(null)
const templateVariables = ref([])
const variableValues = ref({})
const sending = ref(false)
const sendMode = ref('template') // template 或 custom

// 预览内容
const previewSubject = ref('')
const previewContent = ref('')

const mailForm = ref({
  configId: null,
  to: '',
  cc: '',
  bcc: '',
  subject: '',
  content: '',
  isHtml: true
})

const rules = {
  configId: [{ required: true, message: '请选择发件配置', trigger: 'change' }],
  to: [
    { required: true, message: '收件人不能为空', trigger: 'blur' },
    { pattern: /^[\w\.\-\+]+@[\w\.-]+\.\w+(,\s*[\w\.\-\+]+@[\w\.-]+\.\w+)*$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  subject: [{ required: true, message: '邮件主题不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '邮件内容不能为空', trigger: 'blur' }]
}

/** 加载配置列表 */
function loadConfigList() {
  getEnabledConfigList().then(res => {
    configList.value = res.data || []
    if (configList.value.length > 0) {
      const defaultConfig = configList.value.find(c => c.isDefault === '1')
      mailForm.value.configId = defaultConfig ? defaultConfig.configId : configList.value[0].configId
    }
  })
}

/** 加载模板列表 */
function loadTemplateList() {
  getTemplateSelectList().then(res => {
    templateList.value = res.data || []
  })
}

/** 切换发送方式 */
function handleSendModeChange() {
  if (sendMode.value === 'custom') {
    selectedTemplateId.value = null
    currentTemplate.value = null
    templateVariables.value = []
    variableValues.value = {}
    previewSubject.value = ''
    previewContent.value = ''
  }
}

/** 选择模板 */
function handleTemplateChange(templateId) {
  if (!templateId) {
    currentTemplate.value = null
    templateVariables.value = []
    variableValues.value = {}
    previewSubject.value = ''
    previewContent.value = ''
    return
  }
  getMailTemplate(templateId).then(res => {
    currentTemplate.value = res.data
    // 解析模板变量
    if (res.data.variables) {
      try {
        templateVariables.value = JSON.parse(res.data.variables)
        // 初始化变量值
        variableValues.value = {}
        templateVariables.value.forEach(v => {
          variableValues.value[v] = ''
        })
      } catch (e) {
        templateVariables.value = []
      }
    } else {
      templateVariables.value = []
    }
    updatePreview()
  })
}

/** 更新预览 */
function updatePreview() {
  if (!currentTemplate.value) {
    previewSubject.value = mailForm.value.subject
    previewContent.value = mailForm.value.content
    return
  }
  
  let subject = currentTemplate.value.subject
  let content = currentTemplate.value.content
  
  // 替换变量
  for (const [key, value] of Object.entries(variableValues.value)) {
    const regex = new RegExp('\\$\\{' + key + '\\}', 'g')
    const replacement = value || '<span style="color:#999">[' + key + ']</span>'
    subject = subject.replace(regex, replacement)
    content = content.replace(regex, replacement)
  }
  
  previewSubject.value = subject
  previewContent.value = content
}

/** 刷新预览 */
function refreshPreview() {
  updatePreview()
}

/** 监听自定义内容变化 */
watch(() => mailForm.value.subject, () => {
  if (sendMode.value === 'custom') {
    previewSubject.value = mailForm.value.subject
  }
})

watch(() => mailForm.value.content, () => {
  if (sendMode.value === 'custom') {
    previewContent.value = mailForm.value.content
  }
})

/** 发送邮件 */
function handleSend() {
  // 基础验证
  if (!mailForm.value.configId) {
    proxy.$modal.msgWarning('请选择发件配置')
    return
  }
  if (!mailForm.value.to) {
    proxy.$modal.msgWarning('请输入收件人')
    return
  }

  if (sendMode.value === 'template') {
    // 模板发送
    if (!selectedTemplateId.value) {
      proxy.$modal.msgWarning('请选择邮件模板')
      return
    }
    // 检查必填变量
    const emptyVars = templateVariables.value.filter(v => !variableValues.value[v])
    if (emptyVars.length > 0) {
      proxy.$modal.msgWarning('请填写模板参数：' + emptyVars.join(', '))
      return
    }
    
    sending.value = true
    sendMailByTemplate({
      configId: mailForm.value.configId,
      templateCode: currentTemplate.value.templateCode,
      to: mailForm.value.to,
      variables: variableValues.value
    }).then(res => {
      proxy.$modal.msgSuccess(res.msg || "邮件发送成功")
      resetForm()
    }).finally(() => {
      sending.value = false
    })
  } else {
    // 自定义内容发送
    if (!mailForm.value.subject) {
      proxy.$modal.msgWarning('请输入邮件主题')
      return
    }
    if (!mailForm.value.content) {
      proxy.$modal.msgWarning('请输入邮件内容')
      return
    }
    
    sending.value = true
    sendMail(mailForm.value).then(res => {
      proxy.$modal.msgSuccess(res.msg || "邮件发送成功")
      resetForm()
    }).finally(() => {
      sending.value = false
    })
  }
}

/** 重置表单 */
function resetForm() {
  mailForm.value = {
    configId: mailForm.value.configId,
    to: '',
    cc: '',
    bcc: '',
    subject: '',
    content: '',
    isHtml: true
  }
  selectedTemplateId.value = null
  currentTemplate.value = null
  templateVariables.value = []
  variableValues.value = {}
  previewSubject.value = ''
  previewContent.value = ''
}

// 初始化
loadConfigList()
loadTemplateList()

// 如果有URL参数（如回复邮件），填充表单
if (route.query.to || route.query.subject || route.query.content) {
  sendMode.value = 'custom' // 切换到自定义模式
  if (route.query.to) {
    mailForm.value.to = route.query.to
  }
  if (route.query.subject) {
    mailForm.value.subject = route.query.subject
  }
  if (route.query.content) {
    mailForm.value.content = decodeURIComponent(route.query.content)
  }
}
</script>

<style scoped>
.mail-compose-card, .preview-card {
  height: calc(100vh - 140px);
  overflow: auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}
.preview-content {
  padding: 10px;
}
.preview-subject {
  font-size: 16px;
  padding: 10px 0;
}
.preview-body {
  padding: 10px 0;
  line-height: 1.8;
}
.text-content {
  white-space: pre-wrap;
  font-family: inherit;
}
</style>
