<template>
  <div class="p-4">
    <el-card v-loading="loading" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="text-lg font-semibold">{{ t('applet.title') }}</span>
        </div>
      </template>

      <el-tabs v-if="appletData" v-model="activeTab" type="border-card">
        <el-tab-pane :label="t('applet.tab.userAgreement')" name="userAgreement">
          <el-tabs v-model="userAgreementLang" type="card" class="mb-4">
            <el-tab-pane :label="t('applet.lang.chinese')" name="zh_CN">
              <editor v-model="userAgreementData.zh_CN" :min-height="400"/>
            </el-tab-pane>
            <el-tab-pane :label="t('applet.lang.english')" name="en_US">
              <editor v-model="userAgreementData.en_US" :min-height="400"/>
            </el-tab-pane>
          </el-tabs>
          <div class="mt-4">
            <el-button type="primary" :loading="saveLoading" @click="handleSave">{{ t('applet.button.save') }}</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="t('applet.tab.privacyAgreement')" name="privacyAgreement">
          <el-tabs v-model="privacyAgreementLang" type="card" class="mb-4">
            <el-tab-pane :label="t('applet.lang.chinese')" name="zh_CN">
              <editor v-model="privacyAgreementData.zh_CN" :min-height="400"/>
            </el-tab-pane>
            <el-tab-pane :label="t('applet.lang.english')" name="en_US">
              <editor v-model="privacyAgreementData.en_US" :min-height="400"/>
            </el-tab-pane>
          </el-tabs>
          <div class="mt-4">
            <el-button type="primary" :loading="saveLoading" @click="handleSave">{{ t('applet.button.save') }}</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-empty v-else :description="t('applet.message.noData')" />
    </el-card>
  </div>
</template>

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

const { t } = useI18n();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

// 用户协议数据（中英文）
const userAgreementData = ref({
  zh_CN: '',
  en_US: ''
});

// 隐私协议数据（中英文）
const privacyAgreementData = ref({
  zh_CN: '',
  en_US: ''
});

/**
 * 解析协议数据
 * 支持三种格式：
 * 1. BASE64编码的JSON字符串
 * 2. 直接的JSON字符串
 * 3. 普通字符串（兼容旧数据）
 */
const parseAgreementData = (data: string) => {
  if (!data) {
    return { zh_CN: '', en_US: '' };
  }
  
  try {
    // 尝试BASE64解码
    const decoded = decodeURIComponent(escape(atob(data)));
    const parsed = JSON.parse(decoded);
    return {
      zh_CN: parsed.zh_CN || '',
      en_US: parsed.en_US || ''
    };
  } catch (e) {
    // BASE64解码失败，尝试直接JSON解析
    try {
      const parsed = JSON.parse(data);
      return {
        zh_CN: parsed.zh_CN || '',
        en_US: parsed.en_US || ''
      };
    } catch (e2) {
      // JSON解析也失败，作为普通字符串处理（旧格式数据）
      return {
        zh_CN: data,
        en_US: ''
      };
    }
  }
};

/** 获取小程序设置数据 */
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getApplet(1);
    appletData.value = res.data;
    
    // 解析用户协议
    if (appletData.value?.userAgreement) {
      userAgreementData.value = parseAgreementData(appletData.value.userAgreement);
    }
    
    // 解析隐私协议
    if (appletData.value?.privacyAgreement) {
      privacyAgreementData.value = parseAgreementData(appletData.value.privacyAgreement);
    }
  } catch (error) {
    console.error(t('applet.message.fetchFailed'), error);
  } finally {
    loading.value = false;
  }
}

/** 保存数据 */
const handleSave = async () => {
  if (!appletData.value) return;
  
  saveLoading.value = true;
  try {
    // 将中英文协议整理成JSON格式，然后进行BASE64编码
    const userAgreementJson = JSON.stringify({
      zh_CN: userAgreementData.value.zh_CN || '',
      en_US: userAgreementData.value.en_US || ''
    });
    
    const privacyAgreementJson = JSON.stringify({
      zh_CN: privacyAgreementData.value.zh_CN || '',
      en_US: privacyAgreementData.value.en_US || ''
    });
    
    const encodedData = {
      ...appletData.value,
      id: 1, // 默认设置为1
      userAgreement: btoa(unescape(encodeURIComponent(userAgreementJson))),
      privacyAgreement: btoa(unescape(encodeURIComponent(privacyAgreementJson)))
    };
    
    await updateApplet(encodedData);
    proxy?.$modal.msgSuccess(t('applet.message.saveSuccess'));
  } catch (error) {
    console.error(t('applet.message.saveFailed'), error);
  } finally {
    saveLoading.value = false;
  }
}

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