<template>
  <el-form :model="formData" label-width="140px" v-loading="loading">
    <el-collapse v-model="activeCollapse" accordion>
      <el-collapse-item v-for="group in groups" :key="group.key" :title="group.title" :name="group.key">
        <template v-for="field in group.fields" :key="field">
          <el-form-item :label="labelMap[field]||field">
            <el-input v-if="field.includes('secret')||field.includes('key')" v-model="formData[group.key][field]" type="password" show-password />
            <el-input v-else-if="field==='token'||field==='encoding_aes_key'" v-model="formData[group.key][field]" />
            <el-input v-else v-model="formData[group.key][field]" />
          </el-form-item>
        </template>
        <el-form-item>
          <el-button type="primary" @click="saveGroup(group.key)" :loading="saving">保存 {{ group.title }}</el-button>
          <el-button v-if="group.key==='menu'" @click="pushMenu" :loading="pushing">推送菜单</el-button>
        </el-form-item>
      </el-collapse-item>
    </el-collapse>
  </el-form>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../../../utils/request'

const props = defineProps({ terminal: String, groups: Array })
const formData = reactive({})
const loading = ref(false)
const saving = ref(false)
const pushing = ref(false)
const activeCollapse = ref(props.groups?.[0]?.key || '')

const labelMap = { app_id:'AppID', app_secret:'AppSecret', token:'Token', encoding_aes_key:'编码密钥', mch_id:'商户号', api_key:'API密钥', site_name:'站点名称', icp_record:'ICP备案号', primary_color:'主色', header_bg:'头部背景', footer_bg:'底部背景', business_domain:'业务域名', app_name:'应用名称', app_icon:'图标', splash_img:'启动图', version:'版本号', push_appid:'推送AppID', push_appkey:'推送Key', share_title:'分享标题', share_img:'分享图', buttons:'菜单配置', logo:'Logo URL' }

async function loadData() {
  loading.value = true
  for (const group of props.groups) {
    try { const res = await request.get(`/api/terminal/config?terminal=${props.terminal}&group=${group.key}`); formData[group.key] = res || {} } catch(e) { formData[group.key] = {} }
  }
  loading.value = false
}

async function saveGroup(groupKey) {
  saving.value = true
  await request.post('/terminal/config', { terminal: props.terminal, group: groupKey, data: formData[groupKey] })
  ElMessage.success('配置已保存')
  saving.value = false
}

async function pushMenu() {
  pushing.value = true
  try { await request.post('/terminal/push-menu', { terminal: props.terminal }); ElMessage.success('菜单推送成功') }
  catch(e) { ElMessage.error('推送失败: ' + e.message) }
  pushing.value = false
}

onMounted(loadData)
watch(() => props.terminal, loadData)
</script>
