import { systemConfig } from "../config/serverConfig";
import { postForm } from "../util/request";
const Cookie = [
    'sidebar_collapsed=false',
    'cookie_token=6d42894284969a8fa9de3899d0127c80170dcdc40abf6fa50a49806b2fef6bb8',
    '_gitlab_session=71e6b1c04340c01cac8705794e01d768',
    'PHPSESSID=c7r1i01cu436otkcb1438053t5',
    'think_language=zh-CN'
];
let headers = {
    Cookie, 
    Accept:"application/json, text/plain, */*",
    "Accept-Encoding":"gzip, deflate",
    "Content-Type":['application/x-www-form-urlencoded', 'charset=UTF-8'],
    "Connection":"keep-alive",
    "Accept-Language":['zh-CN,zh', 'q=0.9'],
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    Host:"123.207.147.179:2222",
    Origin:"http://123.207.147.179:2222",
    Referer:"http://123.207.147.179:2222/showdoc/web/"
};
const ItemId = 81;//项目id
let distinctMap = {};
export async function getDoc() {
    let body = {
        item_id:ItemId,
        page_id: 1642
    };
    let result:any = await postForm('http://123.207.147.179:2222/showdoc/server/index.php?s=/api/item/info', body, headers);
    result.data.menu.catalogs.forEach(info => {
        let {cat_name, catalogs, cat_id} = info;//一级目录
        if (!distinctMap[cat_name]) distinctMap[cat_name] = {firstId:cat_id, secondMap:{} };
        catalogs.forEach(item => {
            let {pages} = item;
            if (!distinctMap[cat_name].secondMap[item.cat_name]) {
                distinctMap[cat_name].secondMap[item.cat_name] = {secondId:item.cat_id, apiMap:{} };
            }
            pages.forEach(apiItem => {
                let {page_title, page_id } = apiItem;
                distinctMap[cat_name].secondMap[item.cat_name].apiMap[page_title] = page_id;
            });
        });
    });
}
export async function initDoc(firstName, apiConfig, apiFirstRouter) {
    let itemHeaders = Object.assign({ Accept:"application/json, text/plain, */*",  "Cache-Control":"no-store, no-cache, must-revalidate, post-check=0, pre-check=0"}, headers);
    /**创建一级目录 */
    if (!distinctMap[firstName]) {
        let addFirstParam = {
            item_id:ItemId,
            cat_name:firstName
        };
        let addFirstResult:any = await postForm('http://123.207.147.179:2222/showdoc/server/index.php?s=/api/catalog/save', addFirstParam , itemHeaders);
        distinctMap[firstName] = {firstId:addFirstResult.data.cat_id, secondMap:{} };
    }

    for (let pKey in apiConfig) {
        if (!distinctMap[firstName].secondMap[pKey]) {
            /**创建二级目录 */
            let addSecondParam = {
                item_id:ItemId,
                cat_name:pKey,
                parent_cat_id:distinctMap[firstName].firstId
            };
            let addSecondResult:any = await postForm('http://123.207.147.179:2222/showdoc/server/index.php?s=/api/catalog/save', addSecondParam , itemHeaders);
            distinctMap[firstName].secondMap[pKey] = {secondId:addSecondResult.data.cat_id, apiMap:{} };
        }

        let subAPIList = apiConfig[pKey];
        for (let i = 0; i < subAPIList.length; i++) {
            let info = subAPIList[i];
            const ApiIsExistent = distinctMap[firstName].secondMap[pKey].apiMap[info.apiName];

            let itemStr = `**<h4>接口描述</h4>**\n`;
            itemStr += `- ${info.apiName}\n\n------\n`;
            itemStr += `**<h4>接口说明</h4>**\n\n`;
            itemStr += `|方式|ip|端口|URL地址|\n`;
            itemStr += `|:----- |:----- |----- |-------------- |\n`;
            itemStr += `|post|192.168.0.105|${systemConfig.port} |${apiFirstRouter}${info.subUrl}|\n`;
            itemStr += `**<h4>接口地址</h4>**\n\n`;
            itemStr += `\`http://192.168.0.105:${systemConfig.port}${apiFirstRouter}${info.subUrl}\`\n\n------\n`;
            itemStr += `**<h4>请求头（headers）</h4>**\n\n`;
            itemStr += `|参数名|类型|说明|\n`;
            itemStr += `|:---- |:----- |----- |\n`;
            itemStr += `|userid |string |用户id |\n`;
            itemStr += `|token |string |登录下发的token |\n\n ------\n`;
            if (!info.param || !info.param.length) {
                itemStr += `**<h4>请求参数参数（body）</h4>**\n\n`;
                itemStr += `· 无  \n\n ------\n`;
            } else {
                itemStr += `**<h4>请求参数参数（body）</h4>**\n\n`;
                itemStr += `|参数名|必选|类型|说明|\n`;
                itemStr += `|:----|:---|:-----|-----|\n`;
                let subMap = {};
                info.param.forEach(subInfo => {
                    let {key, type, sub, desc, isNull} = subInfo;
                    if (sub) {
                        itemStr += `|${key}|是|object| 参考 ${key}参数  |\n`;
                        subMap[key] = sub;
                    } else {
                        itemStr += `|${key}|${isNull == true?"否":"是"}|${type}| ${desc||''} |\n`;
                    }
                });
                itemStr += `\n------\n\n`;
                for (let subMapKey in subMap) {
                    itemStr+=`**<h5>${subMapKey}参数</h5>**\n\n`;
                    itemStr += `|参数名|必选|类型|说明|\n`;
                    itemStr += `|:----|:---|:-----|-----|\n`;
                    for (let subMapItemKey in subMap[subMapKey]) {
                        let subMapItemValue = subMap[subMapKey][subMapItemKey];
                        itemStr += `|${subMapItemKey}|${subMapItemValue.notMustHave==false? '否' : '是'}|${subMapItemValue.type}| ${subMapItemValue.desc||''} |\n`;
                    }
                    itemStr += `\n\n----------------\n`;
                }
            }
            
            itemStr += `**<h4>返回示例</h4>**\n`;
            
            if (ApiIsExistent) {
                let oldItemData:any = await postForm('http://123.207.147.179:2222/showdoc/server/index.php?s=/api/page/info', {page_id:ApiIsExistent} , itemHeaders);
                let oldItemDataStrList = oldItemData.data.page_content.split('```');
                itemStr += `\`\`\``;
                let checkItemStr = oldItemDataStrList[1].replace(/&amp;/g, "");
                checkItemStr = checkItemStr.replace(/&quot;/g, "");
                checkItemStr = checkItemStr.replace(/&amp;/g, "");
                itemStr += checkItemStr;

                itemStr += `\`\`\` \n\n`;
            } else {
                itemStr += `\`\`\` \n`;
                itemStr += `    {\n`;
                itemStr += `        "code":200,//接口状态码\n`;
                itemStr += `        "success":true,//响应状态\n`;
                itemStr += `        "data":{//数据主体\n`;
                itemStr += `            "success":true\n`;
                itemStr += `        }\n`;
                itemStr += `    }\n`;
                itemStr += `\`\`\` \n\n`;
            }
            itemStr += `------\n\n`;
            itemStr += `**<h4>错误码</h4>**\n\n`;
            itemStr += `|code码|说明|错误原因|后续操作|\n`;
            itemStr += `|:---- |:----- |:----- |----- |\n`;
            itemStr += `|401 |身份验证失败 |headers中的userid错误 |强制跳转到登陆页面 |\n`;
            itemStr += `|402 |非法登录 |headers中没有token或者userid |强制跳转到登陆页面 |\n`;
            itemStr += `|403 |身份验证过期 |token过期 |强制跳转到登陆页面 |\n`;
            itemStr += ``;
    
    
            let body = {
                page_id:ApiIsExistent || 0,
                item_id:ItemId,
                page_title:info.apiName,
                cat_id: distinctMap[firstName].secondMap[pKey].secondId,
                page_content:itemStr
            };
            let result = await postForm('http://123.207.147.179:2222/showdoc/server/index.php?s=/api/page/save', body , itemHeaders);
            console.log(`${info.apiName}文档${ApiIsExistent ? "修改 ":"创建 "}成功`);
        }
       
    }

    console.log("所有接口文档已更新完毕");
}
