<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('ai.title') }}</span>
        </div>
      </template>

      <el-form v-if="aiData" ref="formRef" :model="aiData" :rules="rules" label-width="120px" class="setting-form">
        <el-form-item :label="t('ai.form.enabledFlag')" prop="enabledFlag">
          <el-switch
            v-model="aiData.enabledFlag"
            :active-value="1"
            :inactive-value="0"
            :active-text="t('ai.form.enabled')"
            :inactive-text="t('ai.form.disabled')"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="saveLoading" @click="handleSave">{{ t('ai.button.save') }}</el-button>
          <el-button @click="handleReset">{{ t('ai.button.reset') }}</el-button>
        </el-form-item>
      </el-form>

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

<script setup name="AiSetting" lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue';
import { useI18n } from 'vue-i18n';
import type { FormInstance, FormRules } from 'element-plus';
import { getAiSetting, updateAiSetting } from '@/api/setting/ai';
import { AiSettingVO } from '@/api/setting/ai/types';
import type { ComponentInternalInstance } from 'vue';

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

const loading = ref(true);
const saveLoading = ref(false);
const formRef = ref<FormInstance>();
const aiData = ref<AiSettingVO | null>(null);
const originalData = ref<AiSettingVO | null>(null);

// 表单验证规则
const rules: FormRules = {
  enabledFlag: [
    { required: true, message: t('ai.rule.enabledFlagRequired'), trigger: 'change' }
  ]
};

/**
 * 获取AI设置数据
 */
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getAiSetting();
    if (res.code === 200) {
      aiData.value = res.data;
      // 保存原始数据用于重置
      originalData.value = JSON.parse(JSON.stringify(res.data));
    } else {
      proxy?.$modal.msgError(res.msg || t('ai.message.fetchFailed'));
    }
  } catch (error) {
    console.error(t('ai.message.fetchFailed'), error);
    proxy?.$modal.msgError(t('ai.message.fetchFailed'));
  } finally {
    loading.value = false;
  }
};

/**
 * 保存数据
 */
const handleSave = async () => {
  if (!formRef.value || !aiData.value) return;

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      saveLoading.value = true;
      try {
        await updateAiSetting(aiData.value as AiSettingVO);
        proxy?.$modal.msgSuccess(t('ai.message.saveSuccess'));
        // 重新获取数据
        await fetchData();
      } catch (error) {
        console.error(t('ai.message.saveFailed'), error);
        proxy?.$modal.msgError(t('ai.message.saveFailed'));
      } finally {
        saveLoading.value = false;
      }
    }
  });
};

/**
 * 重置表单
 */
const handleReset = () => {
  if (originalData.value) {
    aiData.value = JSON.parse(JSON.stringify(originalData.value));
  }
  formRef.value?.clearValidate();
};

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

<style scoped lang="scss">
.setting-form {
  max-width: 600px;
  margin-top: 20px;
}
</style>
