<template>
  <ConfigPageBase
    section="integrations"
    title="外部系统对接"
    description="MES / WMS / RCS 等标准接口配置（ExternalIntegrations）"
    :defaults="DEFAULT_INTEGRATIONS">
    <template #default="{ payload, update }">
      <el-tabs model-value="mes">
        <el-tab-pane v-for="kind in (['mes','wms','rcs'] as const)" :key="kind" :name="kind" :label="kind.toUpperCase()">
          <el-table :data="payload[kind]" size="small" border>
            <el-table-column label="ID" width="120">
              <template #default="s">
                <el-input v-model="s.row.id" />
              </template>
            </el-table-column>
            <el-table-column label="名称" min-width="160">
              <template #default="s"><el-input v-model="s.row.name" /></template>
            </el-table-column>
            <el-table-column label="URL" min-width="260">
              <template #default="s"><el-input v-model="s.row.url" /></template>
            </el-table-column>
            <el-table-column label="启用" width="80">
              <template #default="s"><el-switch v-model="s.row.enabled" /></template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="s">
                <el-button text type="danger" size="small" @click="remove(payload, update, kind, s.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button size="small" :icon="Plus" style="margin-top: 8px" @click="add(payload, update, kind)">新增 {{ kind.toUpperCase() }} 端点</el-button>
        </el-tab-pane>
      </el-tabs>
    </template>
  </ConfigPageBase>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import ConfigPageBase from '@/components/ConfigPageBase.vue'
import { DEFAULT_INTEGRATIONS } from '@/mock/data/configs'
import type { ExternalIntegrations } from '@/types/config'

type Kind = 'mes' | 'wms' | 'rcs'

function add(payload: ExternalIntegrations, update: (n: ExternalIntegrations) => void, kind: Kind) {
  const id = `${kind}-${Date.now()}`
  const next: ExternalIntegrations = {
    ...payload,
    [kind]: [...payload[kind], { id, name: '新端点', url: 'http://', enabled: false }]
  }
  update(next)
}

function remove(payload: ExternalIntegrations, update: (n: ExternalIntegrations) => void, kind: Kind, idx: number) {
  const next: ExternalIntegrations = {
    ...payload,
    [kind]: payload[kind].filter((_, i) => i !== idx)
  }
  update(next)
}
</script>
