<template>
  <div>
    <warning-bar title="注：本页面管理各密码设施/系统的接口，支持接口的启用、停用及查询。" />
    <div class="gva-table-box">
      <!-- 按钮区域 -->
      <div class="gva-btn-list">
        <el-button
          v-preReClick
          icon="plus"
          type="primary"
          @click="addInterface"
        >
          新增接口
        </el-button>
        <el-button
          v-preReClick
          icon="upload"
          type="success"
          @click="triggerImport"
        >
          Excel导入
        </el-button>
        <el-button
          v-preReClick
          icon="download"
          type="info"
          @click="downloadTemplate"
        >
          下载模板
        </el-button>
        <el-button
          v-preReClick
          icon="refresh"
          type="warning"
          @click="refreshData"
        >
          刷新
        </el-button>
      </div>

      <!-- 隐藏的文件导入input -->
      <input
        ref="fileInputRef"
        type="file"
        accept=".xlsx,.xls"
        style="display: none"
        @change="handleFileChange"
      />

      <!-- 筛选区域 -->
      <div class="filter-area">
        <span class="filter-label">接口名称：</span>
        <el-input
          v-model="filterName"
          clearable
          placeholder="模糊查询"
          style="width: 160px"
          @change="handleFilterChange"
          @clear="handleFilterChange"
        />

        <span class="filter-label" style="margin-left: 12px">接口描述：</span>
        <el-input
          v-model="filterDesc"
          clearable
          placeholder="模糊查询"
          style="width: 160px"
          @change="handleFilterChange"
          @clear="handleFilterChange"
        />

        <span class="filter-label" style="margin-left: 12px">接入密码应用：</span>
        <el-select
          v-model="filterAppIdentifier"
          clearable
          placeholder="全部"
          style="width: 180px"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="item in appIdentifierOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <span class="filter-label" style="margin-left: 12px">接口状态：</span>
        <el-select
          v-model="filterStatus"
          clearable
          placeholder="全部"
          style="width: 120px"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="启用" value="1" />
          <el-option label="停用" value="2" />
        </el-select>

        <el-button
          v-preReClick
          type="primary"
          style="margin-left: 16px"
          @click="handleFilterChange"
        >
          查询
        </el-button>
        <el-button
          v-preReClick
          @click="resetFilter"
        >
          重置
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        row-key="ID"
        style="margin-top: 12px"
      >
        <el-table-column
          align="left"
          label="ID"
          min-width="60"
          prop="ID"
        />
        <el-table-column
          align="left"
          label="接入密码应用标识"
          min-width="180"
          prop="appIdentifier"
          show-overflow-tooltip
        />
        <el-table-column
          align="left"
          label="接口名称"
          min-width="150"
          prop="interfaceName"
          show-overflow-tooltip
        />
        <el-table-column
          align="left"
          label="接口描述"
          min-width="200"
          prop="interfaceDesc"
          show-overflow-tooltip
        />
        <el-table-column
          align="left"
          label="接口状态"
          min-width="110"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="2"
              inline-prompt

              @change="() => { switchStatus(scope.row) }"
            />
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="创建时间"
          min-width="180"
          prop="createTime"
        />
        <el-table-column
          fixed="right"
          label="操作"
          min-width="160"
        >
          <template #default="scope">
            <el-popover
              v-model:visible="scope.row.visible"
              placement="top"
              width="160"
            >
              <p>确定要删除此接口吗？</p>
              <div style="text-align: right; margin-top: 8px">
                <el-button
                  v-preReClick
                  link
                  type="primary"
                  @click="scope.row.visible = false"
                >
                  取消
                </el-button>
                <el-button
                  v-preReClick
                  type="primary"
                  @click="deleteInterface(scope.row)"
                >
                  确定
                </el-button>
              </div>
              <template #reference>
                <el-button
                  v-preReClick
                  icon="delete"
                  link
                  type="primary"
                >
                  删除
                </el-button>
              </template>
            </el-popover>
            <el-button
              v-preReClick
              icon="edit"
              link
              type="primary"
              @click="openEdit(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 新增/编辑接口弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :title="dialogFlag === 'add' ? '新增接口' : '编辑接口'"
      width="560px"
    >
      <div style="max-height: 60vh; overflow: auto; padding: 0 12px">
        <el-form
          ref="interfaceFormRef"
          :model="interfaceForm"
          :rules="formRules"
          label-width="140px"
        >
          <el-form-item
            label="接入密码应用标识"
            prop="appIdentifier"
          >
            <el-select
              v-model="interfaceForm.appIdentifier"
              placeholder="请选择已接入的密码应用"
              style="width: 100%"
              filterable
              allow-create
            >
              <el-option
                v-for="item in appIdentifierOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="接口名称"
            prop="interfaceName"
          >
            <el-input
              v-model="interfaceForm.interfaceName"
              placeholder="请输入接口名称"
            />
          </el-form-item>
          <el-form-item
            label="接口描述"
            prop="interfaceDesc"
          >
            <el-input
              v-model="interfaceForm.interfaceDesc"
              placeholder="请输入接口描述"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
          <el-form-item
            label="接口状态"
            prop="status"
          >
            <el-switch
              v-model="interfaceForm.status"
              :active-value="1"
              :inactive-value="2"
              inline-prompt
              active-text="启用"
              inactive-text="停用"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-preReClick
            @click="closeDialog"
          >
            取 消
          </el-button>
          <el-button
            v-preReClick
            type="primary"
            @click="submitInterface"
          >
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入结果弹窗 -->
    <el-dialog
      v-model="importResultDialog"
      title="导入结果"
      width="500px"
    >
      <div style="padding: 12px">
        <el-alert
          :type="importResult.successCount > 0 ? 'success' : 'error'"
          :closable="false"
        >
          <template #title>
            成功导入 {{ importResult.successCount }} 条，
            失败 {{ importResult.failCount }} 条
          </template>
        </el-alert>
        <div
          v-if="importResult.errors.length > 0"
          style="margin-top: 12px"
        >
          <p style="font-weight: bold; margin-bottom: 8px">失败详情：</p>
          <div
            v-for="(err, index) in importResult.errors"
            :key="index"
            style="font-size: 13px; color: #f56c6c; margin-bottom: 4px"
          >
            {{ err }}
          </div>
        </div>
      </div>
      <template #footer>
        <el-button
          v-preReClick
          type="primary"
          @click="importResultDialog = false"
        >
          知道了
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import WarningBar from '@/components/warningBar/warningBar.vue'
import * as XLSX from 'xlsx'

defineOptions({
  name: 'InterfaceManagement'
})

// ============== Mock 数据 ==============
// 模拟已接入的密码应用标识（来源于数据采集管理）
const appIdentifierOptions = ref([
  { label: 'FAC-202607150930-0012 (主密码机-01)', value: 'FAC-202607150930-0012' },
  { label: 'FAC-202607161420-0034 (密码服务中台-生产)', value: 'FAC-202607161420-0034' },
  { label: 'FAC-202607171100-0056 (密钥管理系统-主)', value: 'FAC-202607171100-0056' },
  { label: 'FAC-202607181645-0078 (安全认证网关-01)', value: 'FAC-202607181645-0078' },
  { label: 'FAC-202607190830-0090 (密码服务中台-测试)', value: 'FAC-202607190830-0090' },
  { label: 'FAC-202607201315-0112 (密码网关-核心)', value: 'FAC-202607201315-0112' }
])

// 生成时间字符串
const getNowStr = () => {
  const d = new Date()
  return d.getFullYear() + '-' +
    String(d.getMonth() + 1).padStart(2, '0') + '-' +
    String(d.getDate()).padStart(2, '0') + ' ' +
    String(d.getHours()).padStart(2, '0') + ':' +
    String(d.getMinutes()).padStart(2, '0') + ':' +
    String(d.getSeconds()).padStart(2, '0')
}

// 初始 Mock 接口列表
let nextId = 1
const mockInterfaceList = ref([
  {
    ID: nextId++,
    appIdentifier: 'FAC-202607150930-0012',
    interfaceName: '获取设备状态',
    interfaceDesc: '查询密码机当前运行状态',
    status: 1,
    createTime: '2026-07-25 09:00:00',
    visible: false
  },
  {
    ID: nextId++,
    appIdentifier: 'FAC-202607150930-0012',
    interfaceName: '证书认证',
    interfaceDesc: '数字证书认证接口',
    status: 1,
    createTime: '2026-07-25 10:30:00',
    visible: false
  },
  {
    ID: nextId++,
    appIdentifier: 'FAC-202607161420-0034',
    interfaceName: '密码服务调用',
    interfaceDesc: '调用密码服务中台提供的加解密服务',
    status: 1,
    createTime: '2026-07-26 14:00:00',
    visible: false
  },
  {
    ID: nextId++,
    appIdentifier: 'FAC-202607171100-0056',
    interfaceName: '密钥同步',
    interfaceDesc: '同步密钥到各节点',
    status: 2,
    createTime: '2026-07-27 11:20:00',
    visible: false
  },
  {
    ID: nextId++,
    appIdentifier: 'FAC-202607181645-0078',
    interfaceName: '用户认证',
    interfaceDesc: '安全认证网关用户身份认证',
    status: 1,
    createTime: '2026-07-28 16:10:00',
    visible: false
  }
])

// ============== 响应式状态 ==============
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

// 筛选条件
const filterName = ref('')
const filterDesc = ref('')
const filterAppIdentifier = ref('')
const filterStatus = ref('')

// 弹窗相关
const addDialogVisible = ref(false)
const importResultDialog = ref(false)
const dialogFlag = ref('add') // 'add' | 'edit'

const interfaceFormRef = ref(null)
const fileInputRef = ref(null)

// 表单数据
const interfaceForm = reactive({
  ID: null,
  appIdentifier: '',
  interfaceName: '',
  interfaceDesc: '',
  status: 1
})

// 表单验证规则
const formRules = {
  appIdentifier: [
    { required: true, message: '请选择接入密码应用标识', trigger: 'change' }
  ],
  interfaceName: [
    { required: true, message: '请输入接口名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur' }
  ],
  interfaceDesc: [
    { required: true, message: '请输入接口描述', trigger: 'blur' }
  ]
}

// 导入结果
const importResult = reactive({
  successCount: 0,
  failCount: 0,
  errors: []
})

// ============== 工具函数 ==============
// 获取过滤后的列表
const getFilteredList = () => {
  let list = [...mockInterfaceList.value]
  if (filterName.value) {
    const kw = filterName.value.toLowerCase()
    list = list.filter(item => item.interfaceName.toLowerCase().includes(kw))
  }
  if (filterDesc.value) {
    const kw = filterDesc.value.toLowerCase()
    list = list.filter(item => item.interfaceDesc.toLowerCase().includes(kw))
  }
  if (filterAppIdentifier.value) {
    list = list.filter(item => item.appIdentifier === filterAppIdentifier.value)
  }
  if (filterStatus.value) {
    list = list.filter(item => item.status === Number(filterStatus.value))
  }
  return list
}

// 刷新表格
const getTableData = () => {
  const filtered = getFilteredList()
  total.value = filtered.length
  const start = (page.value - 1) * pageSize.value
  const end = start + pageSize.value
  tableData.value = filtered.slice(start, end).map(item => ({
    ...item,
    visible: item.visible || false
  }))
}

// 分页与筛选事件
const handleSizeChange = (val) => {
  pageSize.value = val
  page.value = 1
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const handleFilterChange = () => {
  page.value = 1
  getTableData()
}

const resetFilter = () => {
  filterName.value = ''
  filterDesc.value = ''
  filterAppIdentifier.value = ''
  filterStatus.value = ''
  page.value = 1
  getTableData()
}

const refreshData = () => {
  // 可添加刷新逻辑，此处简单重新加载
  getTableData()
  ElMessage.success('数据已刷新')
}

// ============== 新增/编辑 ==============
const addInterface = () => {
  dialogFlag.value = 'add'
  Object.assign(interfaceForm, {
    ID: null,
    appIdentifier: '',
    interfaceName: '',
    interfaceDesc: '',
    status: 1
  })
  addDialogVisible.value = true
  nextTick(() => {
    interfaceFormRef.value?.resetFields()
  })
}

const openEdit = (row) => {
  dialogFlag.value = 'edit'
  Object.assign(interfaceForm, {
    ID: row.ID,
    appIdentifier: row.appIdentifier,
    interfaceName: row.interfaceName,
    interfaceDesc: row.interfaceDesc,
    status: row.status
  })
  addDialogVisible.value = true
  nextTick(() => {
    interfaceFormRef.value?.clearValidate()
  })
}

const closeDialog = () => {
  interfaceFormRef.value?.resetFields()
  addDialogVisible.value = false
}

const submitInterface = async () => {
  await interfaceFormRef.value?.validate((valid) => {
    if (!valid) return

    if (dialogFlag.value === 'add') {
      // 新增
      const newItem = {
        ID: nextId++,
        appIdentifier: interfaceForm.appIdentifier,
        interfaceName: interfaceForm.interfaceName,
        interfaceDesc: interfaceForm.interfaceDesc,
        status: interfaceForm.status,
        createTime: getNowStr(),
        visible: false
      }
      mockInterfaceList.value.unshift(newItem)
      ElMessage.success('新增接口成功')
    } else {
      // 编辑
      const index = mockInterfaceList.value.findIndex(item => item.ID === interfaceForm.ID)
      if (index !== -1) {
        mockInterfaceList.value[index] = {
          ...mockInterfaceList.value[index],
          appIdentifier: interfaceForm.appIdentifier,
          interfaceName: interfaceForm.interfaceName,
          interfaceDesc: interfaceForm.interfaceDesc,
          status: interfaceForm.status
        }
        ElMessage.success('编辑接口成功')
      }
    }
    closeDialog()
    getTableData()
  })
}

// ============== 删除 ==============
const deleteInterface = (row) => {
  const index = mockInterfaceList.value.findIndex(item => item.ID === row.ID)
  if (index !== -1) {
    mockInterfaceList.value.splice(index, 1)
    row.visible = false
    ElMessage.success('删除成功')
    getTableData()
  }
}

// ============== 状态切换 ==============
const switchStatus = async (row) => {
  const index = mockInterfaceList.value.findIndex(item => item.ID === row.ID)
  if (index !== -1) {
    mockInterfaceList.value[index].status = row.status
    const text = row.status === 1 ? '启用' : '停用'
    // 模拟发送指令（实际项目中调用API）
    if (row.status === 2) {
      ElMessage.info(`已向密码应用 ${row.appIdentifier} 发送停止接口 "${row.interfaceName}" 的指令`)
    } else {
      ElMessage.info(`已向密码应用 ${row.appIdentifier} 发送启用接口 "${row.interfaceName}" 的指令`)
    }
    ElMessage.success(`接口已${text}`)
    getTableData()
  }
}

// ============== Excel 导入 ==============
const triggerImport = () => {
  fileInputRef.value?.click()
}

const handleFileChange = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return
  event.target.value = ''

  try {
    const data = await readFileAsArrayBuffer(file)
    const workbook = XLSX.read(data, { type: 'array' })
    const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
    const jsonData = XLSX.utils.sheet_to_json(firstSheet, { defval: '' })

    if (jsonData.length === 0) {
      ElMessage.warning('Excel文件中没有数据')
      return
    }

    processImportData(jsonData)
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('文件解析失败，请检查格式')
  }
}

const readFileAsArrayBuffer = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => resolve(new Uint8Array(e.target.result))
    reader.onerror = reject
    reader.readAsArrayBuffer(file)
  })
}

const processImportData = (jsonData) => {
  importResult.successCount = 0
  importResult.failCount = 0
  importResult.errors = []

  const existingNames = new Set(mockInterfaceList.value.map(item => item.interfaceName))

  jsonData.forEach((row, index) => {
    const rowNum = index + 2
    const appIdentifier = String(row['接入密码应用标识'] || row['appIdentifier'] || '').trim()
    const interfaceName = String(row['接口名称'] || row['interfaceName'] || '').trim()
    const interfaceDesc = String(row['接口描述'] || row['interfaceDesc'] || '').trim()
    let statusRaw = String(row['接口状态'] || row['status'] || '').trim()

    if (!appIdentifier) {
      importResult.errors.push(`第${rowNum}行：接入密码应用标识不能为空`)
      importResult.failCount++
      return
    }
    if (!interfaceName) {
      importResult.errors.push(`第${rowNum}行：接口名称不能为空`)
      importResult.failCount++
      return
    }
    if (!interfaceDesc) {
      importResult.errors.push(`第${rowNum}行：接口描述不能为空`)
      importResult.failCount++
      return
    }

    // 检查应用标识是否在可选列表中（非强制，可自动创建新标识）
    const validApp = appIdentifierOptions.value.some(opt => opt.value === appIdentifier)
    if (!validApp) {
      // 自动添加到可选列表（模拟）
      appIdentifierOptions.value.push({ label: `${appIdentifier} (导入)`, value: appIdentifier })
    }

    // 检查重复接口名称（同一应用下可能允许重复，但这里全局去重，可根据实际调整）
    if (existingNames.has(interfaceName)) {
      importResult.errors.push(`第${rowNum}行：接口名称"${interfaceName}"已存在，跳过`)
      importResult.failCount++
      return
    }

    let status = 1
    if (statusRaw === '停用' || statusRaw === '2') {
      status = 2
    }

    const newItem = {
      ID: nextId++,
      appIdentifier,
      interfaceName,
      interfaceDesc,
      status,
      createTime: getNowStr(),
      visible: false
    }
    mockInterfaceList.value.unshift(newItem)
    existingNames.add(interfaceName)
    importResult.successCount++
  })

  getTableData()
  importResultDialog.value = true
  if (importResult.successCount > 0 && importResult.failCount === 0) {
    ElMessage.success(`成功导入 ${importResult.successCount} 条接口数据`)
  }
}

// 下载模板
const downloadTemplate = async () => {
  try {
    const templateData = [
      {
        '接入密码应用标识': 'FAC-202607150930-0012',
        '接口名称': '示例接口',
        '接口描述': '这是一个示例接口描述',
        '接口状态': '启用'
      }
    ]
    const worksheet = XLSX.utils.json_to_sheet(templateData)
    worksheet['!cols'] = [
      { wch: 30 },
      { wch: 20 },
      { wch: 30 },
      { wch: 12 }
    ]
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '接口导入模板')
    XLSX.writeFile(workbook, '接口导入模板.xlsx')
    ElMessage.success('模板下载成功')
  } catch (error) {
    ElMessage.error('模板下载失败')
  }
}

// ============== 初始化 ==============
onMounted(() => {
  getTableData()
})
</script>

<style lang="scss" scoped>
.filter-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 16px;
  padding: 0 4px;
  gap: 4px 0;

  .filter-label {
    font-size: 14px;
    color: #606266;
    margin-right: 4px;
    white-space: nowrap;
  }
}

.gva-btn-list {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
