<template>
    <div class="p-2">
        <el-card shadow="never">
            <template #header>
                <span class="font-bold text-base">协议管理</span>
            </template>

            <!-- 协议切换 Tab -->
            <el-tabs v-model="activeTab" @tab-change="handleTabChange">
                <el-tab-pane label="用户协议" name="1" />
                <el-tab-pane label="隐私政策" name="2" />
            </el-tabs>

            <!-- 编辑区 -->
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" class="mt-4">
                <el-form-item label="协议标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入协议标题" style="width: 400px" />
                </el-form-item>
                <el-form-item label="协议内容" prop="content">
                    <div style="width: 100%; border: 1px solid #dcdfe6; border-radius: 4px;">
                        <editor v-model="form.content" :min-height="300" />
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button v-hasPermi="['system:agreement:edit']" type="primary" icon="Check" :loading="saving"
                        @click="handleSave">
                        保存
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { getAgreement, updateAgreement } from '@/api/system/agreement';
import { AgreementForm } from '@/api/system/agreement/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const activeTab = ref<string>('1');
const saving = ref(false);
const formRef = ref<ElFormInstance>();

const form = reactive<AgreementForm>({
    id: 1,
    title: '',
    content: ''
});

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

/** 加载指定协议 */
const loadAgreement = async (id: number) => {
    const res = await getAgreement(id);
    form.id = res.data.id;
    form.title = res.data.title;
    form.content = res.data.content;
};

/** 切换 Tab */
const handleTabChange = (name: string | number) => {
    loadAgreement(Number(name));
};

/** 保存（content base64 编码后提交） */
const handleSave = () => {
    formRef.value?.validate(async (valid: boolean) => {
        if (!valid) return;
        saving.value = true;
        try {
            const encoded = btoa(unescape(encodeURIComponent(form.content)));
            await updateAgreement({ ...form, content: encoded });
            proxy?.$modal.msgSuccess('保存成功');
        } finally {
            saving.value = false;
        }
    });
};

onMounted(() => {
    loadAgreement(1);
});
</script>
