<template>
  <div class="p-4">
    <el-card v-loading="loading" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="text-lg font-semibold">小程序设置</span>
        </div>
      </template>

      <el-tabs v-if="appletData" v-model="activeTab" type="border-card">
        <el-tab-pane label="用户协议" name="userAgreement">
          <editor v-model="appletData.userAgreement" :min-height="400"/>
          <div class="mt-4">
            <el-button type="primary" :loading="saveLoading" @click="handleSave">保存</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="隐私协议" name="privacyAgreement">
          <editor v-model="appletData.privacyAgreement" :min-height="400"/>
          <div class="mt-4">
            <el-button type="primary" :loading="saveLoading" @click="handleSave">保存</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-empty v-else description="暂无数据" />
    </el-card>
  </div>
</template>

<script setup name="Applet" lang="ts">
import { getApplet, updateApplet } from '@/api/setting/applet';
import { AppletVO } from '@/api/setting/applet/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(true);
const saveLoading = ref(false);
const activeTab = ref('userAgreement');
const appletData = ref<AppletVO | null>(null);

/** 获取小程序设置数据 */
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getApplet(1);
    appletData.value = res.data;
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
}

/** 保存数据 */
const handleSave = async () => {
  if (!appletData.value) return;
  
  saveLoading.value = true;
  try {
    // 使用BASE64编码
    const encodedData = {
      ...appletData.value,
      id: 1, // 默认设置为1
      userAgreement: btoa(unescape(encodeURIComponent(appletData.value.userAgreement || ''))),
      privacyAgreement: btoa(unescape(encodeURIComponent(appletData.value.privacyAgreement || '')))
    };
    
    await updateApplet(encodedData);
    proxy?.$modal.msgSuccess("保存成功");
  } catch (error) {
    console.error('保存失败:', error);
  } finally {
    saveLoading.value = false;
  }
}

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