<template>
  <div style="background-color: #ececec; padding: 20px;height: 95vh;">
    <a-row :gutter="[16,16]" style="height: 100%;">
      <a-col :span="leftWidth" style="height: 100%;">
        <a-card title="数据源配置" :bordered="false" style="height:100%;overflow-y:auto">
          <a-form
            ref="formRef"
            :model="formState"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-item label="数据源名称" name="sourceName">
              <a-input v-model:value="formState.sourceName" placeholder="请输入数据源名称" />
            </a-form-item>
            <a-form-item label="数据源类型" name="sourceType">
              <a-radio-group v-model:value="formState.sourceType">
                <a-radio :value="1">REST</a-radio>
                <a-radio :value="2">WebSocket</a-radio>
                <a-radio :value="3">GraphQL</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="接口地址" name="url">
              <a-input v-model:value="formState.url" placeholder="请输入完整的接口地址" />
            </a-form-item>
            <a-form-item label="请求方法" name="method">
              <a-radio-group v-model:value="formState.method">
                <a-radio :value="1">GET</a-radio>
                <a-radio :value="2">POST</a-radio>
                <a-radio :value="3">PUT</a-radio>
                <a-radio :value="4">DELETE</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="请求参数" name="params">
              <a-textarea 
                v-model:value="formState.params" 
                placeholder="请输入JSON格式的请求参数"
                :rows="3"
              />
            </a-form-item>
            <a-form-item label="请求头" name="headers">
              <a-textarea 
                v-model:value="formState.headers" 
                placeholder="请输入JSON格式的请求头"
                :rows="2"
              />
            </a-form-item>
            <a-form-item label="响应格式" name="resType">
              <a-radio-group v-model:value="formState.resType">
                <a-radio :value="1">JSON</a-radio>
                <a-radio :value="2">XML</a-radio>
                <a-radio :value="3">Text</a-radio>
                <a-radio :value="4">File</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="描述信息" name="description">
              <a-textarea 
                v-model:value="formState.description" 
                placeholder="请输入数据源描述"
                :rows="2"
              />
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 24 }" style="text-align: center;">
              <a-space>
                <a-button type="primary" @click="testConnection">测试连接</a-button>
                <a-button @click="saveDataSource">保存配置</a-button>
                <a-button danger @click="resetForm">重置</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>

      <a-col :span="24-leftWidth" style="height: 100%;">
        <a-card  :bordered="false" style="height:100%;display:flex;flex-direction:column">
          <template #title>
            <a-button type="link" @click="hideAndShow()" size="large">{{ leftWidth ? '隐藏' : '显示' }}数据源配置</a-button>
          </template>
          <template #extra>
            <a-space>
              <a-input-search 
                v-model:value="filterName" 
                placeholder="搜索数据源" 
                style="width: 200px"
                @search="handleSearch"
              />
              <a-button type="primary" @click="fetchData">获取数据</a-button>
              <a-button @click="exportData">导出数据</a-button>
            </a-space>
          </template>
          
          <div style="flex:1;min-height:0">
            <vxe-table
              ref="tableRef"
              border
              stripe
              height="auto"
              :loading="loading"
              :column-config="{resizable: true}"
              :row-config="{isHover: true, height: 50}"
              :checkbox-config="{labelField: 'id', highlight: true, range: true}"
              :data="tableData"
              :sort-config="{trigger: 'cell'}"
              @checkbox-change="handleSelectionChange"
              @checkbox-all="handleSelectionChange"
            >
              <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>
              <vxe-column type="seq" width="70" title="序号" fixed="left"></vxe-column>
              
              <vxe-column field="sourceName" title="名称" width="150" sortable>
                <template #default="{ row }">
                  <a-tooltip :title="row.sourceName">
                    <span>{{ row.sourceName }}</span>
                  </a-tooltip>
                </template>
              </vxe-column>
              
              <vxe-column field="type" title="类型" width="120" sortable>
                <template #default="{ row }">
                  <a-tag :color="getTypeColor(row.type)">{{ getTypeText(row.type) }}</a-tag>
                </template>
              </vxe-column>
              
              <vxe-column field="url" title="接口地址" min-width="200" show-overflow>
                <template #default="{ row }">
                  <a-tooltip :title="row.url">
                    <span>{{ row.url }}</span>
                  </a-tooltip>
                </template>
              </vxe-column>
              
              <vxe-column field="method" title="方法" width="100" sortable>
                <template #default="{ row }">
                  <a-tag :color="getMethodColor(row.method)">{{ getMethodText(row.method) }}</a-tag>
                </template>
              </vxe-column>
              
              <vxe-column field="status" title="状态" width="100" sortable>
                <template #default="{ row }">
                  <a-badge :status="row.status === 1 ? 'processing' : 'error'" :text="row.status === 1 ? '正常' : '异常'" />
                </template>
              </vxe-column>
              
              <vxe-column field="responseTime" title="响应时间" width="120" sortable>
                <template #default="{ row }">
                  <span>{{ row.responseTime }}ms</span>
                </template>
              </vxe-column>
              
              <vxe-column field="lastUpdate" title="最后更新" width="180" sortable>
                <template #default="{ row }">
                  <span>{{ formatDate(row.lastUpdate) }}</span>
                </template>
              </vxe-column>
              
              <vxe-column field="description" title="描述" min-width="200" show-overflow>
                <template #default="{ row }">
                  <a-tooltip :title="row.description">
                    <span>{{ row.description }}</span>
                  </a-tooltip>
                </template>
              </vxe-column>
              
              <vxe-column title="操作" width="150" fixed="right">
                <template #default="{ row,rowIndex }">
                  <a-space>
                    <a-button type="link" size="small" @click="editDataSource(row,rowIndex)">编辑</a-button>
                    <a-button type="link" size="small" @click="testSingleConnection(row)">测试</a-button>
                    <a-popconfirm
                      title="确定要删除这个数据源吗？"
                      @confirm="deleteDataSource(row)"
                    >
                      <a-button type="link" size="small" danger>删除</a-button>
                    </a-popconfirm>
                  </a-space>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          
          <template #footer>
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>已选择 {{ selectedRows.length }} 项</span>
              <a-pagination
                v-model:current="pagination.current"
                v-model:page-size="pagination.pageSize"
                :total="pagination.total"
                show-size-changer
                show-quick-jumper
                :show-total="total => `共 ${total} 条`"
                @change="handlePageChange"
              />
            </div>
          </template>
        </a-card>
      </a-col>
    </a-row>
    <ApiRes ref="refApiRes"></ApiRes>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import type { VxeTableInstance } from 'vxe-table';
import ApiRes from './compoents/ApiRes.vue'
import { index } from 'mathjs';

// 定义类型
interface DataSource {
  id: string;
  sourceName: string;
  type: number;
  url: string;
  method: number;
  status: number;
  responseTime: number;
  lastUpdate: string;
  description: string;
  params?: string;
  headers?: string;
  resType?: number;
}

interface Pagination {
  current: number;
  pageSize: number;
  total: number;
}

// 响应式数据
const formState = ref({
  sourceName: '',
  sourceType: 1,
  url: 'https://api.example.com/users',
  method: 1,
  resType: 1,
  params: '{}',
  headers: '{"Content-Type": "application/json"}',
  description: ''
});

const loading = ref(false);
const filterName = ref('');
const tableData = ref<DataSource[]>([]);
const selectedRows = ref<DataSource[]>([]);
const leftWidth = ref(8);
const tableRef = ref<VxeTableInstance>();

const refApiRes = ref()
const curRowInd = ref()

const labelCol = { span: 6 };
const wrapperCol = { span: 18 };

const pagination = reactive<Pagination>({
  current: 1,
  pageSize: 20,
  total: 0
});

// 模拟数据
const mockData: DataSource[] = [
  {
    id: '1',
    sourceName: '用户登录接口',
    type: 1,
    url: 'http://47.98.203.68:8080/stm/survey/surveyTpl/list',
    method: 1,
    status: 1,
    responseTime: 120,
    lastUpdate: '2024-01-15 10:30:00',
    description: '获取用户基本信息'
  },
  {
    id: '2',
    sourceName: '订单数据接口',
    type: 1,
    url: 'https://api.example.com/orders',
    method: 2,
    status: 1,
    responseTime: 80,
    lastUpdate: '2024-01-15 09:15:00',
    description: '提交订单信息'
  },
  {
    id: '3',
    sourceName: '商品列表接口',
    type: 1,
    url: 'https://api.example.com/products',
    method: 1,
    status: 0,
    responseTime: 200,
    lastUpdate: '2024-01-14 16:45:00',
    description: '获取商品列表数据'
  }
];

// 方法定义
const getTypeText = (type: number) => {
  const typeMap = { 1: 'REST', 2: 'WebSocket', 3: 'GraphQL' };
  return typeMap[type as keyof typeof typeMap] || '未知';
};

const getTypeColor = (type: number) => {
  const colorMap = { 1: 'blue', 2: 'green', 3: 'orange' };
  return colorMap[type as keyof typeof colorMap] || 'default';
};

const getMethodText = (method: number) => {
  const methodMap = { 1: 'GET', 2: 'POST', 3: 'PUT', 4: 'DELETE' };
  return methodMap[method as keyof typeof methodMap] || '未知';
};

const getMethodColor = (method: number) => {
  const colorMap = { 1: 'green', 2: 'blue', 3: 'orange', 4: 'red' };
  return colorMap[method as keyof typeof colorMap] || 'default';
};

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN');
};

const handleSearch = () => {
  // 搜索逻辑
  if (filterName.value) {
    tableData.value = mockData.filter(item => 
      item.name.includes(filterName.value) || 
      item.url.includes(filterName.value)
    );
  } else {
    tableData.value = mockData;
  }
  pagination.total = tableData.value.length;
};

const handleSelectionChange = ({ records }: { records: DataSource[] }) => {
  selectedRows.value = records;
};

const handlePageChange = (page: number, pageSize: number) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  // 这里可以添加分页数据获取逻辑
};

const testConnection = async () => {
  if (!formState.value.url) {
    message.warning('请输入接口地址');
    return;
  }

  loading.value = true;
  try {
    // 模拟测试连接
    await new Promise(resolve => setTimeout(resolve, 1000));
    message.success('连接测试成功！');
  } catch (error) {
    message.error('连接测试失败！');
  } finally {
    loading.value = false;
  }
};

const saveDataSource = () => {
  if (!formState.value.sourceName) {
    message.warning('请输入数据源名称');
    return;
  }

  // 保存逻辑
  if(curRowInd.value!=undefined) {
    Object.assign(tableData.value[curRowInd.value], formState.value);
  } else {
    tableData.value.push(formState.value)
  }
 
  message.success('数据源配置保存成功！');
  resetForm();
};

const resetForm = () => {
  formState.value = {
    sourceName: '',
    sourceType: 1,
    url: 'https://api.example.com/users',
    method: 1,
    resType: 1,
    params: '{}',
    headers: '{"Content-Type": "application/json"}',
    description: ''
  };
};

const fetchData = () => {
  loading.value = true;
  // 模拟数据获取
  setTimeout(() => {
    tableData.value = mockData;
    pagination.total = mockData.length;
    loading.value = false;
    //message.success('数据获取成功！');
  }, 1000);
};

const exportData = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择要导出的数据');
    return;
  }
  message.info(`准备导出 ${selectedRows.value.length} 条数据`);
};

const editDataSource = (row: DataSource,rowIndex) => {
  leftWidth.value = 8 
  curRowInd.value = rowIndex
  Object.assign(formState.value, row);
  //message.info(`编辑数据源: ${row.sourceName}`);
};

const testSingleConnection = async(row: DataSource) => {
  //loading.value = true;
  // 模拟单个连接测试
  await refApiRes.value.hanleShowDrawer(row)
  // setTimeout(() => {
  //   loading.value = false;
  //   message.success(`数据源 "${row.sourceName}" 连接测试成功！`);
  // }, 800);
};

const deleteDataSource = (row: DataSource) => {
  tableData.value = tableData.value.filter(item => item.id !== row.id);
  message.success(`数据源 "${row.sourceName}" 删除成功！`);
};

const hideAndShow = () => {
  leftWidth.value = leftWidth.value ? 0 : 8;
};

// 生命周期
onMounted(() => {
  // 初始化时加载数据
  fetchData();
});
</script>

<style scoped>
:deep(.ant-card-body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.vxe-table) {
  font-size: 14px;
}

:deep(.vxe-table--render-wrapper) {
  height: 100% !important;
}
</style>