<template>
  <div class="sms-config-setting">
    <!-- 顶部提示信息 -->
    <div class="setting-hint">
      <el-alert :closable="false" type="info" class="custom-alert">
        <template #title>
          <div class="alert-content">
            <el-icon class="info-icon"><InfoFilled /></el-icon>
            <span>短信目前仅支持 3 家，绑定哪一家后要将模板提交到对方平台审核回填模板 ID；模板中的变量请按照对应平台的标准更改。</span>
          </div>
        </template>
      </el-alert>
    </div>

    <!-- 配置表单区 -->
    <div class="setting-body">
      <el-form ref="smsFormRef" :model="form" :rules="rules" label-width="140px" label-position="right" class="premium-setting-form">
        
        <!-- 供应商选择 -->
        <el-form-item label="短信设置：">
          <el-radio-group v-model="form.supplier" @change="handleSupplierChange" class="custom-radio-group">
            <el-radio label="alibaba" border>阿里云</el-radio>
            <el-radio label="qiniu" border>七牛云</el-radio>
            <el-radio label="tencent" border>腾讯云</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 模板 ID -->
        <el-form-item label="验证码模板 ID：" prop="templateId">
          <el-input v-model="form.templateId" placeholder="请输入在对应平台申请的验证码短信模板 ID" class="config-input" />
          <div class="form-tip">请复制短信模版去申请：尊敬的用户您的短信验证码是${code}，10分钟内有效！</div>
        </el-form-item>

        <!-- AccessKey ID -->
        <el-form-item label="AccessKey_id：" prop="accessKeyId">
          <el-input v-model="form.accessKeyId" placeholder="请输入密钥 AccessKey_id" class="config-input" />
        </el-form-item>

        <!-- AccessKey Secret -->
        <el-form-item label="AccessKey_Secret：" prop="accessKeySecret">
          <el-input v-model="form.accessKeySecret" type="password" show-password placeholder="请输入密钥 AccessKey_Secret" class="config-input" />
        </el-form-item>

        <!-- 短信签名 -->
        <el-form-item label="短信签名：" prop="signature">
          <el-input v-model="form.signature" placeholder="请输入短信签名" class="config-input" />
          <div class="form-tip">需要对方平台审核通过</div>
        </el-form-item>

        <!-- 保存按钮 -->
        <el-form-item class="action-item">
          <el-button type="primary" class="save-btn" :loading="buttonLoading" @click="submitForm">保存设置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup name="SmsConfig" lang="ts">
import { listSmsConfig, addSmsConfig, updateSmsConfig } from '@/api/resource/smsConfig';
import { SmsConfigForm } from '@/api/resource/smsConfig/types';
import { InfoFilled } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buttonLoading = ref(false);
const smsFormRef = ref<ElFormInstance>();

const form = ref<SmsConfigForm>({
  id: undefined,
  supplier: 'alibaba',
  accessKeyId: '',
  accessKeySecret: '',
  signature: '',
  sdkAppId: '',
  templateId: '',
  status: true,
});

const rules = {
  templateId: [{ required: true, message: "验证码模板 ID 不能为空", trigger: "blur" }],
  accessKeyId: [{ required: true, message: "AccessKey_id 不能为空", trigger: "blur" }],
  accessKeySecret: [{ required: true, message: "AccessKey_Secret 不能为空", trigger: "blur" }],
  signature: [{ required: true, message: "短信签名 不能为空", trigger: "blur" }],
};

/** 加载对应供应商配置 */
const loadSupplierConfig = async (supplier: string) => {
  const res = await listSmsConfig({ supplier } as any);
  if (res.rows && res.rows.length > 0) {
    Object.assign(form.value, res.rows[0]);
  } else {
    // 若无配置，重置表单（保留当前选中的供应商）
    const currentSupplier = form.value.supplier;
    form.value = {
      id: undefined,
      supplier: currentSupplier,
      accessKeyId: '',
      accessKeySecret: '',
      signature: '',
      sdkAppId: '',
      templateId: '',
      status: true,
    };
  }
};

/** 切换供应商触发表单刷新 */
const handleSupplierChange = (val: any) => {
  loadSupplierConfig(val);
};

/** 提交保存 */
const submitForm = () => {
  smsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 保存时强制确保 status 为启用
        form.value.status = true;
        if (form.value.id) {
          await updateSmsConfig(form.value);
        } else {
          await addSmsConfig(form.value);
        }
        proxy?.$modal.msgSuccess("配置已保存并启用");
        await loadSupplierConfig(form.value.supplier as string);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 初始化：加载当前已启用的配置 */
const initSmsConfig = async () => {
  // 先查所有配置，找到 status 为 true 的那一项
  const res = await listSmsConfig({} as any);
  if (res.rows && res.rows.length > 0) {
    const activeItem = res.rows.find((item: any) => item.status === true);
    if (activeItem) {
      form.value.supplier = activeItem.supplier;
      Object.assign(form.value, activeItem);
    } else {
      // 没配置就默认第一个阿里
      loadSupplierConfig('alibaba');
    }
  } else {
    loadSupplierConfig('alibaba');
  }
};

onMounted(() => {
  initSmsConfig();
});
</script>

<style scoped lang="scss">
.sms-config-setting {
  padding: 8px 0;
}

.setting-hint {
  margin-bottom: 32px;
  
  .custom-alert {
    background-color: #e8f4ff;
    border: none;
    border-radius: 8px;
    padding: 12px 16px;

    .alert-content {
      display: flex;
      align-items: center;
      gap: 10px;
      color: #1890ff;
      font-size: 14px;
      line-height: 1.5;

      .info-icon {
        font-size: 18px;
      }
    }
  }
}

.setting-body {
  padding-left: 20px;
}

.premium-setting-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #4e5969;
    padding-right: 24px;
  }

  .config-input {
    max-width: 520px;
    
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #e5e6eb inset;
      padding: 4px 12px;
      border-radius: 6px;
      
      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }

  .form-tip {
    font-size: 13px;
    color: #86909c;
    margin-top: 8px;
    line-height: 1.4;
  }

  .custom-radio-group {
    :deep(.el-radio) {
      margin-right: 16px;
      border-radius: 6px;
      padding: 0 20px;
      height: 36px;
      
      &.is-bordered.is-checked {
        border-color: #409eff;
        background-color: rgba(64, 158, 255, 0.04);
      }
      
      .el-radio__label {
        font-size: 14px;
      }
    }
  }

  .action-item {
    margin-top: 40px;
  }

  .save-btn {
    padding: 12px 32px;
    height: auto;
    font-size: 15px;
    font-weight: 500;
    border-radius: 6px;
    box-shadow: 0 4px 10px rgba(64, 158, 255, 0.2);
  }
}
</style>
