const fs = require('fs');
const path = require('path');
const cheerio = require('cheerio');
// 处理 {{}} 里面的 >  < ==>
const preParseGtLt = (content) => {
    const reg = /{{([\s\S]*?)}}/g;
    return content.replace(reg, (match) => {
        return _operationGtLt(match);
    });
};
const _operationGtLt = (content) => {
    const gtltReg = />|</g;
    return content.replace(gtltReg, (match) => {
        if (match === '>') {
            return '_cml_gt_lmc_';
        }
        if (match === '<') {
            return '_cml_lt_lmc_';
        }
        return match;
    });
};
// 预处理 标签内的 {{item.id}} 这种语法jsx无法识别，转化为 {item.id}
const preParseMustache = (content) => {
    const reg = />([\s\S]*?)<[a-zA-Z\/\-_]+?/g;
    return content.replace(reg, (match, key) => {
        return _operationMustache(match);
    });
};
// 模块内置方法
// 这里主要处理1  >{{}}< 双花括号之间的 ==> {}, 因为jsx无法识别 {{}}
// 2 同时将 {{}}内的 _cml_gt_lmc_  _cml_lt_lmc_ 复原  < >
const _operationMustache = (content) => {
    const mustacheReg = /{{([\s\S]*?)}}/g;
    return content.replace(mustacheReg, (match, key) => {
        const newKey = _deOperationGtLt(key);
        return `{${newKey}}`;
    });
};
const _deOperationGtLt = (content) => {
    const deGtLtReg = /_cml_gt_lmc_|_cml_lt_lmc_/g;
    return content.replace(deGtLtReg, (match) => {
        if (match === '_cml_gt_lmc_') {
            return '>';
        }
        if (match === '_cml_lt_lmc_') {
            return '<';
        }
        return match;
    });
};
const getJsonByXml = (xmlStr) => {
    const entities = xmlStr('Object').toArray().map((v) => {
        const $entity = xmlStr(v);
        const entity = Object.assign({}, $entity.attr());
        const fields = $entity.children('Field').toArray().map((ele) => {
            const filed = xmlStr(ele).attr();
            const $options = xmlStr(ele).children('Options').toArray();
            if ($options.length > 0) {
                const options = xmlStr(ele).children('Options').toArray().map((opts) => {
                    const refId = xmlStr(opts).attr('ref-id');
                    const option = xmlStr('Collection').children(`Options[id=${refId}]`).children('Option').toArray()
                        .map((opt) => xmlStr(opt).attr());
                    return option;
                });
                filed.options = options[0];
            }
            return filed;
        });
        entity.fields = fields;
        return entity;
    });
    return entities;
};
// 更新 serverAction 相关数据
// 更新 swagger 相关数据
const compileSwaggerData = (projectPath) => {
    var _a, _b;
    let swaggerStr = '{}';
    const swaggerList = [];
    let swaggerProxy = {};
    const swaggerConfigPath = path.join(projectPath, 'generatedCode/frontend/src/utils/swagger.config.ts');
    const swaggerProxyPath = path.join(projectPath, 'generatedCode/frontend/swaggerProxy.config.js');
    // 能力开放平台接口需要转发 不加入 swaggerProxy 中， 在 .fishx.config.hbs 手动写死配置
    const capabilityOpenPlatformBasePath = '/zmp-pr/db-zmpapi';
    if (fs.existsSync(path.join(projectPath, 'Logic/Integrations/swagger-list.json'))) {
        swaggerStr = fs.readFileSync(path.join(projectPath, 'Logic/Integrations/swagger-list.json'));
        const swaggerObj = JSON.parse(swaggerStr.toString());
        // Object.values(swaggerObj).forEach(v => {
        //   swaggerList.push(v);
        //   // 能力开放平台接口需要转发 不加入 swaggerProxy 中， 在 .fishx.config.hbs 手动写死配置
        //   let { basePath } = v;
        //   const { basePaths, servers = [] } = v;
        //   const host = servers?.[0]?.url;
        //   if (basePaths && !basePath) {
        //     basePaths.forEach((basePathsItem, basePathsIndex) => {
        //       if (basePathsItem.indexOf(capabilityOpenPlatformBasePath) === -1) {
        //         if (basePathsItem.includes('${') && v.env) {
        //           basePaths[basePathsIndex] = basePathsItem.replace(/\${([\S]+)}/g, (match, key) => {
        //             return v.env[key].development;
        //           });
        //         }
        //         swaggerProxy[basePathsItem] = {
        //           target: host,
        //           changeOrigin: true,
        //         };
        //       }
        //     });
        //   } else if (basePath) {
        //     if (v.basePath && v.basePath.indexOf(capabilityOpenPlatformBasePath) === -1) {
        //       if (basePath.includes('${') && v.env) {
        //         basePath = basePath.replace(/\${([\S]+)}/g, (match, key) => {
        //           return v.env[key].development;
        //         });
        //       }
        //       swaggerProxy[basePath] = {
        //         target: host,
        //         changeOrigin: true,
        //       };
        //     }
        //   }
        // });
        // 这里直接使用swaggerGroup的key 作为代理前缀
        for (const [k, v] of Object.entries(swaggerObj)) {
            swaggerList.push(v);
            const { servers = [] } = v;
            const host = (_a = servers === null || servers === void 0 ? void 0 : servers[0]) === null || _a === void 0 ? void 0 : _a.url;
            swaggerProxy[`/${k}`] = {
                target: host,
                changeOrigin: true,
                pathRewrite: {
                    [`^/${k}`]: '/'
                }
            };
        }
    }
    // swaggerProxy 排序 越详细的排上面
    const swaggerProxyKeys = (_b = Object.keys(swaggerProxy)) === null || _b === void 0 ? void 0 : _b.sort((a, b) => (b.length - a.length));
    const sortedSwaggerProxy = {};
    swaggerProxyKeys === null || swaggerProxyKeys === void 0 ? void 0 : swaggerProxyKeys.forEach(swaggerProxyKey => sortedSwaggerProxy[swaggerProxyKey] = swaggerProxy[swaggerProxyKey]);
    swaggerProxy = sortedSwaggerProxy;
    swaggerStr = JSON.stringify(swaggerProxy).replace(/"\$TEMPLATE_ONPROXYRES\$"/g, 'onProxyRes');
    fs.writeFileSync(swaggerConfigPath, `export default ${JSON.stringify(swaggerList)}`, { encoding: 'utf8' });
    fs.writeFileSync(swaggerProxyPath, `module.exports = (onProxyRes) => (${swaggerStr})`, { encoding: 'utf8' });
};
// 更新 实体 相关数据
const compileEntityData = (projectPath) => {
    const entityConfigPath = path.join(projectPath, 'generatedCode/frontend/src/utils/entity.config.ts');
    const domStr = fs.readFileSync(path.join(projectPath, 'Data/Objects/dom.xml'));
    const xmlStr = cheerio.load(domStr.toString(), {
        xml: {
            xmlMode: true,
        },
    });
    fs.writeFileSync(entityConfigPath, `export default ${JSON.stringify(getJsonByXml(xmlStr))}`, { encoding: 'utf8' });
};
module.exports = {
    preParseGtLt,
    preParseMustache,
    compileSwaggerData,
    compileEntityData,
};
