<template>
  <div class="api-setting-page">
    <!-- 表格组件 -->
    <TableList ref="tableListRef" :config="tableConfig" />

    <!-- 表单弹窗组件 -->
    <ApiForm
      v-model:visible="formDialogVisible"
      :mode="formMode"
      :data="formData"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, h } from 'vue'
import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
import TableList from '@/components/TableList/index.vue'
import ApiForm from './form.vue'
import download from '@/utils/download'
import { checkPermi } from '@/utils/permission'
import { dateFormatter } from '@/utils/formatTime'
import {
  getApiSettingPage,
  createApiSetting,
  updateApiSetting,
  deleteApiSetting,
  exportApiSetting
} from '@/api/print/apiSetting'

// 表格引用
const tableListRef = ref()

// 弹窗相关
const formDialogVisible = ref(false)
const formMode = ref<'add' | 'edit' | 'detail'>('add')
const formData = ref<any>(null)

// 模拟数据
const mockData = [
  {
    id: 1,
    name: '用户登录接口',
    interfaceKey: 'API001',
    method: 'POST',
    baseUrl: '/api/auth/login',
    headerTemplate: '{"Content-Type": "application/json"}',
    inputParamTemplate: '{"username": "admin", "password": "123456"}',
    responseParams: '{"code": 200, "data": {"token": "xxx"}}',
    status: 0,
    createdBy: '张三',
    createdTime: '2026-01-10 10:00:00',
    updatedBy: '张三',
    updatedTime: '2026-01-10 10:00:00'
  },
  {
    id: 2,
    name: '获取用户信息',
    interfaceKey: 'API002',
    method: 'GET',
    baseUrl: '/api/user/info',
    headerTemplate: '{"Authorization": "Bearer token"}',
    inputParamTemplate: '{"userId": 1}',
    responseParams: '{"code": 200, "data": {"id": 1, "name": "admin"}}',
    status: 1,
    createdBy: '李四',
    createdTime: '2026-01-11 14:30:00',
    updatedBy: '李四',
    updatedTime: '2026-01-11 14:30:00'
  },
  {
    id: 3,
    name: '用户列表接口',
    interfaceKey: 'API003',
    method: 'GET',
    baseUrl: '/api/user/list',
    headerTemplate: '{"Authorization": "Bearer token"}',
    inputParamTemplate: '{"page": 1, "size": 10}',
    responseParams: '{"code": 200, "data": {"list": [], "total": 0}}',
    status: 2,
    createdBy: '王五',
    createdTime: '2026-01-12 09:15:00',
    updatedBy: '赵六',
    updatedTime: '2026-01-15 16:20:00'
  }
]
// 新增接口
const handleAdd = () => {
  formMode.value = 'add'
  formData.value = null
  formDialogVisible.value = true
}

// 编辑接口
const handleEdit = (row: any) => {
  formMode.value = 'edit'
  formData.value = row
  formDialogVisible.value = true
}

// 查看详情
const handleDetail = (row: any) => {
  formMode.value = 'detail'
  formData.value = row
  formDialogVisible.value = true
}

// 删除接口
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该接口吗？', '提示', {
      type: 'warning'
    })

    // 调用删除API
    await deleteApiSetting(row.id)
    ElMessage.success('删除成功')
    tableListRef.value.getList()
  } catch (error) {
    console.error('删除接口设置失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 表格配置
const tableConfig: any = reactive({
  // 查询参数
  queryParams: {
    name: ''
  },

  // 搜索表单配置
  searchForm: {
    maxItemsPerRow: 3,
    items: [
      {
        field: 'name',
        label: '接口名称',
        type: 'input',
        placeholder: '请输入接口名称',
        width: '200px'
      }
    ]
  },

  // 操作按钮配置
  actions: [
    {
      label: '新增',
      type: 'primary',
      icon: 'ep:plus',
      handler: handleAdd,
      show: () => checkPermi(['print:sap-api-config:create']),
    }
  ],

  // 表格配置
  table: {
    selection: true,
    index: true,
    columns: [
      {
        prop: 'name',
        label: '接口名称',
        minWidth: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'interfaceKey',
        label: '接口编码',
        width: 180,
        showOverflowTooltip: true
      },
      {
        prop: 'baseUrl',
        label: '接口地址',
        minWidth: 200,
        showOverflowTooltip: true
      },
      {
        prop: 'method',
        label: '请求方式',
        width: 100,
        align: 'center',
        render: (_: any, { row }: { row: any }) => {
          const methodColors: Record<
            string,
            'primary' | 'success' | 'warning' | 'danger' | 'info'
          > = {
            GET: 'success',
            POST: 'primary',
            PUT: 'warning',
            DELETE: 'danger',
            PATCH: 'info'
          }
          return h(
            ElTag,
            {
              type: methodColors[row.method] || 'info',
              effect: 'light',
              size: 'small',
              'disable-transitions': true
            },
            () => row.method
          )
        }
      },
      {
        prop: 'headerTemplate',
        label: 'Header信息',
        minWidth: 150,
        showOverflowTooltip: true,
        // formatter: (row: any) => {
        //   try {
        //     const headers = JSON.parse(row.headerTemplate || '{}')
        //     return Object.keys(headers).length > 0 ? '已配置' : '未配置'
        //   } catch {
        //     return row.headerTemplate || '未配置'
        //   }
        // }
      },
      {
        prop: 'inputParamTemplate',
        label: '入参信息',
        minWidth: 150,
        showOverflowTooltip: true,
        // formatter: (row: any) => {
        //   try {
        //     const params = JSON.parse(row.inputParamTemplate || '{}')
        //     return Object.keys(params).length > 0 ? '已配置' : '未配置'
        //   } catch {
        //     return row.inputParamTemplate || '未配置'
        //   }
        // }
      },
      {
        prop: 'creatorName',
        label: '创建人',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'createTime',
        label: '创建时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.createTime)
      },
      {
        prop: 'updaterName',
        label: '修改人',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'updateTime',
        label: '修改时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.updateTime)
      }
    ],
    actions: [
      {
        label: '详情',
        type: 'primary',
        link: true,
        handler: handleDetail
      },
      {
        label: '编辑',
        type: 'primary',
        link: true,
        handler: handleEdit
      },
      {
        label: '删除',
        type: 'danger',
        link: true,
        handler: handleDelete
      }
    ]
  },

  // 分页配置
  pagination: {
    pageSize: 10,
    show: true
  },

  // 设置
  settings: {
    refresh: true,
    download: false,
    // download: async () => {
    //   try {
    //     const queryParams = tableConfig.queryParams
    //     const data = await exportApiSetting(queryParams)
    //     download.excel(data, 'SAP接口设置.xls')
    //     ElMessage.success('导出成功')
    //   } catch (error) {
    //     console.error('导出接口设置失败:', error)
    //     ElMessage.error('导出失败')
    //   }
    // },
    print: true,
    size: true,
    columns: true,
    fullscreen: true
  },

  // API配置
  api: {
    getList: async (params: any) => {
      try {
        const response = await getApiSettingPage(params)
        return response
      } catch (error) {
        console.error('获取接口设置列表失败:', error)
        ElMessage.error('获取数据失败')
        throw error
      }
    }
  }
})

// 表单提交成功处理
const handleFormSuccess = async (data: any) => {
  try {
    let response = null
    if (data.id) {
      // 编辑
      response = await updateApiSetting(data)
      ElMessage.success('更新成功')
    } else {
      // 新增
      response = await createApiSetting(data)
      ElMessage.success('新增成功')
    }

    formDialogVisible.value = false
    tableListRef.value.getList()
  } catch (error) {
    console.error('保存接口设置失败:', error)
    ElMessage.error('保存失败')
  }
}
onMounted(() => {
  // 初始化时调用 getList()
  tableListRef.value.getList()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}
</style>
