const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');
const { convertTsDeclareContentToXml } = require('./TsDeclareToXml');

// 从package.json中读取配置
function loadConfig() {
  const packageJsonPath = path.join(__dirname, '../../package.json');
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
  const uploadConfig = packageJson.uploadConfig || {};
  
  // 自动获取当前项目的src路径
  const projectRoot = path.join(__dirname, '../..');
  
  return {
    cloudUrl: uploadConfig.cloudUrl || 'https://me.keytop.cn/fms-webide-server/getProjectTree',
    tryLockUrl: uploadConfig.tryLockUrl || 'https://me.keytop.cn/fms-webide-server/tryLock',
    saveDraftUrl: uploadConfig.saveDraftUrl || 'https://me.keytop.cn/fms-webide-server/saveDraft',
    commitFileUrl: uploadConfig.commitFileUrl || 'https://me.keytop.cn/fms-webide-server/commitFile',
    createLocalLibUrl: uploadConfig.createLocalLibUrl || 'https://me.keytop.cn/fms-webide-server/createLocalLib',
    createServicesUrl: uploadConfig.createServicesUrl || 'https://me.keytop.cn/fms-webide-server/createService',
    createFolderUrl: uploadConfig.createFolderUrl || 'https://me.keytop.cn/fms-webide-server/createFileFolder/v2',
    removeServices: uploadConfig.removeServices || 'https://me.keytop.cn/fms-webide-server/removeService',
    removeServicesFolder: uploadConfig.removeServicesFolder || 'https://me.keytop.cn/fms-webide-server/removeFileFolder',
    removeLocalLib: uploadConfig.removeLocalLib || 'https://me.keytop.cn/fms-webide-server/removeLocalLib',
    projectVersionId: uploadConfig.projectVersionId || '',
    headers: {
      authorization: uploadConfig.authorization || ''
    },
    localRoot: path.join(projectRoot, 'src')
  };
}

const config = loadConfig();

function loadSharedLibConfig() {
  const packageJsonPath = path.join(__dirname, '../../package.json');
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
  const uploadCfg = packageJson.uploadConfig || {};
  return {
    getListUrl:
      uploadCfg.sharedLibGetListUrl ||
      uploadCfg.getListUrl ||
      'https://me.keytop.cn/fms-webide-server/getList',
    addUrl:
      uploadCfg.sharedLibAddUrl ||
      uploadCfg.addUrl ||
      'https://me.keytop.cn/fms-webide-server/add',
    managerUrl:
      uploadCfg.sharedLibManagerUrl ||
      uploadCfg.managerUrl ||
      'https://me.keytop.cn/sharedlib-console/project/manager',
    versionsUrl:
      uploadCfg.sharedLibVersionsUrl ||
      uploadCfg.versionsUrl ||
      'https://me.keytop.cn/sharedlib-console/project/manager/versions',
    projectVersionId: uploadCfg.projectVersionId || '',
    libs: Array.isArray(uploadCfg.sharedLibs)
      ? uploadCfg.sharedLibs
      : Array.isArray(uploadCfg.libs)
        ? uploadCfg.libs
        : [],
    headers: {
      authorization: uploadCfg.authorization || ''
    }
  };
}

function loadThirdLibConfig() {
  const packageJsonPath = path.join(__dirname, '../../package.json');
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
  const uploadCfg = packageJson.uploadConfig || {};
  return {
    getListUrl:
      uploadCfg.thirdLibGetListUrl ||
      'https://me.keytop.cn/fms-webide-server/use/getThirdLib',
    addUrl:
      uploadCfg.thirdLibAddUrl ||
      'https://me.keytop.cn/fms-webide-server/use/addThirdLib',
    projectVersionId: uploadCfg.projectVersionId || '',
    libs: Array.isArray(uploadCfg.thirdLibs)
      ? uploadCfg.thirdLibs
      : [],
    headers: {
      authorization: uploadCfg.authorization || ''
    }
  };
}

function parseVersionNo(versionNo) {
  const text = `${versionNo || ''}`.trim();
  const pure = text.split('-')[0];
  const parts = pure.split('.').map(n => Number(n) || 0);
  return [
    parts[0] || 0,
    parts[1] || 0,
    parts[2] || 0
  ];
}

function compareVersionDesc(a, b) {
  const va = parseVersionNo(a);
  const vb = parseVersionNo(b);
  for (let i = 0; i < 3; i += 1) {
    if (va[i] !== vb[i]) {
      return vb[i] - va[i];
    }
  }
  return 0;
}

async function queryLibProjectIdByPid(sharedCfg, pid) {
  const response = await axios.get(sharedCfg.managerUrl, {
    headers: sharedCfg.headers,
    params: {
      pageNum: 1,
      pageSize: 10,
      serviceCenterId: '',
      appId: '',
      keyword: pid
    }
  });
  const body = response.data || {};
  if (body.code !== '2000' || body.success !== true) {
    throw new Error(`查询共享库项目失败: ${pid} ${body.message || body.msg || body.code}`);
  }
  const list = body?.data?.data || [];
  if (!Array.isArray(list) || !list.length) {
    throw new Error(`未查询到共享库项目: ${pid}`);
  }
  const matched = list.find(item => item.pid === pid) || list[0];
  if (!matched?.projectId) {
    throw new Error(`共享库项目缺少projectId: ${pid}`);
  }
  return matched.projectId;
}

async function queryLatestLibVersionId(sharedCfg, projectId, pid) {
  const response = await axios.get(sharedCfg.versionsUrl, {
    headers: sharedCfg.headers,
    params: {
      projectId
    }
  });
  const body = response.data || {};
  if (body.code !== '2000' || body.success !== true) {
    throw new Error(`查询共享库版本失败: ${pid} ${body.message || body.msg || body.code}`);
  }
  const minors = Array.isArray(body.data) ? body.data : [];
  if (!minors.length) {
    throw new Error(`共享库无可用版本: ${pid}`);
  }
  const allRevisions = [];
  for (const minor of minors) {
    const revisions = Array.isArray(minor?.revisionList) ? minor.revisionList : [];
    for (const rev of revisions) {
      allRevisions.push(rev);
    }
  }
  if (!allRevisions.length) {
    throw new Error(`共享库无修订版本: ${pid}`);
  }
  allRevisions.sort((a, b) =>
    compareVersionDesc(a?.revisionVersionNo, b?.revisionVersionNo)
  );
  const latest = allRevisions[0];
  if (!latest?.revisionVersionId) {
    throw new Error(`共享库最新版本缺少revisionVersionId: ${pid}`);
  }
  return latest.revisionVersionId;
}

async function syncSharedLibs() {
  const sharedCfg = loadSharedLibConfig();
  if (!sharedCfg.projectVersionId || !sharedCfg.headers.authorization) {
    console.log('共享库上传跳过: 缺少配置');
    return;
  }
  if (!sharedCfg.libs.length) {
    console.log('共享库上传跳过: libs 为空');
    return;
  }
  const listResponse = await axios.get(
    `${sharedCfg.getListUrl}?projectVersionId=${sharedCfg.projectVersionId}`,
    { headers: sharedCfg.headers }
  );
  const listBody = listResponse.data || {};
  if (listBody.code !== '2000' || listBody.success !== true) {
    throw new Error(`查询共享库失败: ${listBody.message || listBody.msg || listBody.code}`);
  }
  const existing = Array.isArray(listBody.data) ? listBody.data : [];
  const existingMap = new Map(
    existing.map(item => [`${item.pid || ''}::${item.msAlias || ''}`, item])
  );
  let uploadCount = 0;
  for (const lib of sharedCfg.libs) {
    const key = `${lib.pid || ''}::${lib.msAlias || ''}`;
    if (existingMap.has(key)) {
      console.log(`共享库已存在，跳过: ${lib.pid} (${lib.msAlias})`);
      continue;
    }
    if (!lib?.pid || !lib?.msAlias) {
      throw new Error('共享库配置必须包含 pid 和 msAlias');
    }
    const libProjectId = await queryLibProjectIdByPid(sharedCfg, lib.pid);
    const libVersionId = await queryLatestLibVersionId(sharedCfg, libProjectId, lib.pid);
    const payload = {
      libProjectId,
      libVersionId,
      pid: lib.pid,
      projectVersionId: sharedCfg.projectVersionId,
      msAlias: lib.msAlias
    };
    const addResponse = await axios.post(sharedCfg.addUrl, payload, {
      headers: {
        ...sharedCfg.headers,
        'content-type': 'application/json'
      }
    });
    const addBody = addResponse.data || {};
    if (addBody.code !== '2000' || addBody.success !== true) {
      throw new Error(
        `上传共享库失败: ${lib.pid} (${lib.msAlias}) ${addBody.message || addBody.msg || addBody.code}`
      );
    }
    uploadCount += 1;
    console.log(`共享库上传成功: ${lib.pid} (${lib.msAlias})`);
  }
  console.log(`共享库处理完成，新增数量=${uploadCount}`);
}

async function syncThirdLibs() {
  const thirdCfg = loadThirdLibConfig();
  if (!thirdCfg.projectVersionId || !thirdCfg.headers.authorization) {
    console.log('第三方开源库上传跳过: 缺少配置');
    return;
  }
  if (!thirdCfg.libs.length) {
    console.log('第三方开源库上传跳过: thirdLibs 为空');
    return;
  }
  const listResponse = await axios.get(
    `${thirdCfg.getListUrl}?projectVersionId=${thirdCfg.projectVersionId}`,
    { headers: thirdCfg.headers }
  );
  const listBody = listResponse.data || {};
  if (listBody.code !== '2000' || listBody.success !== true) {
    throw new Error(`查询第三方开源库失败: ${listBody.message || listBody.msg || listBody.code}`);
  }
  const existing = Array.isArray(listBody.data) ? listBody.data : [];
  const existingNameSet = new Set(
    existing
      .map(item => `${item?.libName || ''}`.trim().toLowerCase())
      .filter(Boolean)
  );
  let uploadCount = 0;
  for (const lib of thirdCfg.libs) {
    if (!lib?.libName) {
      throw new Error('thirdLibs 配置必须包含 libName');
    }
    const libName = `${lib.libName}`.trim();
    const libVersion = `${lib.libVersion || 'latest'}`.trim();
    const key = libName.toLowerCase();
    if (existingNameSet.has(key)) {
      console.log(`第三方开源库已存在，跳过: ${libName}`);
      continue;
    }
    const payload = {
      projectVersionId: thirdCfg.projectVersionId,
      libId: '',
      libName,
      libVersion
    };
    const addResponse = await axios.post(thirdCfg.addUrl, payload, {
      headers: {
        ...thirdCfg.headers,
        'content-type': 'application/json'
      }
    });
    const addBody = addResponse.data || {};
    if (addBody.code !== '2000' || addBody.success !== true) {
      throw new Error(`上传第三方开源库失败: ${libName} ${addBody.message || addBody.msg || addBody.code}`);
    }
    uploadCount += 1;
    existingNameSet.add(key);
    console.log(`第三方开源库上传成功: ${libName}@${libVersion}`);
  }
  console.log(`第三方开源库处理完成，新增数量=${uploadCount}`);
}

// 获取云端文件列表
async function getCloudFileList() {
  try {
    const response = await axios.get(`${config.cloudUrl}?projectVersionId=${config.projectVersionId}`, {
      headers: config.headers
    });
    
    if (response.data.code === '2000' && response.data.success) {
      return response.data.data.projectTree;
    } else {
      throw new Error('获取云端文件列表失败');
    }
  } catch (error) {
    console.error('获取云端文件列表时发生错误:', error);
    throw error;
  }
}

// 解析云端文件列表，筛选出Services下的代码文件
function parseCloudServiceFiles(projectTree) {
  let file={
    servicesFiles:[],
    localLibFiles:[],
    globalFiles:[]
  }
  const globalNode = projectTree.find(node => node.type === 'Global');
  if (globalNode&&globalNode.children) {
     globalNode.children.forEach(service => {
      file.globalFiles.push(service);
    });
  }
  const servicesNode = projectTree.find(node => node.type === 'Services');
  if (servicesNode&&servicesNode.children) {
     servicesNode.children.forEach(service => {
      file.servicesFiles.push(service);
    });
  }

  const localLibs = projectTree.find(node => node.type === 'LocalLibs');
  if (localLibs&&localLibs.children) {
    localLibs.children.forEach(service => {
      file.localLibFiles.push(service);
    });
  }
  return file;
}

// 读取本地目录的所有文件
function readLocalFiles(dir) {
  const files = [];
  const entries = fs.readdirSync(dir, { withFileTypes: true });
  
  entries.forEach(entry => {
    const fullPath = path.join(dir, entry.name);
    if (entry.isFile()) {
      files.push(entry.name);
    }
  });
  
  return files;
}

// 调用tryLock接口获取文件id
async function tryLockFile(fileId) {
  try {
    const response = await axios.get(`${config.tryLockUrl}?projectVersionId=${config.projectVersionId}&fileId=${fileId}`, {
      headers: config.headers
    });
    
   // console.log(`tryLock响应:`, response.data);
    return response.data;
  } catch (error) {
    console.error(`调用tryLock接口时发生错误:`, error);
    return null;
  }
}

// 主函数
async function main() {
  try {
    // 验证配置
    if (!config.projectVersionId) {
      console.error('错误: 请在package.json的uploadConfig中配置projectVersionId');
      console.error('提示: 打开中台项目点击开发进入IDE，复制浏览器地址参数`projectVersionId`');
      return;
    }
    
    if (!config.headers.authorization) {
      console.error('错误: 请在package.json的uploadConfig中配置authorization');
      console.error('提示: 按F12进入开发者工具选择网络复制请求头参数`authorization`头信息');
      return;
    }

    await syncSharedLibs();
    await syncThirdLibs();
    
    console.log(`开始获取中台文件列表;项目Id:${config.projectVersionId}`);
    console.log(`本地src路径:${config.localRoot}`);
    const projectTree = await getCloudFileList();
    const cloudServiceFiles = parseCloudServiceFiles(projectTree);
    console.log(`中台文件列表信息:`,cloudServiceFiles);
    console.log(`开始读取本地Services文件...`);
    await handInit(cloudServiceFiles);
    let localRoot=`${config.localRoot}\\services`;
     //删除services
    await checkAndRemoveNonExistent(cloudServiceFiles,localRoot);
    //删除locallib
    await checkAndRemoveLocalLib(cloudServiceFiles);
    //新增修改services
    await handSevices(cloudServiceFiles,localRoot);
    //新增修改locallib
    await handLocalLib(cloudServiceFiles);
   
    console.log('检测完成');
  } catch (error) {
    console.error('执行过程中发生错误:', error);
  }
}
/**
 * 提交Init文件
 */
async function handInit(cloudServiceFiles) {
  let localRoot=`${config.localRoot}\\init`;
  const localInitFiles = readLocalFiles(localRoot);
   
  console.log('检测本地文件是否在中台Init里面...');
    for (const localFileName of localInitFiles) {
      if(localFileName!='initScript.ts'){
         continue;
      }
      // 检查本地文件是否在云端services里面
      console.log(`开始检测文件：${localFileName}`);
     
      let serviceName=localFileName.split('.')[0].toLowerCase();
      let cloudFile = cloudServiceFiles.globalFiles.find(service => service.code.toLowerCase()==serviceName);
    
      if(!cloudFile){
        console.log(`文件 ${localFileName} 在中台不存在`);
        continue;
       
      }
      let isLocked=true;
      if(cloudFile.versionStatus&&!cloudFile.versionStatus.locked){//未锁定
          isLocked=false;
          console.log(`文件开始锁定${localFileName}...`);
          let lockResult=  await tryLockFile(cloudFile.key);
          if(lockResult&&lockResult.code=='2000'&&lockResult.data){//锁定成功
            console.log(`文件 ${localFileName} 已锁定,lockId:${lockResult.data.id}`);
            cloudFile.versionStatus.locked=true;
            cloudFile.versionStatus.lockId=lockResult.data.id;
            isLocked=true;
          }else{
            console.log(`文件 ${localFileName} 锁定失败`);
          }
        
      }
      if(!isLocked){
        console.log(`文件 ${localFileName} 锁定失败`);
        continue;
      }
      //提交修改
      console.log(`文件开始提交修改${localFileName}...`);
      let saveResult=await saveDraft(localFileName,cloudFile.versionStatus.lockId, cloudFile.key,localRoot);
      if(saveResult&&saveResult.code!='-1111'){
        if(saveResult&&saveResult.code=='2000'){
          console.log(`文件 ${localFileName} 提交成功`);
        }else{
          console.log(`文件 ${localFileName} 提交失败`);
        }
      }
      //解锁
      console.log(`文件开始解锁${localFileName}...`);
      let unlockResult=await unlockFile(cloudFile.versionStatus.lockId);
      if(unlockResult&&unlockResult.code=='2000'){
        console.log(`文件 ${localFileName} 解锁成功`);
      }else{
        console.log(`文件 ${localFileName} 解锁失败`);
      }
    }
}
/**
 * 提交services文件
 */
async function handSevices(cloudServiceFiles,localRoot,fileFolderId) {
 
  const localServicesFiles = readLocalFiles(localRoot);
   
  console.log('检测本地文件是否在中台services里面...');
    for (const localFileName of localServicesFiles) {
      if(['IServiceProxy.ts','ServiceProxy.ts','WsServiceProxy.ts'].includes(localFileName)){
         continue;
      }
      // 检查本地文件是否在云端services里面
      console.log(`开始检测文件：${localFileName}`);
      let cloudFile = null;
      let serviceName=localFileName.split('.')[0].replace('Declare','');
      let isDeclare=localFileName.indexOf('Declare.ts')>-1;
      for (const service of cloudServiceFiles.servicesFiles) {
        if(service.code==serviceName){
           if (service.children) {
              if(isDeclare){
                cloudFile=service.children.find(child=>child.type=='ServiceDeclare');
              }else{
                if(localFileName.indexOf('.test.ts')>-1){
                  let serviceSource=service.children.find(child=>child.type=='ServiceSource');
                  if(serviceSource&&serviceSource.children){
                    cloudFile=serviceSource.children.find(child=>child.type=='ServiceTest');
                  }
                }else{
                   cloudFile=service.children.find(child=>child.type=='ServiceSource');
                }
               
              }
           
           }
           break;
        }
      }
      if(!cloudFile){
        console.log(`文件 ${localFileName} 在中台不存在`);
        if(localFileName.indexOf('.test.ts')==-1&&localFileName.indexOf('Declare.ts')==-1){
          console.log(`创建Services文件 ${localFileName} `);
          let createServicesResult=await createServices(serviceName,fileFolderId);
          if(createServicesResult&&createServicesResult.code=='2000'){
            console.log(`文件 ${localFileName} 创建成功`);
             cloudFile={
                                "code": `${serviceName}`,
                                "desc": null,
                                "key": `${createServicesResult.data.sourceFileId}`,
                                "title": "代码",
                                "type": "ServiceSource",
                                "path": `${createServicesResult.data.sourceFilePath}`,
                                "versionStatus": {
                                    "locked": false,
                                    "lockId": null,
                                    "lockCommitted": null,
                                    "draftRevisionId": null,
                                    "fileStatus": "unversioned"
                                },
                                "children": [
                                    {
                                        "code": `${serviceName}`,
                                        "desc": null,
                                        "key": `${createServicesResult.data.testFileId}`,
                                        "title": "单元测试",
                                        "type": "ServiceTest",
                                        "path": `${createServicesResult.data.testFilePath}`,
                                        "versionStatus": {
                                            "locked": false,
                                            "lockId": null,
                                            "lockCommitted": null,
                                            "draftRevisionId": null,
                                            "fileStatus": "unversioned"
                                        },
                                        "children": [

                                        ]
                                    }
                                ]
                            }
            // cloudFile={
            //             "code": `${serviceName}`,
            //             "desc": "",
            //             "key": `${serviceName}`,
            //             "title": `${serviceName}`,
            //             "type": "Service",
            //             "path": `${serviceName}.ts`,
            //             "versionStatus": {
            //                 "locked": false,
            //                 "lockId": "",
            //                 "lockCommitted": false,
            //                 "draftRevisionId": "",
            //                 "fileStatus": "unversioned"
            //             },
            //             "children": [
            //                 {
            //                     "code": `${serviceName}`,
            //                     "desc": null,
            //                     "key": `${createServicesResult.data.declareFileId}`,
            //                     "title": "声明",
            //                     "type": "ServiceDeclare",
            //                     "path": `${createServicesResult.data.declareFileId}.ts`,
            //                     "versionStatus": {
            //                         "locked": false,
            //                         "lockId": null,
            //                         "lockCommitted": null,
            //                         "draftRevisionId": null,
            //                         "fileStatus": "unversioned"
            //                     },
            //                     "children": [

            //                     ]
            //                 },
            //                 {
            //                     "code": `${serviceName}`,
            //                     "desc": null,
            //                     "key": `${createServicesResult.data.sourceFileId}`,
            //                     "title": "代码",
            //                     "type": "ServiceSource",
            //                     "path": `${createServicesResult.data.sourceFilePath}`,
            //                     "versionStatus": {
            //                         "locked": false,
            //                         "lockId": null,
            //                         "lockCommitted": null,
            //                         "draftRevisionId": null,
            //                         "fileStatus": "unversioned"
            //                     },
            //                     "children": [
            //                         {
            //                             "code": `${serviceName}`,
            //                             "desc": null,
            //                             "key": `${createServicesResult.data.testFileId}`,
            //                             "title": "单元测试",
            //                             "type": "ServiceTest",
            //                             "path": `${createServicesResult.data.testFilePath}`,
            //                             "versionStatus": {
            //                                 "locked": false,
            //                                 "lockId": null,
            //                                 "lockCommitted": null,
            //                                 "draftRevisionId": null,
            //                                 "fileStatus": "unversioned"
            //                             },
            //                             "children": [

            //                             ]
            //                         }
            //                     ]
            //                 }
            //             ]
            //         }
          }else{
            console.log(`文件 ${localFileName} 创建失败`);
            continue;
          }
        }else{
           continue;
        }
       
      }
      let isLocked=true;
      if(cloudFile.versionStatus&&!cloudFile.versionStatus.locked){//未锁定
          isLocked=false;
          console.log(`文件开始锁定${localFileName}...`);
          let lockResult=  await tryLockFile(cloudFile.key);
          if(lockResult&&lockResult.code=='2000'&&lockResult.data){//锁定成功
            console.log(`文件 ${localFileName} 已锁定,lockId:${lockResult.data.id}`);
            cloudFile.versionStatus.locked=true;
            cloudFile.versionStatus.lockId=lockResult.data.id;
            isLocked=true;
          }else{
            console.log(`文件 ${localFileName} 锁定失败`);
          }
        
      }
      if(!isLocked){
        console.log(`文件 ${localFileName} 锁定失败`);
        continue;
      }
      //提交修改
      console.log(`文件开始提交修改${localFileName}...`);
      let saveResult=await saveDraft(localFileName,cloudFile.versionStatus.lockId, cloudFile.key,localRoot);
      if(saveResult&&saveResult.code!='-1111'){
        if(saveResult&&saveResult.code=='2000'){
          console.log(`文件 ${localFileName} 提交成功`);
        }else{
          console.log(`文件 ${localFileName} 提交失败`);
        }
      }
      //解锁
      console.log(`文件开始解锁${localFileName}...`);
      let unlockResult=await unlockFile(cloudFile.versionStatus.lockId);
      if(unlockResult&&unlockResult.code=='2000'){
        console.log(`文件 ${localFileName} 解锁成功`);
      }else{
        console.log(`文件 ${localFileName} 解锁失败`);
      }
    }
    await handFolderSevices(cloudServiceFiles, localRoot,fileFolderId);
}
/**
 * 提交services 多级文件夹文件
 */
async function handFolderSevices(cloudServiceFiles, dir,fileFolderId) {
   //查找多级目录
   const entries = fs.readdirSync(dir, { withFileTypes: true });
   for (const entry of entries) {
     const fullPath = path.join(dir, entry.name);
     if (entry.isDirectory()) {
       // 检查目录名称是否与type="FileFolder"且code=目录名称一致
       const matchingFolder = cloudServiceFiles.servicesFiles.find(file => file.type === 'FileFolder' && file.code === entry.name);
       if(!matchingFolder){
         console.log(`目录 ${entry.name} 未在中台找到匹配`);
         let folderResult= await createFolder(entry.name,entry.name,'0',fileFolderId);
         if(folderResult&&folderResult.code=='2000'&&folderResult.data){
           fileFolderId=folderResult.data.id;
           cloudServiceFiles.servicesFiles=[]
         }
         else{
            console.log(`目录 ${entry.name} 创建失败`);
            continue;
         }
        
       }else{
           fileFolderId=matchingFolder.key;
           cloudServiceFiles.servicesFiles=matchingFolder.children;
       }
      
       await handSevices(cloudServiceFiles,fullPath,fileFolderId);
       fileFolderId=null;
          
     }
   }
}
/**
 * 提交localLib文件
 * @param {*} cloudServiceFiles 
 */
async function handLocalLib(cloudServiceFiles) {
    let localRoot=`${config.localRoot}\\local-lib`;
    const localLibFiles = readLocalFiles(localRoot);
    console.log('检测本地文件是否在中台localLib里面...');
    for (const localFileName of localLibFiles) {
      if(['IServiceProxy.ts','ServiceProxy.ts','WsServiceProxy.ts'].includes(localFileName)){
         continue;
      }
      // 检查本地文件是否在云端services里面
      console.log(`开始检测文件：${localFileName}`);
      let cloudFile = null;
      let serviceName=localFileName.split('.')[0];
      for (const service of cloudServiceFiles.localLibFiles) {
        if(service.code==serviceName){
          if(localFileName.indexOf('.test.ts')>-1){
            if (service.children) {
               cloudFile=service.children.find(child=>child.type=='LocalLibTest');
             }   
          }else{
            cloudFile=service;
          }
          
           break;
        }
      }
      if(!cloudFile){
        console.log(`文件 ${localFileName} 在中台不存在`);
        if(localFileName.indexOf('.test.ts')==-1){
          console.log(`创建LocalLib文件 ${localFileName} `);
          let createLocalLibResult=await createLocalLib(serviceName);
          if(createLocalLibResult&&createLocalLibResult.code=='2000'){
            console.log(`文件 ${localFileName} 创建成功`);
            cloudFile={
                        "code": `${serviceName}`,
                        "desc": null,
                        "key": `${createLocalLibResult.data.sourceFileId}`,
                        "title": `${serviceName}`,
                        "type": "LocalLib",
                        "path": `${createLocalLibResult.data.sourceFilePath}`,
                        "versionStatus": {
                            "locked": false,
                            "lockId": null,
                            "lockCommitted": null,
                            "draftRevisionId": null,
                            "fileStatus": "modified"
                        },
                        "children": [
                            {
                                "code": `${serviceName}`,
                                "desc": null,
                                "key": `${createLocalLibResult.data.testFileId}`,
                                "title": "单元测试",
                                "type": "LocalLibTest",
                                "path": `${createLocalLibResult.data.testFilePath}`,
                                "versionStatus": {
                                    "locked": false,
                                    "lockId": null,
                                    "lockCommitted": null,
                                    "draftRevisionId": null,
                                    "fileStatus": "unversioned"
                                },
                                "children": [

                                ]
                            }
                        ]
                      }
          }else{
            console.log(`文件 ${localFileName} 创建失败`);
            continue;
          }
        }else{
           continue;
        }
        
       
      }
      let isLocked=true;
      if(cloudFile.versionStatus&&!cloudFile.versionStatus.locked){//未锁定
          isLocked=false;
          console.log(`文件开始锁定${localFileName}...`);
          let lockResult=  await tryLockFile(cloudFile.key);
          if(lockResult&&lockResult.code=='2000'&&lockResult.data){//锁定成功
            console.log(`文件 ${localFileName} 已锁定,lockId:${lockResult.data.id}`);
            cloudFile.versionStatus.locked=true;
            cloudFile.versionStatus.lockId=lockResult.data.id;
            isLocked=true;
          }else{
            console.log(`文件 ${localFileName} 锁定失败`);
          }
        
      }
      if(!isLocked){
        console.log(`文件 ${localFileName} 锁定失败`);
        continue;
      }
      //提交修改
      console.log(`文件开始提交修改${localFileName}...`);
      let saveResult=await saveDraft(localFileName,cloudFile.versionStatus.lockId, cloudFile.key,localRoot);
      if(saveResult&&saveResult.code!='-1111'){
        if(saveResult&&saveResult.code=='2000'){
          console.log(`文件 ${localFileName} 提交成功`);
        }else{
          console.log(`文件 ${localFileName} 提交失败`);
        }
      }
      //解锁
      console.log(`文件开始解锁${localFileName}...`);
      let unlockResult=await unlockFile(cloudFile.versionStatus.lockId);
      if(unlockResult&&unlockResult.code=='2000'){
        console.log(`文件 ${localFileName} 解锁成功`);
      }else{
        console.log(`文件 ${localFileName} 解锁失败`);
      }
    }
}

function getUploadContent(filePath, sourcePath) {
  const fullPath = path.join(sourcePath, filePath);
  const localContent = fs.readFileSync(fullPath, 'utf8');
  if (filePath.endsWith('Declare.ts')) {
    return convertTsDeclareContentToXml(localContent);
  }
  return localContent;
}
// 文件提交函数
async function saveDraft(filePath, lockId, fileId,sourcePath) {
  try {
    // 检查文件是否修改
    console.log(`检查文件是否修改...`);
    const isModified = await isFileModified(filePath, fileId, lockId,sourcePath);
    
    if (!isModified) {
      console.log(`文件 ${filePath} 未修改，跳过提交`);
      return { code: '-1111', success: true, message: '文件未修改' };
    }
    
    // 读取文件内容
    const content = getUploadContent(filePath, sourcePath);
    
    // 调用saveDraft接口
    
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('projectVersionId', config.projectVersionId);
    formData.append('lockId', lockId);
    formData.append('content', content);
    
    const response = await axios.post(config.saveDraftUrl, formData, {
      headers: {
        ...config.headers,
        ...formData.getHeaders()
      }
    });
    
   // console.log(`saveDraft响应:`, response.data);
    
    // 如果saveDraft成功，调用commitFile接口
    if (response.data.code === '2000' && response.data.success && response.data.data && response.data.data.revisionId) {
      console.log(`开始提交文件...`);
      await commitFile(lockId, response.data.data.revisionId);
    }
    
    return response.data;
  } catch (error) {
    console.error(`调用saveDraft接口时发生错误:`, error);
    return null;
  }
}
//检查文件是否修改
// 获取云端文件内容
async function getCloudFileContent(fileId, lockId) {
  try {
    const getTextFileUrl = `https://me.keytop.cn/fms-webide-server/getTextFile?projectVersionId=${config.projectVersionId}&fileId=${fileId}&lockId=${lockId}`;
    const response = await axios.get(getTextFileUrl, {
      headers: config.headers
    });
    
    //console.log(`getTextFile响应:`, response.data);
    return response.data.data?.content || '';
  } catch (error) {
    console.error(`调用getTextFile接口时发生错误:`, error);
    return null;
  }
}

// 检查文件是否修改
async function isFileModified(filePath, fileId, lockId,sourcePath) {
  try {
    const localContent = getUploadContent(filePath, sourcePath);
    
    // 获取云端文件内容
    const cloudContent = await getCloudFileContent(fileId, lockId);
    
    // 比较内容
    return localContent !== cloudContent;
  } catch (error) {
    console.error(`检查文件是否修改时发生错误:`, error);
    return true; // 出错时默认认为文件已修改
  }
}

// 提交文件函数
async function commitFile(lockId, revisionId) {
  try {
  
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('projectVersionId', config.projectVersionId);
    formData.append('lockId', lockId);
    formData.append('unlock', 'false');
    
    const response = await axios.post(config.commitFileUrl, formData, {
      headers: {
        ...config.headers,
        ...formData.getHeaders()
      }
    });
    
    console.log(`commitFile响应:`, response.data);
    return response.data;
  } catch (error) {
    console.error(`调用commitFile接口时发生错误:`, error);
    return null;
  }
}
// 创建Services文件夹函数
async function createFolder(code,name,seqNo,fileFolderId) {
  try {
  
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('projectVersionId', config.projectVersionId);
    formData.append('code', code);
    formData.append('name', name);
    formData.append('seqNo', seqNo??0);
    formData.append('parentId', fileFolderId?fileFolderId:'Services');
    
    const response = await axios.post(config.createFolderUrl, formData, {
      headers: {
        ...config.headers,
        ...formData.getHeaders()
      }
    });
    
    console.log(`createFolder响应:`, response.data);
    return response.data;
  } catch (error) {
    console.error(`调用createFolder接口时发生错误:`, error);
    return null;
  }
}
// 创建Services文件函数
async function createServices(code,fileFolderId) {
  try {
  
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('projectVersionId', config.projectVersionId);
    formData.append('code', code);
    formData.append('desc', '');
    if(fileFolderId){//在指定文件夹下创建Services文件
      formData.append('fileFolderId', fileFolderId);
    }
    
    const response = await axios.post(config.createServicesUrl, formData, {
      headers: {
        ...config.headers,
        ...formData.getHeaders()
      }
    });
    
    console.log(`createServices响应:`, response.data);
    return response.data;
  } catch (error) {
    console.error(`调用createServices接口时发生错误:`, error);
    return null;
  }
}
// 创建localLib文件函数
async function createLocalLib(code) {
  try {
  
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('projectVersionId', config.projectVersionId);
    formData.append('code', code);
    
    const response = await axios.post(config.createLocalLibUrl, formData, {
      headers: {
        ...config.headers,
        ...formData.getHeaders()
      }
    });
    
    console.log(`createLocalLib响应:`, response.data);
    return response.data;
  } catch (error) {
    console.error(`调用createLocalLib接口时发生错误:`, error);
    return null;
  }
}
//删除文件
// 删除locallib接口
async function removeLocallib(code) {
  try {
     // 创建FormData对象
    const formData = new FormData();
    formData.append('projectVersionId', config.projectVersionId);
    formData.append('code', code);
    
    const response = await axios.post(config.removeLocalLib, formData, {
      headers: {
        ...config.headers,
        ...formData.getHeaders()
      }
    });
    
    console.log(`removeLocallib响应:`, response.data);
    return response.data;
  } catch (error) {
    console.error(`调用removeLocallib接口时发生错误:`, error);
    return null;
  }
}
// 删除服务接口
async function removeService(code) {
  try {
     // 创建FormData对象
    const formData = new FormData();
    formData.append('projectVersionId', config.projectVersionId);
    formData.append('code', code);
    
    const response = await axios.post(config.removeServices, formData, {
      headers: {
        ...config.headers,
        ...formData.getHeaders()
      }
    });
    
    console.log(`removeService响应:`, response.data);
    return response.data;
  } catch (error) {
    console.error(`调用removeService接口时发生错误:`, error);
    return null;
  }
}

// 删除文件夹接口
async function removeFileFolder(id) {
  try {
     const formData = new FormData();
    formData.append('projectVersionId', config.projectVersionId);
    formData.append('id', id);
    
     const response = await axios.post(config.removeServicesFolder, formData, {
      headers: {
        ...config.headers,
        ...formData.getHeaders()
      }
    });
    console.log(`removeFileFolder响应:`, response.data);
    return response.data;
  } catch (error) {
    console.error(`调用removeFileFolder接口时发生错误:`, error);
    return null;
  }
}

// 检查并删除不存在的文件和目录
async function checkAndRemoveNonExistent(cloudServiceFiles,localRoot) {
  console.log('检查并删除不存在的文件和目录...');
  await checkAndRemoveRecursive(cloudServiceFiles.servicesFiles,localRoot);
}

// 递归检查并删除不存在的文件和目录
async function checkAndRemoveRecursive(items, currentPath) {
  for (let i = items.length - 1; i >= 0; i--) {
    const item = items[i];
    const itemPath = path.join(currentPath, item.code);
    
    if (item.type === 'FileFolder') {
      // 检查目录是否存在
      if (!fs.existsSync(itemPath) || !fs.lstatSync(itemPath).isDirectory()) {
        console.log(`目录 ${item.code} 不存在，准备删除`);
        // 递归检查子目录和文件
        if (item.children && item.children.length > 0) {
          await checkAndRemoveRecursive(item.children, itemPath);
        }
        // 删除文件夹
        await removeFileFolder(item.key);
      } else {
        // 目录存在，递归检查子目录
        if (item.children && item.children.length > 0) {
          await checkAndRemoveRecursive(item.children, itemPath);
        }
      }
    } else if (item.type === 'Service') {
      // 检查服务文件是否存在
      const serviceFilePath = path.join(currentPath, `${item.code}.ts`);
      if (!fs.existsSync(serviceFilePath)) {
        console.log(`服务文件 ${item.code}.ts 不存在，准备删除`);
        // 删除服务
        await removeService(item.code);
      }
    }
  }
}

// 删除lib文件
async function checkAndRemoveLocalLib(cloudServiceFiles) {
  let currentPath=`${config.localRoot}\\local-lib`;
  let items=cloudServiceFiles.localLibFiles;
  for (let i = items.length - 1; i >= 0; i--) {
    const item = items[i];
    if (item.type === 'LocalLib') {
      // 检查服务文件是否存在
      const serviceFilePath = path.join(currentPath, `${item.code}.ts`);
      if (!fs.existsSync(serviceFilePath)) {
        console.log(`localLib文件 ${item.code}.ts 不存在，准备删除`);
        // 删除服务
        await removeLocallib(item.code);
      }
    }
  }
}

// 文件解锁函数
async function unlockFile(lockId) {
  try {
    const unlockUrl = `https://me.keytop.cn/fms-webide-server/unlock?lockId=${lockId}`;
    const response = await axios.get(unlockUrl, {
      headers: config.headers
    });
    
   // console.log(`unlock响应:`, response.data);
    return response.data;
  } catch (error) {
    console.error(`调用unlock接口时发生错误:`, error);
    return null;
  }
}


// 执行主函数
main();
