"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUserInfo = getUserInfo;
exports.getAppOptions = getAppOptions;
exports.getProjectTree = getProjectTree;
exports.getTextFile = getTextFile;
exports.getProjectSharedLibs = getProjectSharedLibs;
exports.getProjectThirdLibs = getProjectThirdLibs;
exports.createProjectVersionId = createProjectVersionId;
const axios_1 = __importDefault(require("axios"));
const BASE_URL = 'https://me.keytop.cn';
const SERVICE_CENTER_ID = '45e441e2cd7e453a97cdccd802042f38';
const DEFAULT_APP_ID = '76cd1d1556e6475ba6e84330c05d9351';
const DIRECT_CONNECT = process.env.MIDCLI_USE_PROXY !== '1';
function getHeaders(authorization) {
    return {
        authorization,
        'Content-Type': 'application/json',
    };
}
function getRequestConfig(authorization) {
    return {
        headers: getHeaders(authorization),
        ...(DIRECT_CONNECT ? { proxy: false } : {}),
    };
}
/**
 * 获取当前操作人信息
 */
async function getUserInfo(authorization) {
    const url = `${BASE_URL}/kt_midend/user/info`;
    const response = await axios_1.default.get(url, {
        ...getRequestConfig(authorization),
    });
    if (response.data.code === '2000' && response.data.data) {
        const userData = response.data.data;
        return {
            userId: userData.id,
            userName: userData.name,
            departmentName: userData.departmentName,
            email: userData.email,
            phone: userData.phone,
        };
    }
    throw new Error(response.data.message || '获取用户信息失败');
}
/**
 * 获取应用选择列表
 */
async function getAppOptions(authorization) {
    const url = `${BASE_URL}/kt_midend/app/selectOptions`;
    const response = await axios_1.default.get(url, {
        params: { serviceCenterId: SERVICE_CENTER_ID },
        ...getRequestConfig(authorization),
    });
    if (response.data.code === '2000' && response.data.data) {
        return response.data.data;
    }
    throw new Error(response.data.message || '获取应用列表失败');
}
async function getProjectTree(projectVersionId, authorization) {
    const url = `${BASE_URL}/fms-webide-server/getProjectTree`;
    const response = await axios_1.default.get(url, {
        params: { projectVersionId },
        ...getRequestConfig(authorization),
    });
    if (response.data.code === '2000' && response.data.data) {
        return response.data.data;
    }
    throw new Error(response.data.message || '获取项目树失败');
}
async function getTextFile(projectVersionId, fileId, authorization, lockId = '') {
    const url = `${BASE_URL}/fms-webide-server/getTextFile`;
    const response = await axios_1.default.get(url, {
        params: { projectVersionId, fileId, lockId },
        ...getRequestConfig(authorization),
    });
    if (response.data.code !== '2000') {
        throw new Error(response.data.message || `获取文件内容失败: ${fileId}`);
    }
    const data = response.data.data;
    if (typeof data === 'string') {
        return data;
    }
    if (typeof data?.content === 'string') {
        return data.content;
    }
    if (typeof data?.text === 'string') {
        return data.text;
    }
    return '';
}
async function getProjectSharedLibs(projectVersionId, authorization) {
    const url = `${BASE_URL}/fms-webide-server/getList`;
    const response = await axios_1.default.get(url, {
        params: { projectVersionId },
        ...getRequestConfig(authorization),
    });
    if (response.data.code !== '2000') {
        throw new Error(response.data.message || '获取共享库列表失败');
    }
    const list = Array.isArray(response.data.data) ? response.data.data : [];
    return list
        .filter((item) => item?.pid && item?.msAlias)
        .map((item) => ({
        pid: item.pid,
        msAlias: item.msAlias,
        version: item.revisionVersionNo || item.versionNo || item.libVersionNo || item.version,
    }));
}
async function getProjectThirdLibs(projectVersionId, authorization) {
    const url = `${BASE_URL}/fms-webide-server/use/getThirdLib`;
    const response = await axios_1.default.get(url, {
        params: { projectVersionId },
        ...getRequestConfig(authorization),
    });
    if (response.data.code !== '2000') {
        throw new Error(response.data.message || '获取第三方开源库列表失败');
    }
    const list = Array.isArray(response.data.data) ? response.data.data : [];
    return list
        .filter((item) => item?.libName)
        .map((item) => ({
        libName: item.libName,
        libVersion: item.libVersion || item.version || 'latest',
    }));
}
/**
 * 创建项目
 */
async function createProject(msId, appId, authorization, userInfo, description = '') {
    const url = `${BASE_URL}/sms-console/project/manager`;
    const data = {
        serviceCenterId: SERVICE_CENTER_ID,
        appId,
        msId,
        developers: [{ userId: userInfo.userId, userName: userInfo.userName }],
        readonlyUsers: [],
        description,
    };
    const response = await axios_1.default.post(url, data, {
        ...getRequestConfig(authorization),
    });
    if (response.data.code === '2000') {
        return;
    }
    throw new Error(response.data.message || '创建项目失败');
}
/**
 * 查询项目信息
 */
async function queryProject(msId, authorization) {
    const url = `${BASE_URL}/sms-console/project/manager`;
    const response = await axios_1.default.get(url, {
        params: {
            pageNum: 1,
            pageSize: 10,
            serviceCenterId: '',
            appId: '',
            keyword: msId,
        },
        ...getRequestConfig(authorization),
    });
    if (response.data.code === '2000') {
        const project = response.data.data?.data?.find((p) => p.msId === msId);
        if (project) {
            return { projectId: project.projectId };
        }
    }
    throw new Error(`未找到项目: ${msId}`);
}
/**
 * 创建Minor版本
 */
async function createMinorVersion(projectId, authorization, description) {
    const url = `${BASE_URL}/sms-console/project/manager/minorVersion`;
    const data = {
        versionNo: '1.0',
        description: description || '自动创建版本',
        projectId,
    };
    const response = await axios_1.default.post(url, data, {
        ...getRequestConfig(authorization),
    });
    if (response.data.code === '2000') {
        return response.data.data?.id;
    }
    throw new Error(response.data.message || '创建Minor版本失败');
}
/**
 * 查询版本信息
 */
async function queryVersions(projectId, authorization) {
    const url = `${BASE_URL}/sms-console/project/queryMinorServices`;
    const response = await axios_1.default.get(url, {
        params: { projectId },
        ...getRequestConfig(authorization),
    });
    if (response.data.code === '2000') {
        return response.data.data || [];
    }
    throw new Error(response.data.message || '查询版本信息失败');
}
/**
 * 创建Revision版本
 */
async function createRevisionVersion(minorVersionId, projectId, authorization, description) {
    const url = `${BASE_URL}/sms-console/project/dev/revisionVersion`;
    const data = {
        minorVersionId,
        versionId: '',
        description: description || '自动创建Revision版本',
    };
    const response = await axios_1.default.post(url, data, {
        ...getRequestConfig(authorization),
    });
    if (response.data.code === '2000') {
        // 尝试多种方式获取 revisionVersionId
        const respData = response.data;
        const revisionVersionId = respData.data?.revisionVersionId
            || respData.data?.id
            || respData.revisionVersionId;
        if (revisionVersionId) {
            return revisionVersionId;
        }
        // data 为 null 时，使用 queryVersions 接口查询
        const versionsResp = await axios_1.default.get(`${BASE_URL}/sms-console/project/dev/queryVersions`, {
            params: { projectId },
            ...getRequestConfig(authorization),
        });
        // 从返回数据中获取最新的 revisionVersionId
        const versionsData = versionsResp.data.data;
        if (versionsData && versionsData.length > 0) {
            // 找到对应的 minorVersion，获取最新的 revision
            const minorVersionData = versionsData.find((v) => v.minorVersionId === minorVersionId);
            if (minorVersionData?.revisionList?.length > 0) {
                const latestRevision = minorVersionData.revisionList[minorVersionData.revisionList.length - 1];
                return latestRevision.revisionVersionId;
            }
            // 尝试其他可能的结构
            if (minorVersionData?.revisionVersionId) {
                return minorVersionData.revisionVersionId;
            }
        }
        // 尝试从顶层获取
        const latestVersion = versionsData?.[versionsData.length - 1];
        if (latestVersion?.revisionVersionId) {
            return latestVersion.revisionVersionId;
        }
    }
    throw new Error(response.data.message || '创建Revision版本失败');
}
/**
 * 创建 projectVersionId（完整流程）
 * 1. 获取用户信息
 * 2. 检查项目是否存在（存在则终止）
 * 3. 创建项目
 * 4. 创建 Minor 版本
 * 5. 创建 Revision 版本
 */
async function createProjectVersionId(msId, authorization, appId = DEFAULT_APP_ID, description = '', minorVersionDescription = '', revisionVersionDescription = '') {
    // 1. 获取用户信息
    const userInfo = await getUserInfo(authorization);
    // 2. 检查项目是否已存在
    try {
        const project = await queryProject(msId, authorization);
        // 项目已存在，直接报错终止
        throw new Error(`项目ID [${msId}] 已存在，请使用其他名称`);
    }
    catch (error) {
        // 如果是"项目已存在"的错误，继续抛出
        if (error.message?.includes('已存在')) {
            throw error;
        }
        // 其他错误（未找到项目），继续创建流程
    }
    // 3. 创建新项目
    await createProject(msId, appId, authorization, userInfo, description);
    const project = await queryProject(msId, authorization);
    const projectId = project.projectId;
    // 4. 查询现有版本
    const versions = await queryVersions(projectId, authorization);
    let minorVersion = versions.find((v) => v.minorVersionNo === '1.0');
    let minorVersionId;
    if (minorVersion) {
        minorVersionId = minorVersion.minorVersionId;
    }
    else {
        // 创建新的 Minor 版本
        minorVersionId = await createMinorVersion(projectId, authorization, minorVersionDescription);
        if (!minorVersionId) {
            const newVersions = await queryVersions(projectId, authorization);
            minorVersion = newVersions.find((v) => v.minorVersionNo === '1.0');
            minorVersionId = minorVersion?.minorVersionId;
        }
    }
    if (!minorVersionId) {
        throw new Error('无法获取 Minor 版本 ID');
    }
    // 5. 创建 Revision 版本
    const projectVersionId = await createRevisionVersion(minorVersionId, projectId, authorization, revisionVersionDescription);
    if (!projectVersionId) {
        throw new Error('无法获取 projectVersionId');
    }
    return {
        projectVersionId,
        projectId,
        minorVersionId,
        appId,
    };
}
//# sourceMappingURL=projectApi.js.map