<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="API授权" :width="adaptiveWidth" @ok="handleSubmit" :showFooter="showFooter">
    <a-table :data-source="APIList" :columns="columns" :row-selection="rowSelection" :row-key="(record) => record.id"> </a-table>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, onMounted, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { apiManageList, apiPermPagelist, bathAddApiPerm } from './user.api';
import { useDrawerAdaptiveWidth } from '/@/hooks/jeecg/useAdaptiveWidth';
import { message, Modal } from 'ant-design-vue';
// 声明Emits
const emit = defineEmits(['success', 'register']);
const showFooter = ref(true);
const APIList = ref([]);
const selectedRowKeys = ref<any>([]);
const userID = ref('');
const columns = [
  {
    title: 'API名称',
    dataIndex: 'apiName',
    key: 'apiName',
    align: 'center',
  },
  {
    title: '请求路径',
    dataIndex: 'reqUrl',
    key: 'reqUrl',
    align: 'center',
  },
  {
    title: 'HTTP方法',
    dataIndex: 'reqMethod',
    key: 'reqMethod',
    align: 'center',
  },
];
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({ confirmLoading: false });
  userID.value = data.userID;
  await getAllApiList();
  await getPermApiList();
});
const { adaptiveWidth } = useDrawerAdaptiveWidth();
// 行选择配置
const rowSelection = {
  selectedRowKeys,
  onChange: (selectedKeys) => {
    selectedRowKeys.value = selectedKeys;
  },
};
//表单提交事件
async function handleSubmit() {
  try {
    setModalProps({ confirmLoading: true });
    // 参数
    const params = {
      apiIdList: selectedRowKeys.value.length > 0 ? selectedRowKeys.value.join(',') : {}, // 转换为逗号分隔的字符串
      userId: userID.value, // 用户ID
    };
    const response = await bathAddApiPerm(params);
    console.log('提交的ID:', selectedRowKeys.value);
    console.log('API响应:', response);
    message.success('提交成功');
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
async function getPermApiList() {
  const result = await apiPermPagelist({ pageNo: 1, pageSize: 1000, userId: userID.value });
  const permApiIds = result.records?.map((item) => String(item.apiId)) || [];
  selectedRowKeys.value = [...permApiIds];
  return result;
}
// 获取接口列表
async function getAllApiList() {
  const result = await apiManageList({ pageNo: 1, pageSize: 1000 });
  APIList.value = result.records;
}
onMounted(async () => {
  await getAllApiList();
});
</script>
<style scoped>
.selected-info {
  background: #cccc;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}
</style>