gqz / FOP Bean代码生成

// ==UserScript==
// @name         FOP Bean代码生成
// @namespace    http://tampermonkey.net/
// @version      1.02.02
// @description  try to take over the world!
// @author       gqz
// @match        https://fop.goodcang.com/portal/alInner/detail?*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=goodcang.com
// @run-at       document-end
// @license      Apache-2.0
// @grant        GM_xmlhttpRequest

// @require https://cdn.bootcdn.net/ajax/libs/jquery/2.2.4/jquery.min.js
// @require https://cdn.bootcdn.net/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js


// @resource jqueryUiCSS https://cdn.bootcdn.net/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.css
// @resource jqueryUiThemeCSS https://cdn.bootcdn.net/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @grant        GM_setClipboard
// @grant        GM_notification

// ==/UserScript==

(function() {
    'use strict';

    var ReqBeanData = null;
    var RespBeanData = null;

    var checkUrlChange=null;

    var tonken = localStorage.getItem('micro-gosAdmin-Token');
    var url = window.location.search;

    if(!tonken){
        return;
    }

   GM_addStyle(GM_getResourceText("jqueryUiCSS"));
   GM_addStyle(GM_getResourceText("jqueryUiThemeCSS"));

   GM_addStyle('.ui-button .ui-icon{background-image: url(https://cdn.bootcdn.net/ajax/libs/jqueryui/1.13.2/themes/base/images/ui-icons_777777_256x240.png);}');
   GM_addStyle('.ui-widget-header .ui-icon{background-image: url(https://cdn.bootcdn.net/ajax/libs/jqueryui/1.13.2/themes/base/images/ui-icons_777777_256x240.png);}');

   GM_addStyle('.toast > .ui-dialog-titlebar{ display:none;}');
   GM_addStyle('#toast{min-height: 20px !important;}');
   GM_addStyle('.ui-accordion-content-active{height: auto !important;display:block  !important;}');
   GM_addStyle('.ui-accordion-header.ui-state-active{background:#e5e5e5 !important; border: 1px solid #ccc !important;color:#666666; }');
   GM_addStyle('.ui-accordion-header .copy_btn{float:right;display:none;}');
   GM_addStyle('.ui-accordion-header.ui-state-active .copy_btn{float:right;display:block;}');


    $(function(){
        setTimeout(()=>{
             console.log('fop-left-tree-menu a',$('.fop-left-tree-menu a').length)
             $('.fop-left-tree-menu a').on('click',function(){
                 if(checkUrlChange!==null){
                     clearTimeout(checkUrlChange)
                 }
                checkUrlChange = setTimeout(()=>{
                      checkUrlChange = null;
                      console.log(url,window.location.search)
                      if(url != window.location.search){//网址发生改变重新请求数据
                          url = window.location.search;
                          $('reqStr').html('');
                          $('accordion').html('');
                          getFieldData();
                      }
                  },300)
             })
        },1000)

        //添加弹窗
        $('body').append('<div  style="display:none;" id="requestBeanBox" title="请求参数"></div>');
        $('body').append('<div  style="display:none;" id="responseBeanBox" title="响应参数"></div>');
        $('body').append('<div  style="display:none;" id="toast"></div>');

        $("#toast" ).dialog({
            autoOpen: false,
            draggable:false,
            resizable:false,
            dialogClass:"toast",
            position :{ my: "center", at: "top+150", of: window },
            hide:{
              effect:'blind',
              duration:800
            }
        });
        //添加按钮
        var $reqButton = $('<button type="button" id="reqBtn">').text('生成请求参数');
        var $resqButton = $('<button type="button"  id="respBtn">').text('生成响应参数');

        $reqButton.on('click', function() {
            $("#requestBeanBox" ).dialog({
                height: 400,
                width:600,
                modal: true,
                closeOnEscape : true,
                buttons: {
                     "复制": function() {
                         let copyText = $('#reqStr').text();
                         if(!copyText){
                           for (const type in ReqBeanData) {
                               copyText +='\n\n\n/** class: '+type+' */\n\n' + ReqBeanData[type].join('')
                           }
                         }
                         GM_setClipboard(copyText, "text", () => {
                             $( this ).dialog( "close" );
                             toast('复制成功');
                         });
                     },
                     "关闭 ESC": function() {
                         $( this ).dialog( "close" );
                     }
                 }
            });
        });
        $resqButton.on('click',function(){
             $("#responseBeanBox" ).dialog({
                  height: 600,
                  width:600,
                  modal: true,
                  closeOnEscape : true,
                  buttons: {
                     "复制": function() {
                         let copyText = $('#respStr').text();
                         if(!copyText){
                             for (const type in RespBeanData) {
                                 copyText +='\n\n\n/** class: '+type+' */\n\n' + RespBeanData.join('')
                             }
                         }
                         GM_setClipboard(copyText, "text", () => {
                             $( this ).dialog( "close" );
                             toast('复制成功');
                         });
                     },
                     "关闭 ESC": function() {
                         $( this ).dialog( "close" );
                     }
                 }

              });
        });
        setTimeout(()=>{
            $('.fbg-group-title').each((i,v)=>{
                if($(v).text().trim() == '请求参数'){
                    $(v).append($reqButton);
                }
                if($(v).text().trim() == '响应数据'){
                    $(v).append($resqButton);
                }
            })
            //$( "#accordion" ).accordion();
            getFieldData();
        },1000);
    });


function getFieldData(){
        const urlParams = new URLSearchParams(window.location.search);
        let icode= urlParams.get('icode') || ''
        console.log('开始请求数据',icode)
        //request
        getData('https://ark-gateway.goodcang.com/gos/api/v1/interface_base/get_interface_detail/'+icode+'?ability=1&customer_app_id=',(data)=>{
             let filed = (JSON.parse(data.data.req_param_json)).object_params;
             if(!filed){
                 $('#reqBtn').hide();
                 return;
             }

             $('#reqBtn').show();
             let format = new PHP(filed)
             ReqBeanData = format.format();
             render(ReqBeanData,'req')

        })

         //response
        getData('https://ark-gateway.goodcang.com/gos/api/v1/interface_reqresp/get_detail_resp/'+icode+'?ability=1',(data)=>{
             let dataFiled = (JSON.parse(data.data.RESP)).object_params.filter(item=>item.field_name=='data')
             if(dataFiled.length < 1){ return;}
             let filed = null;
             if(dataFiled[0].field_type == 'object'){
                  filed = dataFiled[0].object_params;
             }
            if(dataFiled[0].field_type == 'array'){
                  filed = dataFiled[0].array_params;
             }
            
             if(!filed || filed.length<1){
                      $('#respBtn').hide();
                      return;
              }
             $('#respBtn').show();


             let format = new PHP(filed)
             RespBeanData = format.format();
             render(RespBeanData,'resp')


        })
}

function render(beanData,type){
    console.log('rener',type)
 let root = $('#'+(type == 'req' ? 'requestBeanBox': 'responseBeanBox'));
 let tmpOneDom = type+'Str';
 let tmpMoreDom = type+'Accordion';

	if(Object.keys(beanData).length > 1){
		root.html('<div id="'+tmpMoreDom+'"></div>');

		for (const key in beanData) {
			$('#'+tmpMoreDom).append(`<h3 data-type="${type}" data-key="${key}">${key}</h3><div id="accordion_${type}_${key}"></div>`);
			beanData[key].map((item)=>{
				$('#'+tmpMoreDom+' #accordion_'+type+'_'+key).append('<p>'+item.replace(new RegExp("\n", "g"), '<br>')+'</p>');
			})
		}

		$('#'+tmpMoreDom).children('h3').each((i,v)=>{
                 let type = $(v).data('type');
				 let key = $(v).data('key');
                 var $copyButton = $('<span class="copy_btn">').text('copy');

                 $copyButton.on('click', function() {
                      GM_setClipboard( '/** class: '+key+' */\n\n' +beanData[key].join(''), "text", () => {
                          toast('复制成功');
                      });
                 })
               $(v).append($copyButton);
        })

		$( "#"+tmpMoreDom ).accordion({collapsible: true });

	}else{
		 let tmpDom = type+'Str';
		 root.html('<pre id="'+tmpDom+'" style="margin:0"></pre>')
		 ReqBeanData.default.map((item)=>{
			 $('#'+tmpDom).append(item);
		 })
	}
}

function toast(msg){
    $('#toast').html(`<div>${msg}</div>`);
    $( "#toast" ).dialog( "open" );
    setTimeout(()=>{
        $( "#toast" ).dialog( "close" );
    },2000)
}

function getData(url,callback){
       GM_xmlhttpRequest({
        method: 'GET',
        url: url,
         headers: {
             'Authorization': tonken
         },
        onload: function(response) {
            callback(JSON.parse(response.responseText))
            //console.log(response.responseText);
        }
    });
}

class PHP {
    constructor(data) {
        //this.data = data
        this.fieldGroup = {}
        this.beanGroup = {}
        this.typeMap = {
            "integer":'int',
            "number":'int'
        }
        this.expandData(data)
    }
    format() {
        for (const key in this.fieldGroup) {
            this.beanGroup[key]=[];
            this.fieldGroup[key].forEach(item => {
                this.beanGroup[key].push(this.formatItem(item))
            })
        }
        return this.beanGroup
    }

    expandData(data,group='default'){
        if(!(group in this.fieldGroup)){
            this.fieldGroup[group]=[]
        }
        data.forEach(item => {
            let {field_name,field_type,filed_must,field_desc} = item;
            if(item.field_type=='array' && item.array_params!==null && item.array_params.object_params!==null){ //存在子元素
                this.fieldGroup[group].push({field_name,field_type,filed_must,field_desc,true_type:this.formmatName(field_name)})
                item.array_params.object_params && this.expandData(item.array_params.object_params,this.formmatName(field_name))
            }else if(item.field_type=='object' && item.object_params!==null && item.object_params.object_params!==null){ //存在子元素
                field_type = this.formmatName(field_name)
                this.fieldGroup[group].push({field_name,field_type,filed_must,field_desc})
                item.object_params.object_params && this.expandData(item.object_params.object_params,field_type)
            }else{
                this.fieldGroup[group].push({field_name,field_type,filed_must,field_desc})
            }
        })
    }
    formmatName(name) {
        return  name.split('_').map(item=>{
            let tempItem = item.charAt(0).toUpperCase() + item.slice(1);
            return tempItem == 'List'?'ListItem':tempItem;
        }).join('')
    }
    formatItem(item){
        let filedMastStr1 =  item.filed_must == "false" ? '?':'';
        let filedMastStr2 =  item.filed_must == "false" ? ' = null':'' ;
        let filedMastStr3 =  item.filed_must == "false" ? '|null':'' ;

        let filedType1 =  this.typeMap[item.field_type] || item.field_type;
        let trueType = filedType1;
        if(filedType1 == 'array'){
            trueType = (item.true_type || 'string')+'[]'
        }

return `\/** @var ${trueType}${filedMastStr3} ${item.field_desc} *\/
public ${filedMastStr1}${filedType1} \$${item.field_name}${filedMastStr2};

`
 }
}

})();