报表

作者: wsj1211 | 来源:发表于2021-06-01 10:12 被阅读0次

项目启动类:

位置:ureport-cy/src/main/java/org/rcisoft/UreportApplication.java
修改连接内置数据源:ureport-cy/src/main/resources/application.yml

spring:
  profiles:
    active: default
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:mysql://101.36.228.164:31104/in_first?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&autoReconnect=true&failOverReadOnly=false
    username: root
    password: ijwkxk
    max-active: 100
    max-idle: 20
    min-idle: 8
    initial-size: 10
    testConnectionOnCheckin: true
    testConnectionOnCheckout: true
    idleConnectionTestPeriod: 18000

内置数据源选择


image.png

报表信息保存和查看权限验的数据库连接:
ureport-jdbc/src/main/java/org/rcisoft/util/DBUtil.java

    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://101.36.228.164:31104/zt_first?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false";
    private static String user = "root";
    private static String password = "ijwkxk";

    // 1. 获取驱动
    static {
        try {
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 2. 创建连接
    public static Connection get_Conn() throws SQLException {
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println("数据库连接成功" + conn);
        return conn;
    }

    // 3. 关闭连接
    public static void get_CloseConn(ResultSet rs, PreparedStatement pstm, Connection conn) throws SQLException {
        if(rs !=null){
            rs.close();
        }

        if(pstm !=null){
            pstm.close();
        }

        if(conn !=null){
            conn.close();
        }
    }


保存

saveReportFile 根据主键更新报表zt_report信息

public  void update(ZtReport ztReport,List<ZtReportSearch> ztReportSearches){
        try {
            con = DBUtil.get_Conn();
            con.setAutoCommit(false);
            pstm = con.prepareStatement("update zt_report  set update_date = sysdate(), content = ?,css_file=? where business_id= ?");
            pstm.setString(1,ztReport.getContent());
            pstm.setString(2,ztReport.getCss_file());
            pstm.setString(3,ztReport.getBusiness_id());
            int i = pstm.executeUpdate();
            ZtReportSearchService ztReportSearchService = new ZtReportSearchService();
           ztReportSearchService.delReportSearch(ztReport.getBusiness_id());
           if (null != ztReportSearches && ztReportSearches.size() >0) {
                for (ZtReportSearch ztReportSearch : ztReportSearches) {
                    ztReportSearch.setReport_id(ztReport.getBusiness_id());
                }
                ztReportSearchService.insertBatch(ztReportSearches,con);
            }
            con.commit();
        } catch (SQLException e) {
            try {
                // 若出现异常,对数据库中所有已完成的操作全部撤销,则回滚到事务开始状态
                if(!con.isClosed()){
                    con.rollback();//当异常发生执行catch中SQLException时,记得要rollback(回滚);
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            if(pstm!=null) {
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }else if(con!=null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

预览

1 权限验证
获取token 从cookies中拿到token 解析后 得到userId,查询此userId 是否绑定了报表菜单

private HtmlReport loadReport(HttpServletRequest req) throws ServletException, IOException {
    // 添加权限验证
        Cookie[] cookies = req.getCookies();
        String token = "";
//      String token = "eyJhbGciOiJIUzUxMiJ9.eyJuaWNrTmFtZSI6IuaWueeOsiIsImRlcHRJZCI6NTIsInVzZXJOYW1lIjoi5pa5546yIiwidXNlcklkIjo4MywibG9naW5fdXNlcl9rZXkiOiJiOTE3OTkyZC01ZjY4LTQ3OWQtYjM5Ny1iODNkMTE4MWQwNGIifQ.OQRqsjeDgDCEb6GH4kRSD5HADwGVZ2tZeNbBm1nZ8Ky560DgwG3AuEWW1DlrsYtWqsPHX-FmdBaR5PYCjrhPXA";
        if (null != cookies){
            for(Cookie c :cookies ){
                if (c.getName().equals("Admin-Token")){
                    token = c.getValue();
                }
            }
        }
        // 拿到userId
        String userId = this.getUserIdByToken(token);
        if (StrUtil.isNotBlank(userId)){
            if (userId.equals("1")){
                return getHtmlReport(req);
            }
            // 验证userId 是否有访问权限
            String menu=req.getParameter("_m"); //menu_name
            ZtReportService ztReportService  = new ZtReportService();
            boolean hasPermiss = ztReportService.getPermissionByUserIdAndMenu(userId,menu);
            System.out.println("-------------"+hasPermiss+"---------------------");
            if (hasPermiss){
                return getHtmlReport(req);
            }
        }
        HtmlReport htmlReport = new HtmlReport();
        htmlReport.setContent(PermissionConstant.NO_PREVIEW_PERMISSION);
        return htmlReport;

    }


private String getUserIdByToken(String token) {
        if (StrUtil.isBlank(token)) {
            return null;
        } else {
            token = token.replace("Bearer ", "");
            //校验token
            Map<String, Object> map = JWTUtil.extractInfo(token, SECRET);
            String userId = map.get(TokenInfoConstants.USER_ID) == null ? "1111" : map.get(TokenInfoConstants.USER_ID).toString();
            System.out.println(userId);
            return userId;
        }
    }

ztReportService.java

public boolean getPermissionByUserIdAndMenu(String userId,String menu){
        try {
            con = DBUtil.get_Conn();
            pstm =con.prepareStatement("SELECT sm.* FROM `sys_role_menu` srm left join sys_role sr on sr.role_id = srm.role_id " +
                    " left join sys_menu sm on sm.menu_id = srm.menu_id " +
                    "left join sys_user_role sur on sur.role_id= sr.role_id " +
                    "where sur.user_id =  ? and sm.menu_name = ?");
            pstm.setString(1,userId);
            pstm.setString(2,menu);
            ResultSet rs = pstm.executeQuery();
            rs.last();
            if (rs.getRow() >0){
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } else if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

下载

public void buildWord(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String file=req.getParameter("_u");
        String isContTemp=req.getParameter("_tmp");
        file=decode(file);
        if(StringUtils.isBlank(file)){
            throw new ReportComputeException("Report file can not be null.");
        }
        OutputStream outputStream=resp.getOutputStream();
        try {
            String fileName=req.getParameter("_n");
            fileName=buildDownloadFileName(file, fileName, ".docx");
            fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1");
            resp.setContentType("application/octet-stream;charset=ISO8859-1");
            resp.setHeader("Content-Disposition","attachment;filename=\"" + fileName + "\"");
            ZtReportService ztReportService = new ZtReportService();
            ZtReportDto ztReport = ztReportService.findById(file,new ArrayList<>(),"","");
            String content = ztReport.getContent();
            if (!(!org.springframework.util.StringUtils.isEmpty(isContTemp) && "0".equals(isContTemp)) && !org.springframework.util.StringUtils.isEmpty(ztReport.getContent_temp())) {
                content = ztReport.getContent_temp();
            }
            InputStream inputStream= IOUtils.toInputStream(content,"UTF-8");
            ReportParser reportParser = new ReportParser();
            ReportDefinition reportDefinition=reportParser.parse(inputStream,"p");
            reportRender.rebuildReportDefinition(reportDefinition);
            Report report=reportBuilder.buildReport(reportDefinition, new HashMap<>());
            wordProducer.produce(report, outputStream);
        }catch(Exception ex) {
            throw new ReportException(ex);
        }finally {          
            outputStream.flush();
            outputStream.close();
        }
    }
    

分页预览

ReportBuilder.java

for(int i=0;i<rowSize;i++){
                Row row=rows.get(i);
                int rowRealHeight=row.getRealHeight();
                if(rowRealHeight==0){
                    continue;
                }
                Band band=row.getBand();
                if(band!=null){
                    String rowKey=row.getRowKey();
                    int index=-1;
                    if(band.equals(Band.headerrepeat)){
                        for(int j=0;j<pageRepeatHeaders.size();j++){
                            Row headerRow=pageRepeatHeaders.get(j);
                            if(headerRow.getRowKey().equals(rowKey)){
                                index=j;
                                break;
                            }
                        }
                        pageRepeatHeaders.remove(index);
                        pageRepeatHeaders.add(index,row);
                    }else if(band.equals(Band.footerrepeat)){
                        for(int j=0;j<pageRepeatFooters.size();j++){
                            Row footerRow=pageRepeatFooters.get(j);
                            if(footerRow.getRowKey().equals(rowKey)){
                                index=j;
                                break;
                            }
                        }
                        pageRepeatFooters.remove(index);
                        pageRepeatFooters.add(index,row);
                    } 
                    continue;
                }
                rowHeight+=rowRealHeight+1;
                pageRows.add(row);
                row.setPageIndex(pageIndex);
                boolean overflow=false;
                if((i+1)<rows.size()){
                    Row nextRow=rows.get(i+1);
                    // 限制每页数量--分页
                    if (StringUtils.isNotBlank(_i) && pageRows.size() >= pageSize){
//                  if((rowHeight+nextRow.getRealHeight()) > height){
                        overflow=true;
                    }else if(StringUtils.isBlank(_i) && (rowHeight+nextRow.getRealHeight()) > height) {
                        overflow = true;
                    }
                }
                if(!overflow && row.isPageBreak()){
                    overflow=true;
                }
                if(overflow){
                    Page newPage=buildPage(pageRows,pageRepeatHeaders,pageRepeatFooters,titleRows,pageIndex,report);
                    pageIndex++;
                    pages.add(newPage);
                    rowHeight=repeatHeaderRowHeight+repeatFooterRowHeight;
                    pageRows=new ArrayList<Row>();
                }
            }
            if(pageRows.size()>0){
                Page newPage=buildPage(pageRows,pageRepeatHeaders,pageRepeatFooters,titleRows,pageIndex,report);
                pages.add(newPage);
            }

筛选

1 添加筛选数据到zt_report_search表中

 public void insertBatch(List<ZtReportSearch> list,Connection connection ){

        if (null != list && !list.isEmpty()){
            try {
                connection = DBUtil.get_Conn();
                PreparedStatement statement = connection.prepareStatement("INSERT INTO zt_report_search(business_id,field_name,access_field_name," +
                        "field_type,create_date,create_by,update_by,update_date,del_flag,flag,remarks,report_id,sort,filter) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)");
                for (ZtReportSearch ztReportSearch : list){
                    statement.setString(1,UUID.randomUUID().toString().replace("-",""));
                    statement.setString(2,ztReportSearch.getField_name());
                    statement.setString(3,ztReportSearch.getAccess_field_name());
                    statement.setString(4,ztReportSearch.getField_type());
                    statement.setDate(5,new Date(System.currentTimeMillis()));
                    statement.setString(6,ztReportSearch.getCreate_by());
                    statement.setString(7,ztReportSearch.getUpdate_by());
                    statement.setDate(8,new Date(System.currentTimeMillis()));
                    statement.setString(9,"0");
                    statement.setString(10,"1");
                    statement.setString(11,ztReportSearch.getRemarks());
                    statement.setString(12,ztReportSearch.getReport_id());
                    statement.setString(13,ztReportSearch.getSort());
                    statement.setString(14,ztReportSearch.getFilter());
                    statement.addBatch();
                }
                statement.executeBatch();
                connection.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                } else if (con != null) {
                    try {
                        con.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

2 功能实现

    public ZtReportDto findById(String businessId,List<ZtReportSearchParamDto> list,String sort,String isContTemp){
        try {
            con = DBUtil.get_Conn();
            String sqlType = this.getDataBaseType(con);
            pstm =con.prepareStatement("select * from zt_report where del_flag=0 and flag =1 and " +
                    " business_id= ?");
            pstm.setString(1,businessId);
            ResultSet rs = pstm.executeQuery();
            ZtReportDto ztReport = resultToBean(rs,ZtReportDto.class);
            pstm =con.prepareStatement("select * from zt_report_search where del_flag=0 and flag =1 and " +
                    " report_id= ? ");
            pstm.setString(1,businessId);
            rs = pstm.executeQuery();
            List<ZtReportSearch> reportSearchList = resultToList(rs,ZtReportSearch.class);
            ztReport.setZtReportSearchList(reportSearchList);

            if ((null !=list && list.size() > 0) || !StringUtils.isEmpty(sort)){
                String content = ztReport.getContent();
                if (!(!StringUtils.isEmpty(isContTemp) && "0".equals(isContTemp)) && !StringUtils.isEmpty(ztReport.getContent_temp())) {
                    content = ztReport.getContent_temp();
                }
                String preSql = content.split("<sql>")[0];
                String afterSql = content.split("<sql>")[1].split("]]></sql>")[1];
                String preq = content.split("<sql>")[1];
                String contentSql =preq.split("]]></sql>")[0];
                // 有where的话 直接在where 后拼接参数 表是否有别名
                String beforeWhere = "";
                String endWhere = "";
                if (null !=list && list.size() > 0){
                    StringBuffer whereSqlBuffer = new StringBuffer();
                    whereSqlBuffer.append(" where ");
                    for (ZtReportSearchParamDto paramDto : list) {
                        if (!StringUtils.isEmpty(paramDto.getField_value())){
//                            whereSqlBuffer.append(" where ");
                            switch (paramDto.getField_type()){
                                case FUZZY_QUERY:
                                    whereSqlBuffer.append(" instr(");
                                    whereSqlBuffer.append(paramDto.getAccess_field_name());
                                    whereSqlBuffer.append(",'");
                                    whereSqlBuffer.append(paramDto.getField_value());
                                    whereSqlBuffer.append("')>0 and ");
                                    break;
                                case PRECISE_QUERY:
                                    whereSqlBuffer.append(" ");
                                    whereSqlBuffer.append(paramDto.getAccess_field_name());
                                    whereSqlBuffer.append("=");
                                    whereSqlBuffer.append("'");
                                    whereSqlBuffer.append(paramDto.getField_value());
                                    whereSqlBuffer.append("'");
                                    whereSqlBuffer.append(" and ");
                                    break;
                                case RANGE_INPUT_QUERY:
                                    whereSqlBuffer.append(" ");
                                    whereSqlBuffer.append(paramDto.getAccess_field_name());
                                    whereSqlBuffer.append(" between ");
                                    whereSqlBuffer.append("'");
                                    whereSqlBuffer.append(paramDto.getField_value());
                                    whereSqlBuffer.append("'");
                                    whereSqlBuffer.append(" and ");
                                    whereSqlBuffer.append("'");
                                    whereSqlBuffer.append(paramDto.getField_value_end());
                                    whereSqlBuffer.append("'");
                                    whereSqlBuffer.append(" and ");
                                    break;
                                case RANGE_DATE_QUERY:
                                    if(!StringUtils.isEmpty(paramDto.getField_value_end())){
                                        DateTime endDate = DateUtil.offsetDay(DateUtil.parseDate(paramDto.getField_value_end()),1);
                                        paramDto.setField_value_end(DateUtil.format(endDate,"yyyy-MM-dd"));
                                    }
                                    whereSqlBuffer.append(" ");
                                    whereSqlBuffer.append(paramDto.getAccess_field_name());
                                    whereSqlBuffer.append(" between ");
                                    if (sqlType.equals("MYSQL")){
                                        whereSqlBuffer.append(" STR_TO_DATE(' ");
                                        whereSqlBuffer.append(paramDto.getField_value());
                                        whereSqlBuffer.append(" ','%Y-%m-%d') ");
                                        whereSqlBuffer.append(" and ");
                                        whereSqlBuffer.append(" STR_TO_DATE(' ");
                                        whereSqlBuffer.append(paramDto.getField_value_end());
                                        whereSqlBuffer.append(" ','%Y-%m-%d') ");
                                    }
                                    if (sqlType.equals("ORACLE")){
                                        whereSqlBuffer.append(" TO_DATE(' ");
                                        whereSqlBuffer.append(paramDto.getField_value());
                                        whereSqlBuffer.append(" ','yyyy-MM-dd') ");
                                        whereSqlBuffer.append(" and ");
                                        whereSqlBuffer.append(" TO_DATE(' ");
                                        whereSqlBuffer.append(paramDto.getField_value_end());
                                        whereSqlBuffer.append(" ','yyyy-MM-dd') ");
                                    }

                                    whereSqlBuffer.append(" and ");
                                    break;
                                default:
                                    break;
                            }
                        }

                    }
                    if (contentSql.toLowerCase().contains("where")) {
                        beforeWhere = contentSql.substring(0, contentSql.toLowerCase().indexOf("where"));
                        endWhere = contentSql.substring(beforeWhere.length()+5,contentSql.length());
                    } else if (contentSql.toLowerCase().contains("group")) {
                        beforeWhere = contentSql.substring(0, contentSql.toLowerCase().indexOf("group"));
                        endWhere = contentSql.substring(contentSql.toLowerCase().indexOf("group"));
                        whereSqlBuffer.append(" 1=1 ");
                        whereSqlBuffer.append(" group ");
                    } else if (contentSql.toLowerCase().contains("order")) {
                        beforeWhere = contentSql.substring(0, contentSql.toLowerCase().indexOf("order"));
                        endWhere = contentSql.substring(contentSql.toLowerCase().indexOf("order"));
                        whereSqlBuffer.append(" 1=1 ");
                        whereSqlBuffer.append(" order ");
                    } else if (contentSql.toLowerCase().contains("limit")) {
                        beforeWhere = contentSql.substring(0, contentSql.toLowerCase().indexOf("limit"));
                        endWhere = contentSql.substring(contentSql.toLowerCase().indexOf("limit"));
                        whereSqlBuffer.append(" 1=1 ");
                        whereSqlBuffer.append(" limit ");
                    }else {
                        whereSqlBuffer.append(" 1=1 ");
                    }
                    contentSql = beforeWhere + contentSql + whereSqlBuffer.toString()+endWhere;
                }
                if (!StringUtils.isEmpty(sort)) {
                    StringBuffer sortSql = new StringBuffer();
//                    sortSql.append( "order by ");
                    sortSql.append(sort);
                    if (contentSql.toLowerCase().contains("order")) {
                        sortSql.append(", ");
                        beforeWhere = contentSql.substring(0, contentSql.toLowerCase().indexOf("order"));
                        endWhere = contentSql.substring(beforeWhere.length()+8,contentSql.length());
                    }else if (contentSql.toLowerCase().contains("limit")){
                        sortSql.append(" ");
                        beforeWhere = contentSql.substring(0, contentSql.toLowerCase().indexOf("limit"));
                        endWhere = contentSql.substring(beforeWhere.length()+5,contentSql.length());
                    }
                    contentSql = beforeWhere+ contentSql+ sortSql + endWhere;
                }
                ztReport.setContent(preSql+"<sql>"+contentSql+"]]></sql>"+afterSql);
                ztReport.setContent_temp(preSql+"<sql>"+contentSql+"]]></sql>"+afterSql);
            }
            return ztReport;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } else if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

注意:设计页面时 不保存进行预览 先更新zt_report表中content_temp字段
预览渲染页面用content_temp中的内容渲染。

con = DBUtil.get_Conn();
            con.setAutoCommit(false);
            pstm = con.prepareStatement("update zt_report  set update_date = sysdate(), content = ?,css_file=? where business_id= ?");
            pstm.setString(1,ztReport.getContent());
            pstm.setString(2,ztReport.getCss_file());
            pstm.setString(3,ztReport.getBusiness_id());
            pstm.executeUpdate();
            ZtReportSearchService ztReportSearchService = new ZtReportSearchService();
            ztReportSearchService.delReportSearch(ztReport.getBusiness_id());
            if (null != ztReportSearches && ztReportSearches.size() >0) {
                for (ZtReportSearch ztReportSearch : ztReportSearches) {
                    ztReportSearch.setReport_id(ztReport.getBusiness_id());
                }
                ztReportSearchService.insertBatch(ztReportSearches,con);
            } 
            con.commit();

在报表列表页预览时添加参数_tmp=0 即从zt_report表中 content字段中的值渲染页面。

ZtReportDto ztReport = ztReportService.findById(file,new ArrayList<>(),"","");
            String content = ztReport.getContent();
            if (!(!org.springframework.util.StringUtils.isEmpty(isContTemp) && "0".equals(isContTemp)) && !org.springframework.util.StringUtils.isEmpty(ztReport.getContent_temp())) {
                content = ztReport.getContent_temp();
            }

前端相关

ureport2-js为修改js的地方,修改完相关js后,在此文件夹下运行npm run build进行构建,webpack打包后的文件会生成在ureport-parent\ureport-console\src\main\resources\ureport-asserts\js中。

如果需要修改html文件,html文件的相关地址在ureport-parent\ureport-console\src\main\resources\ureport-html目录下。

筛选

designer页面

设计designer页面配置功能,在ureport2-js/src/table/ContextMenu.js下进行配置。代码部分如下:

else if (key==='filter_item') {
    const selected=this.getSelected();
    const startRow=selected[0],endRow=selected[2],startCol=selected[1],endCol=selected[3];
    let cell=_this.context.getCell(startRow,startCol);
    const fieldName = cell.value.value
    const cellName = cell.name
    const sessionStringValue = sessionStorage.getItem('filterItemObject')
    const sessionValue = sessionStringValue ? JSON.parse(sessionStringValue) : null
    // const rowHeight=this.getRowHeight(startRow);
    const dialog=new FilterItemDialog();
    console.log(cell)
    dialog.show(function(filterItemObj){
        // _this.updateSettings({
        //     rowHeights:rowHeights,
        //     manualRowResize:rowHeights
        // });
        let data = {}
        console.log(cell, selected, filterItemObj)
        if (sessionValue) {
            sessionValue[cellName] = filterItemObj
            data = Object.assign({}, sessionValue)
        } else {
            data = {
                [cellName]: filterItemObj
            }
        }
        sessionStorage.setItem('filterItemObject', JSON.stringify(data))
    },{fieldName, sessionValue, cellName});
    setDirty();
}

代码中有了一个 new FilterItemDialog() 对象,该对象为Class类,文件存放在ureport2-js/src/dialog目录下。

preview页面

ureport2-js/src/preview.js_buildSearchForm函数是用来构建筛选项dom的。代码如下:

function _buildSearchForm(ztReportSearchList) {
    const _ureport_table_search_form = $('#_ureport_table_search_form')
    const sessionZtReportSearchList = getFilterItemObjectSearchList()
    if (sessionZtReportSearchList && sessionZtReportSearchList.length > 0) {
        ztReportSearchList = sessionZtReportSearchList
    }
    if (!ztReportSearchList || ztReportSearchList.length === 0) {
        _ureport_table_search_form.html('')
        return
    }
    let searchFormDom = ''
    const DATE_LIST_ID_ARRAY = []
    if (typeof ztReportSearchList === 'string') {
        ztReportSearchList = JSON.parse(ztReportSearchList)
    }
    ztReportSearchList.forEach(item => {
        const {business_id, field_name, field_type, access_field_name, filter, sort} = item
        let inputFragment = ''
        if (field_type === '0' || field_type === '1') {
            inputFragment = `<input data-pure-clear-button class="form-control" id="${business_id}">`
        }else if (field_type === '2') {
            inputFragment = `<input class="form-control" id="${business_id}_first" > - <input class="form-control" id="${business_id}_second">`
        }else if (field_type === '3') {
            inputFragment = `<input  id="${business_id}_startDate" type="text" class="form-control" > - <input  id="${business_id}_endDate" type="text" class="form-control">`
            DATE_LIST_ID_ARRAY.push(business_id)
        }
        let htmlFragment = `<div class="form-group form-item" data-filedType="${field_type}" data-id="${business_id}" data-accessFieldName="${access_field_name}" data-fieldName="${field_name}">
                                <label for="${business_id}">${field_name}:</label>
                                ${inputFragment}
                              </div>`
        if (filter === '0') {
            htmlFragment = ''
        }
        searchFormDom += htmlFragment
    })
    searchFormDom += `<button id="search-form-btn" class="btn btn-primary">查询</button>`
    const inlineSearchDom = `<form id="search-form" onSubmit="return false;" class="form-inline search-form">${searchFormDom}</form>`
    _ureport_table_search_form.html(inlineSearchDom)
    setTimeout(()=> {
        DATE_LIST_ID_ARRAY.forEach(id => {
            console.log(id)
            $('#'+ id + '_startDate').datetimepicker({
                format: 'yyyy-mm-dd',//显示格式
                startView:2,
                minView:2,
                maxView :2,
                language: 'zh-CN',
                autoclose: 1,//选择后自动关闭
                clearBtn:true,//清除按钮
            });
            $('#'+ id + '_endDate').datetimepicker({
                format: 'yyyy-mm-dd',//显示格式
                startView:2,
                minView:2,
                maxView :2,
                language: 'zh-CN',
                autoclose: 1,//选择后自动关闭
                clearBtn:true,//清除按钮
            });
        })
        if (ztReportSearchList) {
            const sessionZtReportSearchListJsonParse = typeof sessionZtReportSearchList === 'string' ? JSON.parse(sessionZtReportSearchList) : sessionZtReportSearchList
            const fromGroup = $('#search-form .form-group')
            ztReportSearchList.forEach(item => {
                const { field_value, field_value_end, business_id, field_type } = item
                if (field_type === '0' || field_type === '1') {
                     $(fromGroup).find(`#${business_id}`).val(field_value)
                }else if (field_type === '2') {
                    $(fromGroup).find(`#${business_id}_first`).val(field_value)
                    $(fromGroup).find(`#${business_id}_second`).val(field_value_end)
                }else if (field_type === '3') {
                    console.log('寒夜剩我一个人,等青春')
                    console.log(field_value, field_value_end)
                      $(fromGroup).find(`#${business_id}_startDate`).val(field_value)
                      $(fromGroup).find(`#${business_id}_endDate`).val(field_value_end)
                }
            })
        }
        $('#search-form-btn').on('click', () => {
            const fromGroup = $('#search-form .form-group')
            const dataArray = []
            $(fromGroup).each(function (){
                const field_type = $(this).data('filedtype') + ''
                const business_id = $(this).data('id')
                const access_field_name = $(this).data('accessfieldname')
                const field_name = $(this).data('fieldname')
                let field_value = ''
                let field_value_end = ''
                if (field_type === '0' || field_type === '1') {
                    field_value = $(this).find(`#${business_id}`).val()
                }else if (field_type === '2') {
                    field_value = $(this).find(`#${business_id}_first`).val()
                    field_value_end = $(this).find(`#${business_id}_second`).val()
                }else if (field_type === '3') {
                    field_value = $(this).find(`#${business_id}_startDate`).val()
                    field_value_end = $(this).find(`#${business_id}_endDate`).val()
                    console.log($(this).find(`#${business_id}_startDate`))
                    console.log($(this).find(`#${business_id}_endDate`))
                }
                dataArray.push({
                    field_type,
                    access_field_name,
                    field_value,
                    field_value_end,
                    business_id,
                    field_name
                })
            })
            // searchTableData(JSON.stringify(dataArray))
            sessionStorage.setItem('ztReportSearchList', JSON.stringify(dataArray))
            const parameters = window.buildLocationSearchParameters('_i');
            let url = window._server + `/preview${parameters}`;
            const pageSelector = $(`#pageSelector`);
            console.log(pageSelector)
            if (pageSelector.length > 0) {
                url += "&_i=1";
            }
            window.open(url, '_self');
        })
    }, 500)
}

排序

designer页面

同筛选,排序只是 new FilterItemDialog()的一个小选项。

preview页面

ureport2-js/src/preview.js_buildSearchForm函数是用来构建筛选项dom的。代码如下:

// 新增sort icon
function addSortIcon(ztReportSearchList) {
    const sessionZtReportSearchList = getFilterItemObjectSearchList()
    if (sessionZtReportSearchList && sessionZtReportSearchList.length > 0) {
        ztReportSearchList = sessionZtReportSearchList
    }
    if (typeof ztReportSearchList === 'string') {
        ztReportSearchList = JSON.parse(ztReportSearchList)
    }
    if (ztReportSearchList && ztReportSearchList.length > 0) {
        ztReportSearchList.forEach(item => {
            const {remarks, field_name, access_field_name} = item
            const dataSort = sessionStorage.getItem('_'+remarks+'_icon_sort') ? sessionStorage.getItem('_'+remarks+'_icon_sort') : 'desc'
            const newHtml = `${field_name}<i id="_${remarks}_icon" data-sort="${dataSort}" class="glyphicon glyphicon-sort sort-icon" style="font-size: 16px">`

            $('._' + remarks).html(newHtml)
            $(`#_${remarks}_icon`).on('click', function (){
                const sortRules = $(this).data('sort')
                if (sortRules === 'desc') {
                    $(this).data('sort', 'asc')
                    sessionStorage.setItem(`_${remarks}_icon_sort`, 'asc')
                }else {
                    $(this).data('sort', 'desc')
                    sessionStorage.setItem(`_${remarks}_icon_sort`, 'desc')
                }
                const sort = `order by ${access_field_name} ${sortRules}`
                const fromGroup = $('#search-form .form-group')
                const dataArray = []
                $(fromGroup).each(function (){
                    const field_type = $(this).data('filedtype') + ''
                    const business_id = $(this).data('id')
                    const access_field_name = $(this).data('accessfieldname')
                    let field_value = ''
                    let field_value_end = ''
                    console.log(typeof field_type)
                    if (field_type === '0' || field_type === '1') {
                        field_value = $(this).find(`#${business_id}`).val()
                    }else if (field_type === '2') {
                        field_value = $(this).find(`#${business_id}_first`).val()
                        field_value_end = $(this).find(`#${business_id}_second`).val()
                    }else if (field_type === '3') {
                        field_value = $(this).find(`#${business_id}_startDate`).val()
                        field_value_end = $(this).find(`#${business_id}_endDate`).val()
                        console.log($(this).find(`#${business_id}_startDate`))
                        console.log($(this).find(`#${business_id}_endDate`))
                    }
                    dataArray.push({
                        field_type,
                        access_field_name,
                        field_value,
                        field_value_end,
                        business_id
                    })
                })
                console.log(dataArray)
                if (dataArray.length === 0) {
                    searchTableData(null, sort)
                }else {
                    searchTableData(JSON.stringify(dataArray), sort)
                }
            })
        })
    }
}

样式选择工具

designer页面

样式选择工具主要文件地址在ureport2-js/src/tools/CssTool.js下,然后在ureport2-js/src/designer.js中的buildTools方法中进行”注册“。

preview页面

html-preview页面中会js会动态加载css,具体代码如下:

// 动态加载css文件
function loadStyles(url) {
    var link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = url;
    document.getElementsByTagName("head")[0].appendChild(link);
}

相关文章

网友评论

      本文标题:报表

      本文链接:https://www.haomeiwen.com/subject/szvbsltx.html