<template>
  <el-card shadow="never" class="settings-card">
    <template #header>
      <div class="card-header">
        <slot name="header">
          <span>插件配置</span>
        </slot>
      </div>
    </template>

    <formCreate
      :rule="configRule"
      :option="configOptions"
      v-if="configRule.length > 0"
    />
    <el-empty v-else description="暂无配置项" />
  </el-card>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getPluginConfigApi, savePluginConfigApi } from '@/api/plugin'
import {useUserStore} from "@/store/user.js";

const userStore = useUserStore()
const props = defineProps({
  pluginId: {
    type: String,
    required: true
  },
  setting: {
    type: String,
    default: null
  }
})

const configRule = ref([])
const loading = ref(false)

const configOptions = ref({
  form: {
    labelPosition: 'right',
  },
  submitBtn: {
    innerText: '保存配置',
    loading: loading
  },
  resetBtn: true,
  onSubmit: async (formData) => {
    try {
      loading.value = true
      await savePluginConfigApi(props.pluginId, formData)
      ElMessage.success('配置保存成功')
    } finally {
      loading.value = false
    }
  },
  beforeFetch: (options) => {
    options.headers = {
      Authorization: `Bearer ${userStore.token}`
    };
  }
})

const loadConfig = async () => {
  try {
    let { data } = await getPluginConfigApi(props.pluginId)

    if (!Array.isArray(data)) {
      console.warn('Expected configRule to be an array, but got:', typeof data)
      data = []
    }

    if (props.setting) {
      const findSetting = (items, target) => {
        for (const item of items) {
          if (item.field === target) return item
          if (item.children) {
            const found = findSetting(item.children, target)
            if (found) return found
          }
        }
        return null
      }
      const setting = findSetting(data, props.setting)
      configRule.value = setting ? [setting] : []
    } else {
      configRule.value = data
    }
  } catch (e) {
    console.error('加载配置失败:', e)
    ElMessage.error('配置加载失败')
  }
}

// 监听参数变化自动加载
watch(() => props.pluginId, loadConfig, { immediate: true })
watch(() => props.setting, loadConfig)
</script>

<style scoped>
.settings-card {
  margin-bottom: 20px;
}
</style>
