<template>
  <div class="protocol-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>协议配置：目前支持用户协议、隐私政策、履约者说明、托运协议、宠物洗护服务规范；请确保内容准确合规。</span>
          </div>
        </template>
      </el-alert>
    </div>

    <!-- 配置表单区 -->
    <div class="setting-body">
      <el-form ref="protocolFormRef" :model="form" :rules="rules" label-width="140px" label-position="right"
        class="premium-setting-form">

        <!-- 协议选择 -->
        <el-form-item label="协议选择：">
          <el-radio-group v-model="currentId" @change="handleTypeChange" class="custom-radio-group">
            <el-radio :label="1" border>用户协议</el-radio>
            <el-radio :label="2" border>隐私政策</el-radio>
            <el-radio :label="3" border>履约者说明</el-radio>
            <el-radio :label="4" border>托运协议</el-radio>
            <el-radio :label="5" border>宠物洗护服务规范</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 协议标题 -->
        <el-form-item label="协议标题：" prop="title">
          <el-input v-model="form.title" placeholder="请输入协议标题" class="config-input" />
        </el-form-item>

        <!-- 协议内容 -->
        <el-form-item label="协议内容：" prop="content">
          <Editor v-model="form.content" :min-height="400" class="config-editor" />
          <div class="form-tip">协议内容将以 HTML 格式保存，支持图片和视频插入。</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="ProtocolConfig" lang="ts">
import { ref, reactive, onMounted, getCurrentInstance, ComponentInternalInstance } from 'vue';
import { getAgreement, editAgreement } from '@/api/system/agreement';
import { InfoFilled } from '@element-plus/icons-vue';
import { ElForm } from 'element-plus';
import Editor from '@/components/Editor/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buttonLoading = ref(false);
const protocolFormRef = ref<InstanceType<typeof ElForm>>();
const currentId = ref(1); // 默认选择用户协议 ID:1

const form = reactive({
  id: undefined,
  title: '',
  content: ''
});

const rules = {
  title: [{ required: true, message: "协议标题不能为空", trigger: "blur" }],
  content: [{ required: true, message: "协议内容不能为空", trigger: "blur" }],
};

/** 加载协议配置 */
const loadProtocolConfig = async (id: number) => {
  try {
    const res = await getAgreement(id);
    if (res.data) {
      Object.assign(form, res.data);
    }
  } catch (error) {
    console.error('获取协议信息失败', error);
  }
};

/** 切换协议 */
const handleTypeChange = (val: any) => {
  loadProtocolConfig(val as number);
};

/** 提交按钮 */
const submitForm = () => {
  protocolFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 将 content 按照 Base64 方式编码，同时处理非西欧语言字符集
        const contentBase64 = btoa(unescape(encodeURIComponent(form.content)));

        const submitData = {
          id: form.id || currentId.value,
          title: form.title,
          content: contentBase64
        };

        await editAgreement(submitData);
        proxy?.$modal.msgSuccess("保存成功");
        await loadProtocolConfig(currentId.value);
      } catch (error) {
        console.error('保存协议信息失败', error);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

onMounted(() => {
  loadProtocolConfig(currentId.value);
});
</script>

<style scoped lang="scss">
.protocol-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;
      }
    }
  }

  .config-editor {
    width: 100%;
    max-width: 1000px;
  }

  .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>
