package com.wb.interact;

import com.wb.common.Base;
import com.wb.common.KVBuffer;
import com.wb.util.FileUtil;
import com.wb.util.JsonUtil;
import com.wb.util.StringUtil;
import com.wb.util.WebUtil;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * 创建模板
 *
 * @author shao
 */
public class FileGenProcess {

    /**
     * 创建基本增删改查
     *
     * @param request
     * @param response
     * @param name
     * @param title
     * @param iconCls
     * @param path
     * @param tableName
     * @param keyField
     * @param codeField
     * @param nameField
     * @param isDialog
     * @param hasUpload
     * @throws Exception
     */
    private static void addbasiceCRUDFrame(HttpServletRequest request, HttpServletResponse response, String name, String title, String iconCls, File path, String tableName, String keyField, String codeField, String nameField, boolean isDialog, boolean hasUpload) throws Exception {
        File destFolder = new File(path, name);
        File destModule = new File(path, name + ".xwl");

//        File filedestfolder = new File(destFolder, "select.xwl");
//        JSONObject jsondest=new JSONObject();
//        jsondest.put("tablesql","T_student");
//        FileUtil.syncSave(filedestfolder, StringUtil.replaceParams(jsondest, FileUtil.readString(filedestfolder)));


        if (destModule.exists()) {
            throw new RuntimeException("模块“" + name + ".xwl”已经存在。");
        } else if (destFolder.exists()) {
            throw new RuntimeException("目录“" + name + "”已经存在。");
        } else {


            if (!StringUtil.isEmpty(codeField) && StringUtil.isEmpty(nameField)) {
                nameField = codeField;
                codeField = null;
            }
            File sourcePath;
            if (isDialog) {
                if (hasUpload) {
                    sourcePath = new File(Base.path, "wb/modules/dev/template/");
                } else {
                    sourcePath = new File(Base.path, "wb/modules/dev/template/");
                }
            } else {
                sourcePath = new File(Base.path, "wb/modules/dev/template/");
            }

            //==========创建查询文件start=========
            FileUtil.syncCreate(destFolder, true);
            File destfolderModule = new File(destFolder, "select" + name + ".xwl");
            FileUtil.syncCopyA(new File(sourcePath, "selectall.xwl"), destfolderModule);
            String contentchild = FileUtil.readString(destfolderModule);
            contentchild = contentchild.replace("#{tablename}", tableName);
            JSONObject modulechild = new JSONObject(contentchild);
            FileUtil.syncSave(destfolderModule, modulechild.toString());

            //======end=======

            FileUtil.syncCopyA(new File(sourcePath, "basic-dialog-edit.xwl"), destModule);

            File file = new File(path, "folder.json");
            JSONObject json = JsonUtil.readObject(file);
            JSONArray array = json.optJSONArray("index");
            array.put(name + ".xwl");
            array.put(name);
            StringBuffer buffer = new StringBuffer();

            buffer.append("{\n" +
                    "\"configs\": {\n" +
                    "\"itemId\": \"columns\"\n" +
                    "},\n" +
                    "\"expanded\": true,\n" +
                    "\"children\": [");

            request.setAttribute("tableName",request.getParameter("tableName"));

            String data = WebUtil.runresulte("m?xwl=dev/autogenControl/datasource", request, response);
            JSONObject datas = new JSONObject(data);
            JSONObject datama = new JSONObject(datas.optString("metaData"));
            JSONArray djons = new JSONArray(datama.optString("fields"));
            for (int a = 0; a < djons.length(); a++) {
                JSONObject jsondata = djons.getJSONObject(a);
                String namedata = jsondata.optString("name");
                String typedata = jsondata.optString("type");
                String usernuldata = jsondata.optString("useNull");
                String comment = jsondata.optString("comment");

                boolean flag = true;
                if (KVBuffer.getList(namedata).equals("[]")) {
                    flag = false;
                }
                buffer.append(" {\n" +
                        "        \"configs\": {" +
                        "\"itemId\": \"" + namedata + "\",\n" +
                        "\"dataIndex\": \"" + namedata + "\",\n" +
                        "\"width\": \"130\",\n" +
                        "\"text\": \"" + comment + "\",\n");
                if (flag) {//如果存在key

                    buffer.append(" \"keyName\": \"" + namedata + "\",");
                }
                buffer.append("\"titleAlign\": \"center\"" +
                        "},\n" +
                        "        \"expanded\": true,\n" +
                        " \"children\": [],"+
                     "\"type\": \"column\"\n");
                if (a == djons.length() - 1) {
                    buffer.append("}");
                } else {
                    buffer.append("},");
                }
            }
            buffer.append("],\n" +
                    "\"type\": \"array\"\n" +
                    "}");

            FileUtil.syncSave(file, json.toString());
            String baseUrl = FileUtil.getModuleUrl(destModule) + "/";
            String content = FileUtil.readString(destModule);
            json = new JSONObject();
            json.put("selectUrl", baseUrl + "select");
            json.put("searchUrl", baseUrl + "search");
            json.put("title", title);
            json.put("iconCls", iconCls);
            if (isDialog) {
                json.put("insertUrl", baseUrl + "insert");
                json.put("updateUrl", baseUrl + "update");
                json.put("deleteUrl", baseUrl + "delete");
            } else {
                json.put("saveUrl", baseUrl + "save");
            }

            json.put("nameField", nameField);
            json.put("codeField", codeField);
            boolean emptyCodeField = StringUtil.isEmpty(codeField);
            boolean hasSearch = !emptyCodeField || !StringUtil.isEmpty(nameField);
            if (hasSearch) {
                if (emptyCodeField) {
                    json.put("searchKeyField", nameField);
                } else {
                    json.put("searchKeyField", codeField);
                    json.put("codeFieldExp", codeField + ", ");
                }
            }
            content = StringUtil.replaceParams(json, content);
            content = content.replace("#{columnsrep}", buffer.toString());

            StringBuffer windowbuffer = new StringBuffer();
            windowbuffer.append("{\n" +
                    "\t\t\t\"configs\": {\n" +
                    // "\t\t\t\t\"layout\": \"absolute\",\n" +
                    "\t\t\t\t\"dialog\": \"true\",\n" +
                    "\t\t\t\t\"itemId\": \"win\",\n" +

                    "  \"defaults\": \"{margin: 4,labelAlign: 'right',style: 'float:left;'}\"," +


                    "\t\t\t\t\"createInstance\": \"false\",\n" +
                    "\t\t\t\t\"focusControl\": \"STRING_FIELD\",\n" +
                    "\t\t\t\t\"closeAction\": \"destroy\",\n" +
                    "\t\t\t\t\"width\": \"664\",\n" +
                    "\t\t\t\t\"title\": \"增删改查\",\n" +
                    "\t\t\t\t\"modal\": \"true\",\n" +
                    "\t\t\t\t\"height\": \"352\"\n" +
                    "\t\t\t},\n" +
                    "\t\t\t\"expanded\": true,\n" +
                    "\t\t\t\"children\": [");


            for (int a = 0; a < djons.length(); a++) {
                JSONObject jsondata = djons.getJSONObject(a);
                String namedata = jsondata.optString("name");
                String typedata = jsondata.optString("type");
                String usernuldata = jsondata.optString("useNull");
                String comment = jsondata.optString("comment");
                boolean flag = true;
                if (KVBuffer.getList(namedata).equals("[]")) {
                    flag = false;
                }
                windowbuffer.append(
                        "{\n" +
                                "\t\t\t\t\"configs\": {\n" +
                                "\t\t\t\t\t\"allowBlank\": \"false\",\n" +
                                "\t\t\t\t\t\"itemId\": \"" + namedata + "\",\n" );

                if(flag){

                    windowbuffer.append("  \"keyName\": \""+namedata+"\",");
                }




                windowbuffer.append(  "\t\t\t\t\t\"labelAlign\": \"right\",\n" +
                                "\t\t\t\t\t\"fieldLabel\": \"" + comment + "\",\n" +
                                "\t\t\t\t\t\"width\": \"312\",\n" +
                                "\t\t\t\t\t\"x\": \"8\",\n" +
                                "\t\t\t\t\t\"y\": \"16\",\n" +
                                "\t\t\t\t\t\"labelWidth\": \"90\",\n" +
                                "\t\t\t\t\t\"height\": \"22\"\n" +
                                "\t\t\t\t},\n" +
                                "\t\t\t\t\"expanded\": false,\n" +
                                "\t\t\t\t\"children\": [],\n");

                if (typedata.equals("number")) {
                    windowbuffer.append("\"type\": \"number\"\n");
                }
                if (typedata.equals("date")) {
                    windowbuffer.append("\"type\": \"date\"\n");
                } else if(flag){
                    windowbuffer.append("\"type\": \"combo\"\n");

                }else{
                    windowbuffer.append("\"type\": \"text\"\n");
                }


                if (a == djons.length() - 1) {
                    windowbuffer.append("}");
                } else {
                    windowbuffer.append("},");
                }
            }


            windowbuffer.append(
                    "],\n" +
                            "\t\t\t\"type\": \"window\"\n" +
                            "\t\t}");

            content = content.replace("#{windowresp}", windowbuffer.toString());
            content = content.replace("#{controller}", request.getAttribute("controllername").toString());
            content = content.replace("#{table_store_url}", "m?xwl=" + destfolderModule.getPath().toString().split("modules")[1].replace(".xwl", ""));


            JSONObject module = new JSONObject(content);
            FileUtil.syncSave(destModule, module.toString());
        }
    }
    /**
     * 创建基本增删改查
     *
     * @param request
     * @param response
     * @param name
     * @param title
     * @param iconCls
     * @param path
     * @param tableName
     * @param keyField
     * @param codeField
     * @param nameField
     * @param isDialog
     * @param hasUpload
     * @throws Exception
     */
    private static void addcrudmultiFormbasicFrame(HttpServletRequest request, HttpServletResponse response, String name, String title, String iconCls, File path, String tableName, String keyField, String codeField, String nameField, boolean isDialog, boolean hasUpload) throws Exception {
        File destFolder = new File(path, name);
        File destModule = new File(path, name + ".xwl");
        if (destModule.exists()) {
            throw new RuntimeException("模块“" + name + ".xwl”已经存在。");
        } else if (destFolder.exists()) {
            throw new RuntimeException("目录“" + name + "”已经存在。");
        } else {
            if (!StringUtil.isEmpty(codeField) && StringUtil.isEmpty(nameField)) {
                nameField = codeField;
                codeField = null;
            }
            File sourcePath;
            if (isDialog) {
                if (hasUpload) {
                    sourcePath = new File(Base.path, "wb/modules/dev/template/");
                } else {
                    sourcePath = new File(Base.path, "wb/modules/dev/template/");
                }
            } else {
                sourcePath = new File(Base.path, "wb/modules/dev/template/");
            }

            //==========创建查询文件start=========
            FileUtil.syncCreate(destFolder, true);
            File destfolderModule = new File(destFolder, "select" + name + ".xwl");
            FileUtil.syncCopyA(new File(sourcePath, "selectall.xwl"), destfolderModule);
            String contentchild = FileUtil.readString(destfolderModule);
            contentchild = contentchild.replace("#{tablename}", tableName);
            JSONObject modulechild = new JSONObject(contentchild);
            FileUtil.syncSave(destfolderModule, modulechild.toString());

            //======end=======

            FileUtil.syncCopyA(new File(sourcePath, "multiform_mainDetail.xwl"), destModule);

            File file = new File(path, "folder.json");
            JSONObject json = JsonUtil.readObject(file);
            JSONArray array = json.optJSONArray("index");
            array.put(name + ".xwl");
            array.put(name);


            //===========================================grid 列替换 start===============================
            StringBuffer buffer = new StringBuffer();

            buffer.append("{\n" +
                    "\"configs\": {\n" +
                    "\"itemId\": \"columns\"\n" +
                    "},\n" +
                    "\"expanded\": true,\n" +
                    "\"children\": [");
            request.setAttribute("tableName",request.getParameter("tableName"));

            String data = WebUtil.runresulte("m?xwl=dev/autogenControl/datasource", request, response);

            JSONObject datas = new JSONObject(data);
            JSONObject datama = new JSONObject(datas.optString("metaData"));
            JSONArray djons = new JSONArray(datama.optString("fields"));
            for (int a = 0; a < djons.length(); a++) {
                JSONObject jsondata = djons.getJSONObject(a);
                String namedata = jsondata.optString("name");
                String typedata = jsondata.optString("type");
                String usernuldata = jsondata.optString("useNull");
                String comment = jsondata.optString("comment");

                boolean flag = true;
                if (KVBuffer.getList(namedata).equals("[]")) {
                    flag = false;
                }
                buffer.append(" {\n" +
                        "        \"configs\": {" +
                        "\"itemId\": \"" + namedata + "\",\n" +
                        "\"dataIndex\": \"" + namedata + "\",\n" +
                        "\"width\": \"130\",\n" +
                        "\"text\": \"" + comment + "\",\n");
                if (flag) {//如果存在key

                    buffer.append(" \"keyName\": \"" + namedata + "\",");
                }
                buffer.append("\"titleAlign\": \"center\"" +
                        "},\n" +
                        "        \"expanded\": true,\n" +
                        " \"children\": [],"+
                        "\"type\": \"column\"\n");
                if (a == djons.length() - 1) {
                    buffer.append("}");
                } else {
                    buffer.append("},");
                }
            }
            buffer.append("],\n" +
                    "\"type\": \"array\"\n" +
                    "}");

            FileUtil.syncSave(file, json.toString());
            String baseUrl = FileUtil.getModuleUrl(destModule) + "/";
            String content = FileUtil.readString(destModule);
            json = new JSONObject();
            json.put("selectUrl", baseUrl + "select");
            json.put("searchUrl", baseUrl + "search");
            json.put("title", title);
            json.put("iconCls", iconCls);
            if (isDialog) {
                json.put("insertUrl", baseUrl + "insert");
                json.put("updateUrl", baseUrl + "update");
                json.put("deleteUrl", baseUrl + "delete");
            } else {
                json.put("saveUrl", baseUrl + "save");
            }

            json.put("nameField", nameField);
            json.put("codeField", codeField);
            boolean emptyCodeField = StringUtil.isEmpty(codeField);
            boolean hasSearch = !emptyCodeField || !StringUtil.isEmpty(nameField);
            if (hasSearch) {
                if (emptyCodeField) {
                    json.put("searchKeyField", nameField);
                } else {
                    json.put("searchKeyField", codeField);
                    json.put("codeFieldExp", codeField + ", ");
                }
            }
            content = StringUtil.replaceParams(json, content);
            content = content.replace("#{columnsrep}", buffer.toString());
            //===========================================grid 列替换 end===============================
            //===========================================grid 2列替换 start===============================
            StringBuilder bufferchild = new StringBuilder();

            bufferchild.append("{\n" +
                    "\"configs\": {\n" +
                    "\"itemId\": \"columns\"\n" +
                    "},\n" +
                    "\"expanded\": true,\n" +
                    "\"children\": [");
            request.setAttribute("tableName",request.getParameter("tablechildName"));

            String datachild = WebUtil.runresulte("m?xwl=dev/autogenControl/datasource", request, response);

            JSONObject dataschild = new JSONObject(datachild);
            JSONObject datametaachild = new JSONObject(dataschild.optString("metaData"));
            JSONArray djsonchild = new JSONArray(datametaachild.optString("fields"));
            for (int a = 0; a < djsonchild.length(); a++) {
                JSONObject jsondata = djsonchild.getJSONObject(a);
                String namedata = jsondata.optString("name");
                String typedata = jsondata.optString("type");
                String usernuldata = jsondata.optString("useNull");
                String comment = jsondata.optString("comment");

                if(comment==null||comment.equals("")){
                    comment=namedata;
                }

                boolean flag = true;
                if (KVBuffer.getList(namedata).equals("[]")) {
                    flag = false;
                }
                bufferchild.append(" {\n" +
                        "        \"configs\": {" +
                        "\"itemId\": \"" + namedata + "\",\n" +
                        "\"dataIndex\": \"" + namedata + "\",\n" +
                        "\"width\": \"130\",\n" +
                        "\"text\": \"" + comment + "\",\n");
                if (flag) {//如果存在key

                    bufferchild.append(" \"keyName\": \"" + namedata + "\",");
                }
                bufferchild.append("\"titleAlign\": \"center\"" +
                        "},\n" +
                        "        \"expanded\": true,\n" +
                        " \"children\": [],"+
                        "\"type\": \"column\"\n");
                if (a == djsonchild.length() - 1) {
                    bufferchild.append("}");
                } else {
                    bufferchild.append("},");
                }
            }
            bufferchild.append("],\n" +
                    "\"type\": \"array\"\n" +
                    "}");

          //  FileUtil.syncSave(file, json.toString());
          //  String baseUrlchild = FileUtil.getModuleUrl(destModule) + "/";
          //  String contentchild = FileUtil.readString(destModule);
//            json = new JSONObject();
//            json.put("selectUrl", baseUrl + "select");
//            json.put("searchUrl", baseUrl + "search");
//            json.put("title", title);
//            json.put("iconCls", iconCls);
//            if (isDialog) {
//                json.put("insertUrl", baseUrl + "insert");
//                json.put("updateUrl", baseUrl + "update");
//                json.put("deleteUrl", baseUrl + "delete");
//            } else {
//                json.put("saveUrl", baseUrl + "save");
//            }


         //   boolean emptyCodeFieldchild = StringUtil.isEmpty(codeField);
          //  boolean hasSearchchild = !emptyCodeFieldchild || !StringUtil.isEmpty(nameField);

           // content = StringUtil.replaceParams(json, content);
           // content = content.replace("#{columnsrepchild}", bufferchild.toString());
            content = content.replace("#{columnsrepchild}", bufferchild.toString());
            //===========================================grid 列替换 end===============================


            //===============================================窗口替换 start=============================================
            StringBuffer windowbuffer = new StringBuffer();
            windowbuffer.append("{\n" +
                    "\t\t\t\"configs\": {\n" +
                    // "\t\t\t\t\"layout\": \"absolute\",\n" +
                    "\t\t\t\t\"dialog\": \"true\",\n" +
                    "\t\t\t\t\"itemId\": \"win\",\n" +

                    "  \"defaults\": \"{margin: 4,labelAlign: 'right',style: 'float:left;'}\"," +


                    "\t\t\t\t\"createInstance\": \"false\",\n" +
                    "\t\t\t\t\"focusControl\": \"STRING_FIELD\",\n" +
                    "\t\t\t\t\"closeAction\": \"destroy\",\n" +
                    "\t\t\t\t\"width\": \"664\",\n" +
                    "\t\t\t\t\"title\": \"增删改查\",\n" +
                    "\t\t\t\t\"modal\": \"true\",\n" +
                    "\t\t\t\t\"height\": \"352\"\n" +
                    "\t\t\t},\n" +
                    "\t\t\t\"expanded\": true,\n" +
                    "\t\t\t\"children\": [");


            for (int a = 0; a < djons.length(); a++) {
                JSONObject jsondata = djons.getJSONObject(a);
                String namedata = jsondata.optString("name");
                String typedata = jsondata.optString("type");
                String usernuldata = jsondata.optString("useNull");
                String comment = jsondata.optString("comment");
                boolean flag = true;
                if (KVBuffer.getList(namedata).equals("[]")) {
                    flag = false;
                }
                windowbuffer.append(
                        "{\n" +
                                "\t\t\t\t\"configs\": {\n" +
                                "\t\t\t\t\t\"allowBlank\": \"false\",\n" +
                                "\t\t\t\t\t\"itemId\": \"" + namedata + "\",\n" );

                if(flag){

                    windowbuffer.append("  \"keyName\": \""+namedata+"\",");
                }




                windowbuffer.append(  "\t\t\t\t\t\"labelAlign\": \"right\",\n" +
                        "\t\t\t\t\t\"fieldLabel\": \"" + comment + "\",\n" +
                        "\t\t\t\t\t\"width\": \"312\",\n" +
                        "\t\t\t\t\t\"x\": \"8\",\n" +
                        "\t\t\t\t\t\"y\": \"16\",\n" +
                        "\t\t\t\t\t\"labelWidth\": \"90\",\n" +
                        "\t\t\t\t\t\"height\": \"22\"\n" +
                        "\t\t\t\t},\n" +
                        "\t\t\t\t\"expanded\": false,\n" +
                        "\t\t\t\t\"children\": [],\n");

                if (typedata.equals("number")) {
                    windowbuffer.append("\"type\": \"number\"\n");
                }
                if (typedata.equals("date")) {
                    windowbuffer.append("\"type\": \"date\"\n");
                } else if(flag){
                    windowbuffer.append("\"type\": \"combo\"\n");

                }else{
                    windowbuffer.append("\"type\": \"text\"\n");
                }


                if (a == djons.length() - 1) {
                    windowbuffer.append("}");
                } else {
                    windowbuffer.append("},");
                }
            }


            windowbuffer.append(
                    "],\n" +
                            "\t\t\t\"type\": \"window\"\n" +
                            "\t\t}");

            content = content.replace("#{windowresp}", windowbuffer.toString());
            //===============================================窗口替换 end=============================================


            content = content.replace("#{controller}", request.getAttribute("controllername").toString());
            content = content.replace("#{table_store_url}", "m?xwl=" + destfolderModule.getPath().toString().split("modules")[1].replace(".xwl", ""));


            JSONObject module = new JSONObject(content);
            FileUtil.syncSave(destModule, module.toString());
        }
    }

    /**
     * 创建表格编辑增删改查
     *
     * @param request
     * @param response
     * @param name
     * @param title
     * @param iconCls
     * @param path
     * @param tableName
     * @param keyField
     * @param codeField
     * @param nameField
     * @param isDialog
     * @param hasUpload
     * @throws Exception
     */
    private static void addeditgridCRUDFrame(HttpServletRequest request, HttpServletResponse response, String name, String title, String iconCls, File path, String tableName, String keyField, String codeField, String nameField, boolean isDialog, boolean hasUpload) throws Exception {
        File destFolder = new File(path, name);
        File destModule = new File(path, name + ".xwl");
        if (destModule.exists()) {
            throw new RuntimeException("模块“" + name + ".xwl”已经存在。");
        } else if (destFolder.exists()) {
            throw new RuntimeException("目录“" + name + "”已经存在。");
        } else {


            if (!StringUtil.isEmpty(codeField) && StringUtil.isEmpty(nameField)) {
                nameField = codeField;
                codeField = null;
            }
            File sourcePath;
            if (isDialog) {
                if (hasUpload) {
                    sourcePath = new File(Base.path, "wb/modules/dev/template/");
                } else {
                    sourcePath = new File(Base.path, "wb/modules/dev/template/");
                }
            } else {
                sourcePath = new File(Base.path, "wb/modules/dev/template/");
            }


            //==========创建查询文件start=========
            FileUtil.syncCreate(destFolder, true);
            File destfolderModule = new File(destFolder, "select" + name + ".xwl");
            FileUtil.syncCopyA(new File(sourcePath, "selectall.xwl"), destfolderModule);
            String contentchild = FileUtil.readString(destfolderModule);
            contentchild = contentchild.replace("#{tablename}", tableName);
            JSONObject modulechild = new JSONObject(contentchild);
            FileUtil.syncSave(destfolderModule, modulechild.toString());

            //======end=======


            FileUtil.syncCopyA(new File(sourcePath, "gridCrud.xwl"), destModule);
            File file = new File(path, "folder.json");
            JSONObject json = JsonUtil.readObject(file);
            JSONArray array = json.optJSONArray("index");
            array.put(name + ".xwl");
            array.put(name);
            StringBuffer buffer = new StringBuffer();

            buffer.append("{\n" +
                    "\"configs\": {\n" +
                    "\"itemId\": \"columns\"\n" +
                    "},\n" +
                    "\"expanded\": true,\n" +
                    "\"children\": [");
            request.setAttribute("tableName",request.getParameter("tableName"));

            String data = WebUtil.runresulte("m?xwl=dev/autogenControl/datasource", request, response);
            JSONObject datas = new JSONObject(data);
            JSONObject datama = new JSONObject(datas.optString("metaData"));
            JSONArray djons = new JSONArray(datama.optString("fields"));


            for (int a = 0; a < djons.length(); a++) {
                JSONObject jsondata = djons.getJSONObject(a);
                String namedata = jsondata.optString("name");

                boolean flag = true;
                if (KVBuffer.getList(namedata).equals("[]")) {
                    flag = false;
                }

                String text = jsondata.optString("comment");
                String typedata = jsondata.optString("type");
                String usernuldata = jsondata.optString("useNull");

                buffer.append(" {\n" +
                        "\"configs\": {" +
                        "\"itemId\": \"" + namedata + "\",\n" +
                        "\"dataIndex\": \"" + namedata + "\",\n" +
                        "\"width\": \"130\",\n" +
                        "\"text\": \"" + text + "\",\n");

                if (flag) {//如果存在key

                    buffer.append(" \"keyName\": \"" + namedata + "\",");
                }


                buffer.append("\"titleAlign\": \"center\"" +
                        "},\n" +
                        "        \"expanded\": true,\n" +
                        "        \"children\": [{\n" +
                        "         \"configs\": {\"itemId\": \"editor\"");

                if (flag) {//如果存在key

                    buffer.append(",\n" +
                            "          \"keyName\": \"" + namedata + "\",\n" +
                            "          \"displayField\": \"V\",\n" +
                            "          \"valueField\": \"K\"");
                }


                buffer.append("" +
                        "},\n" +
                        "         \"expanded\": false,\n" +
                        "         \"children\": [],\n");

                if (typedata.equals("number")) {
                    buffer.append("\"type\": \"number\"\n");
                }
                if (typedata.equals("date")) {
                    buffer.append("\"type\": \"date\"\n");
                } else if (flag) {
                    buffer.append("\"type\": \"combo\"\n");
                } else {
                    buffer.append("\"type\": \"text\"\n");
                }


                buffer.append(" }],\"type\": \"column\"\n");
                if (a == djons.length() - 1) {
                    buffer.append("}");
                } else {
                    buffer.append("},");
                }
            }


            buffer.append("],\n" +
                    "\"type\": \"array\"\n" +
                    "}");

            FileUtil.syncSave(file, json.toString());
            String baseUrl = FileUtil.getModuleUrl(destModule) + "/";
            String content = FileUtil.readString(destModule);
            json = new JSONObject();
            json.put("selectUrl", baseUrl + "select");
            json.put("searchUrl", baseUrl + "search");
            json.put("title", title);
            json.put("iconCls", iconCls);
            if (isDialog) {
                json.put("insertUrl", baseUrl + "insert");
                json.put("updateUrl", baseUrl + "update");
                json.put("deleteUrl", baseUrl + "delete");
            } else {
                json.put("saveUrl", baseUrl + "save");
            }

            json.put("nameField", nameField);
            json.put("codeField", codeField);
            boolean emptyCodeField = StringUtil.isEmpty(codeField);
            boolean hasSearch = !emptyCodeField || !StringUtil.isEmpty(nameField);
            if (hasSearch) {
                if (emptyCodeField) {
                    json.put("searchKeyField", nameField);
                } else {
                    json.put("searchKeyField", codeField);
                    json.put("codeFieldExp", codeField + ", ");
                }
            }
            content = StringUtil.replaceParams(json, content);
            content = content.replace("#{columnsrep}", buffer.toString());


            content = content.replace("#{entityname}", request.getAttribute("entityname").toString());
            content = content.replace("#{servicebean}", request.getAttribute("controllername").toString());
            content = content.replace("#{table_store_url}", "m?xwl=" + destfolderModule.getPath().toString().split("modules")[1].replace(".xwl", ""));

            JSONObject module = new JSONObject(content);
            FileUtil.syncSave(destModule, module.toString());
        }
    }


    public static synchronized void addFrame(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String name = request.getParameter("name");
        String title = request.getParameter("title");
        String iconCls = request.getParameter("iconCls");
        File path = new File(request.getParameter("path"));
        String frameType = request.getParameter("frameType");
        if (!FileUtil.isAncestor(Base.modulePath, path)) {
            throw new Exception("模块文件必须创建于模块目录。");
        } else {
            if ("crud".equals(frameType)) {
                addeditgridCRUDFrame(request, response, name, title, iconCls, path, request.getParameter("tableName"), request.getParameter("keyField"), request.getParameter("codeField"), request.getParameter("nameField"), Boolean.parseBoolean(request.getParameter("dialog")), Boolean.parseBoolean(request.getParameter("hasUpload")));
            }
            if ("crudbasic".equals(frameType)) {
                addbasiceCRUDFrame(request, response, name, title, iconCls, path, request.getParameter("tableName"), request.getParameter("keyField"), request.getParameter("codeField"), request.getParameter("nameField"), Boolean.parseBoolean(request.getParameter("dialog")), Boolean.parseBoolean(request.getParameter("hasUpload")));
            } if ("crudmultiFormbasic".equals(frameType)) {
                addcrudmultiFormbasicFrame(request, response, name, title, iconCls, path, request.getParameter("tableName"), request.getParameter("keyField"), request.getParameter("codeField"), request.getParameter("nameField"), Boolean.parseBoolean(request.getParameter("dialog")), Boolean.parseBoolean(request.getParameter("hasUpload")));
            }
        }
    }
}
