package org.jeecg.modules.commonQueryConfig.controller;

import java.math.BigDecimal;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.JsonObject;
import io.swagger.util.Json;
import javafx.scene.input.InputMethodTextRun;
import lombok.extern.slf4j.XSlf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.bussMapQuery.controller.QueryRecord;
import org.jeecg.modules.bussMapQuery.controller.QueryResult;
import org.jeecg.modules.commonQueryConfig.entity.CommonQueryConfig;
import org.jeecg.modules.commonQueryConfig.service.ICommonQueryConfigService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.resManager.catalog.entity.Rescatalog;
import org.jeecg.modules.resManager.catalog.service.IRescatalogService;
import org.jeecg.modules.topicManage.entity.TopicsConfig;
import org.jeecg.modules.topicManage.service.ITopicsConfigService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 通用查询配置表
 * @Author: jeecg-boot
 * @Date: 2022-08-20
 * @Version: V1.0
 */
@Api(tags = "通用查询配置表")
@RestController
@RequestMapping("/commonQueryConfig/commonQueryConfig")
@Slf4j
public class CommonQueryConfigController extends JeecgController<CommonQueryConfig, ICommonQueryConfigService> {
    @Autowired
    private ICommonQueryConfigService commonQueryConfigService;
    @Autowired
    private IRescatalogService rescatalogService;
    @Autowired
    private CommonAPI commonApi;
    @Autowired
    private ITopicsConfigService topicsConfigService;

    //TODO
    @GetMapping(value = "/queryListByUser")
    public Result<?> queryListByUser(@RequestParam("username") String username, @RequestParam("topicId") String topicId) {
        List<JSONObject> queryList = new ArrayList<>();
        LambdaQueryWrapper<Rescatalog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Rescatalog::getQueryable, "true");
        List<Rescatalog> resCatalogs = rescatalogService.list(queryWrapper);

        if (resCatalogs.size() > 0) {
            String querytypes = "";
            if (!"null".equals(topicId) && !topicId.isEmpty()) {
                LambdaQueryWrapper<TopicsConfig> topicsConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
                topicsConfigLambdaQueryWrapper.eq(TopicsConfig::getTopicid, topicId);
                TopicsConfig topicsConfig = topicsConfigService.getOne(topicsConfigLambdaQueryWrapper);
                querytypes = topicsConfig.getQuerytypes();
            }

            for (int i = 0; i < resCatalogs.size(); i++) {
                Rescatalog rescatalog = resCatalogs.get(i);
                String res_id = rescatalog.getId();
                //判断是否有该业务资源目录权限
                int resCount = rescatalogService.queryCountByUsername(username, res_id);
                if (resCount == 0) {
                    continue;
                }
                if (!querytypes.isEmpty() && querytypes.indexOf(res_id) == -1) {
                    continue;
                }
                String tablename = rescatalog.getTablename();
                JSONObject jsonObject = new JSONObject();

                ArrayList<HashMap> list = new ArrayList<>();
                String queryfield = rescatalog.getQueryname();
                String chinesename = rescatalog.getChinesename();
                if (StringUtils.isNotBlank(queryfield) && StringUtils.isNotBlank(chinesename)
                        && queryfield.contains(",") && chinesename.contains(",")) {
                    List<String> queryfieldList = Arrays.asList(queryfield.split(","));
                    List<String> chinesenameList = Arrays.asList(chinesename.split(","));
                    for (int j = 0; j < queryfieldList.size(); j++) {
                        HashMap<String, String> querylisyMap = new HashMap<>();
                        querylisyMap.put("queryname", queryfieldList.get(j));
                        querylisyMap.put("chinesename", chinesenameList.get(j));
                        list.add(querylisyMap);
                    }
                } else if (StringUtils.isNotBlank(queryfield) && StringUtils.isNotBlank(chinesename)
                        && !queryfield.contains(",") && !chinesename.contains(",")) {
                    HashMap<String, String> querylisyMap = new HashMap<>();
                    querylisyMap.put("queryname", queryfield);
                    querylisyMap.put("chinesename", chinesename);
                    list.add(querylisyMap);
                }

                jsonObject.put("id", res_id);
                jsonObject.put("tablename", tablename);
                jsonObject.put("inputTip", rescatalog.getLyrhint());
                jsonObject.put("returntree", rescatalog.getReturntree());
                jsonObject.put("queryList", list);
                LambdaQueryWrapper<CommonQueryConfig> queryConfigQueryWrapper = new LambdaQueryWrapper<>();
                queryConfigQueryWrapper.eq(CommonQueryConfig::getTablename, rescatalog.getTablename());
                long count = commonQueryConfigService.count(queryConfigQueryWrapper);
                if (count < 1) {
                    continue;
                }
                CommonQueryConfig commonQueryConfig = commonQueryConfigService.getOne(queryConfigQueryWrapper, false);
                jsonObject.put("tablealias", commonQueryConfig.getTablealias());
                queryList.add(jsonObject);
            }
        }
        return Result.OK(queryList);
    }

    /**
     * 分页列表查询
     *
     * @param commonQueryConfig
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "通用查询配置表-分页列表查询")
    @ApiOperation(value = "通用查询配置表-分页列表查询", notes = "通用查询配置表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<CommonQueryConfig>> queryPageList(CommonQueryConfig commonQueryConfig,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        QueryWrapper<CommonQueryConfig> queryWrapper = QueryGenerator.initQueryWrapper(commonQueryConfig, req.getParameterMap());
        Page<CommonQueryConfig> page = new Page<CommonQueryConfig>(pageNo, pageSize);
        IPage<CommonQueryConfig> pageList = commonQueryConfigService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param commonQueryConfig
     * @return
     */
    @AutoLog(value = "通用查询配置表-添加")
    @ApiOperation(value = "通用查询配置表-添加", notes = "通用查询配置表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody CommonQueryConfig commonQueryConfig) {
        commonQueryConfigService.save(commonQueryConfig);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param commonQueryConfig
     * @return
     */
    @AutoLog(value = "通用查询配置表-编辑")
    @ApiOperation(value = "通用查询配置表-编辑", notes = "通用查询配置表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody CommonQueryConfig commonQueryConfig) {
        commonQueryConfigService.updateById(commonQueryConfig);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通用查询配置表-通过id删除")
    @ApiOperation(value = "通用查询配置表-通过id删除", notes = "通用查询配置表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        commonQueryConfigService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "通用查询配置表-批量删除")
    @ApiOperation(value = "通用查询配置表-批量删除", notes = "通用查询配置表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.commonQueryConfigService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "通用查询配置表-通过id查询")
    @ApiOperation(value = "通用查询配置表-通过id查询", notes = "通用查询配置表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<CommonQueryConfig> queryById(@RequestParam(name = "id", required = true) String id) {
        CommonQueryConfig commonQueryConfig = commonQueryConfigService.getById(id);
        if (commonQueryConfig == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(commonQueryConfig);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param commonQueryConfig
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CommonQueryConfig commonQueryConfig) {
        return super.exportXls(request, commonQueryConfig, CommonQueryConfig.class, "通用查询配置表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CommonQueryConfig.class);
    }

    @GetMapping(value = "/identifyQuery")
    public Result<?> identifyQuery(@RequestParam(name = "layerName", required = true) String layerName,
                                   @RequestParam(name = "objectId") String objectId) {
        JSONObject result = new JSONObject();
        LambdaQueryWrapper<Rescatalog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Rescatalog::getName, layerName);
        Rescatalog resCatalog = rescatalogService.getOne(queryWrapper);
        String tableName = resCatalog.getTablename();

        LambdaQueryWrapper<CommonQueryConfig> configLambdaQueryWrapper = new LambdaQueryWrapper<>();
        configLambdaQueryWrapper.eq(CommonQueryConfig::getTablename, tableName).orderByAsc(CommonQueryConfig::getShoworder);
        List<CommonQueryConfig> commonQueryConfigs = commonQueryConfigService.list(configLambdaQueryWrapper);

        if (commonQueryConfigs.size() > 0) {
            CommonQueryConfig temp = commonQueryConfigs.get(0);
            String reltablename = temp.getReltablename();
            HashMap<String, Object> queryParams = new HashMap<>();
            queryParams.put("tablename", tableName);
            queryParams.put("objectid", objectId);

            List<Map<String, Object>> queryList = new ArrayList<>();
            if (layerName.equals(reltablename)) {
                queryList = commonQueryConfigService.identifyQuery(queryParams);
            } else {
                String fromfldname = temp.getFromfldname();
                String tofldname = temp.getTofldname();
                queryParams.put("reltablename", reltablename);
                queryParams.put("fromfldname", fromfldname);
                queryParams.put("tofldname", tofldname);
                queryList = commonQueryConfigService.identifyQuery2(queryParams);
            }
            if (queryList.size() > 0) {
                Map<String, Object> queryItem = queryList.get(0);
                for (int j = 0; j < commonQueryConfigs.size(); j++) {
                    CommonQueryConfig configItem = commonQueryConfigs.get(j);
                    String unit = configItem.getUnit();
                    String fieldType = configItem.getType();
                    String dictName = configItem.getDictname();
                    Integer pre = configItem.getPre();
                    String fldName = configItem.getFldname();
                    String fldAlias = configItem.getFldalias();
                    if (unit != null) {
                        fldAlias = fldAlias + "(" + unit + ")";
                    }
                    Object fldValue = queryItem.get(fldName);
                    if (fldValue == null) {
                        result.put(fldAlias, "");
                        continue;
                    }
                    if (fieldType != null && fieldType == "N") {
                        double value = Double.parseDouble(fldValue.toString());
                        if (pre != null && pre > 0) {
                            BigDecimal bg = new BigDecimal(value);
                            value = bg.setScale(pre, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }
                        result.put(fldAlias, value);
                    } else if (dictName != null) {
                        String val = fldValue.toString();
                        List<DictModel> dictItems = commonApi.queryEnableDictItemsByCode(dictName);
                        if (dictItems.size() > 0) {
                            for (int k = 0; k < dictItems.size(); k++) {
                                DictModel dictItem = dictItems.get(k);
                                if (dictItem.getValue().indexOf(fldValue.toString()) > -1) {
                                    val = dictItem.getText();
                                    break;
                                }
                            }
                        }
                        result.put(fldAlias, val);
                    } else {
                        result.put(fldAlias, fldValue.toString());
                    }
                }

            }
        }
        return Result.OK(result);
    }


    @AutoLog(value = "通用属性信息查询")
    @ApiOperation(value = "通用属性信息查询", notes = "通用属性信息查询")
    @GetMapping(value = "/commonQuery")
    public Result<?> commonQuery(@RequestParam(name = "queryType", required = true) String queryType,
                                 @RequestParam(name = "queryList", required = true) String queryList,
                                 @RequestParam(name = "queryInfo", required = true) String queryInfo,
                                 @RequestParam(name = "returntree") Boolean returntree,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws SQLException {
        queryList=queryList.toLowerCase();
        QueryResult queryResult = new QueryResult();
        if (returntree) {
            //树形
            queryResult = doCommonQuery2(queryType, queryInfo, pageNo, pageSize);
        } else {
            //普通
            queryResult = doCommonQuery(queryType, queryList, queryInfo, pageNo, pageSize);
        }
        return Result.OK(queryResult);
    }

    private QueryResult doCommonQuery2(String queryType, String queryInfo, Integer pageNo, Integer pageSize)
            throws SQLException {
        QueryResult queryResult = new QueryResult();
        List<QueryRecord> queryRecords = new ArrayList<>();
        Integer total = 0;
        LambdaQueryWrapper<CommonQueryConfig> configLambdaQueryWrapper = new LambdaQueryWrapper<>();
        configLambdaQueryWrapper.eq(CommonQueryConfig::getTablename, queryType).orderByAsc(CommonQueryConfig::getShoworder);
        List<CommonQueryConfig> commonQueryConfigs = commonQueryConfigService.list(configLambdaQueryWrapper);
        if (commonQueryConfigs.size() > 0) {
            CommonQueryConfig temp = commonQueryConfigs.get(0);
            String queryField = temp.getQfldname();
            String reltablename = temp.getReltablename();
            String otherfield = temp.getOtherfield();
            String returnArea = temp.getReturnarea();
            String fromfldname = temp.getFromfldname();
            String tofldname = temp.getTofldname();
            HashMap<String, Object> queryParams = new HashMap<>();
            queryParams.put("tablename", queryType);
            queryParams.put("queryfield", queryField);
            queryParams.put("queryinfo", queryInfo);
            queryParams.put("pageno", pageNo);
            queryParams.put("pagesize", pageSize);
            queryParams.put("reltablename", reltablename);
            queryParams.put("fromfldname", fromfldname);
            queryParams.put("tofldname", tofldname);
            queryParams.put("otherfield", otherfield);

            List<Map<String, Object>> queryList = new ArrayList<>();        //存储查询到的所有一级数据列表
            List<Map<String, Object>> queryList_curPage = new ArrayList<>();       //存储查询到的当前页数据列表，然后在组装返回数据
            queryList = commonQueryConfigService.commonQuery4(queryParams);
            if (queryList.size() > 0) {
                total = queryList.size();
                queryList_curPage = getListpaging(queryList, pageNo, pageSize);
                for (int i = 0; i < queryList_curPage.size(); i++) {
                    QueryRecord queryRecord = new QueryRecord();
                    Map<String, Object> queryItem = queryList_curPage.get(i);
                    queryRecord.setId(queryItem.get(fromfldname).toString());
                    queryRecord.setName(queryItem.get(queryField).toString());
                    queryRecord.setLayerName(queryType);
                    JSONObject attribute = new JSONObject();
                    List<Map<String, Object>> queryList2 = new ArrayList<>();        //存储查询到的二级数据列表
                    String fromfldvalue = queryItem.get(fromfldname).toString();
                    queryParams.put("fromfldvalue", fromfldvalue);
                    queryList2 = commonQueryConfigService.commonQuery5(queryParams);
                    if (queryList2.size() > 0) {
                        Map<String, Object> attrItem = queryList2.get(0);
                        //根据配置表组装查询结果
                        for (int j = 0; j < commonQueryConfigs.size(); j++) {
                            CommonQueryConfig configItem = commonQueryConfigs.get(j);
                            String unit = configItem.getUnit();
                            String fieldType = configItem.getType();
                            String dictName = configItem.getDictname();
                            Integer pre = configItem.getPre();
                            String fldName = configItem.getFldname();
                            String fldAlias = configItem.getFldalias();
                            if (unit != null) {
                                fldAlias = fldAlias + "(" + unit + ")";
                            }
                            Object fldValue = attrItem.get(fldName);
                            if (fldValue == null) {
                                attribute.put(fldAlias, "");
                                continue;
                            }
                            if (fieldType != null && fieldType == "N") {
                                double value = Double.parseDouble(fldValue.toString());
                                if (pre != null && pre > 0) {
                                    BigDecimal bg = new BigDecimal(value);
                                    value = bg.setScale(pre, BigDecimal.ROUND_HALF_UP).doubleValue();
                                }
                                attribute.put(fldAlias, value);
                            } else if (dictName != null) {
                                String val = fldValue.toString();
                                List<DictModel> dictItems = commonApi.queryEnableDictItemsByCode(dictName);
                                if (dictItems.size() > 0) {
                                    for (int k = 0; k < dictItems.size(); k++) {
                                        DictModel dictItem = dictItems.get(k);
                                        if (dictItem.getValue().indexOf(fldValue.toString()) > -1) {
                                            val = dictItem.getText();
                                            break;
                                        }
                                    }
                                }
                                attribute.put(fldAlias, val);
                            } else {
                                attribute.put(fldAlias, fldValue.toString());
                            }
                        }
                        queryRecord.setAttributes(attribute);
                        JSONObject[] subInfos = new JSONObject[queryList2.size()];
                        for (int m = 0; m < queryList2.size(); m++) {
                            Map<String, Object> subItem = queryList2.get(m);
                            JSONObject subInfo = new JSONObject();
                            subInfo.put("OBJECTID", subItem.get("objectid").toString());
                            subInfo.put("mainInfo", subItem.get(otherfield).toString());
                            if (subItem.get("wkt") instanceof Clob) {
                                Clob clob = (Clob) subItem.get("wkt");
                                String wkt = clob.getSubString((long) 1, (int) clob.length());
                                subInfo.put("geoinfo", wkt);
                            } else {
                                subInfo.put("geoinfo", subItem.get("wkt").toString());
                            }
//                            if ("true".equals(returnArea)) {
//                                double shapeArea = Double.parseDouble(subItem.get("SHAPEAREA").toString());
//                                subInfo.put("shapeArea", String.format("%.2f", shapeArea) + "㎡");
//                            }
                            subInfos[m] = subInfo;
                        }
                        queryRecord.setSubInfos(subInfos);
                        queryRecords.add(queryRecord);
                    }
                }
            }
        }

       /* Map<String, List<QueryRecord>> collect = queryRecords.stream().collect(Collectors.groupingBy(QueryRecord::getName));
        System.out.println("6666666666666"+collect);*/


        queryResult.setRecords(queryRecords);
        /*   queryResult.setIds(collect);*/
        queryResult.setCurrent(pageNo);
        queryResult.setSize(pageSize);
        queryResult.setTotal(total);
        return queryResult;
    }

    private QueryResult doCommonQuery(String queryType, String query, String queryInfo, Integer pageNo, Integer pageSize) throws SQLException {
        QueryResult queryResult = new QueryResult();
        List<QueryRecord> queryRecords = new ArrayList<>();
        Integer total = 0;
        LambdaQueryWrapper<CommonQueryConfig> configLambdaQueryWrapper = new LambdaQueryWrapper<>();
        configLambdaQueryWrapper.eq(CommonQueryConfig::getTablename, queryType).orderByAsc(CommonQueryConfig::getShoworder);
        List<CommonQueryConfig> commonQueryConfigs = commonQueryConfigService.list(configLambdaQueryWrapper);
        if (commonQueryConfigs.size() > 0) {
            CommonQueryConfig temp = commonQueryConfigs.get(0);
            String queryField = temp.getQfldname();
            String reltablename = temp.getReltablename();
            String otherfield = temp.getOtherfield();
            String returnArea = temp.getReturnarea();
            HashMap<String, Object> queryParams = new HashMap<>();
            queryParams.put("tablename", queryType);
            queryParams.put("queryfield", query);
            queryParams.put("queryinfo", queryInfo);
            queryParams.put("pageno", pageNo);
            queryParams.put("pagesize", pageSize);

            List<Map<String, Object>> queryList = new ArrayList<>();        //存储查询到的所有数据列表
            List<Map<String, Object>> queryList_curPage = new ArrayList<>();       //存储查询到的当前页数据列表，然后在组装返回数据
            System.out.println(queryType + " | " + reltablename);
            if (queryType.equals(reltablename)) {
                queryList = commonQueryConfigService.commonQuery(queryParams);
            } else {
                String fromfldname = temp.getFromfldname();
                String tofldname = temp.getTofldname();
                queryParams.put("reltablename", reltablename);
                queryParams.put("fromfldname", fromfldname);
                queryParams.put("tofldname", tofldname);
                if (otherfield != null) {
                    queryParams.put("otherfield", otherfield);
                    queryList = commonQueryConfigService.commonQuery3(queryParams);
                } else {
                    //todo
                    queryList = commonQueryConfigService.commonQuery2(queryParams);
                    log.info(queryList.toString());
                    total = commonQueryConfigService.count(queryParams);
                }
            }
            //循环queryList看是否查询到数据
            if (queryList.size() > 0) {

                for (int i = 0; i < queryList.size(); i++) {
                    QueryRecord queryRecord = new QueryRecord();
                    Map<String, Object> queryItem = queryList.get(i);
                    queryRecord.setId(queryItem.get("objectid").toString());
                    if (queryItem.get(query) == null) {
                        continue;
                    }
                    queryRecord.setName(queryItem.get(query).toString());
                    if (queryItem.get("wkt") instanceof Clob) {
                        Clob clob = (Clob) queryItem.get("wkt");
                        String wkt = clob.getSubString((long) 1, (int) clob.length());
                        queryRecord.setGeoinfo(wkt);
                    } else {
                        queryRecord.setGeoinfo(queryItem.get("wkt").toString());
                    }

                    String otherInfo = "";
                    if (queryItem.get("dk") != null) {
                        queryRecord.setOtherInfo(queryItem.get("dk").toString());
                    }
                    queryRecord.setLayerName(queryType);
                    JSONObject attribute = new JSONObject();

                    //根据配置表组装查询结果
                    for (int j = 0; j < commonQueryConfigs.size(); j++) {
                        CommonQueryConfig configItem = commonQueryConfigs.get(j);
                        String unit = configItem.getUnit();
                        String fieldType = configItem.getType();
                        String dictName = configItem.getDictname();
                        Integer pre = configItem.getPre();
                        String fldName = configItem.getFldname();
                        String fldAlias = configItem.getFldalias();
                        if (unit != null) {
                            fldAlias = fldAlias + "(" + unit + ")";
                        }
                        Object fldValue = queryItem.get(fldName);
                        if (fldValue == null) {
                            attribute.put(fldAlias, "");
                            continue;
                        }
                        if (fieldType != null && fieldType == "N") {
                            double value = Double.parseDouble(fldValue.toString());
                            if (pre != null && pre > 0) {
                                BigDecimal bg = new BigDecimal(value);
                                value = bg.setScale(pre, BigDecimal.ROUND_HALF_UP).doubleValue();
                            }
                            attribute.put(fldAlias, value);
                        } else if (dictName != null) {
                            String val = fldValue.toString();
                            List<DictModel> dictItems = commonApi.queryEnableDictItemsByCode(dictName);
                            if (dictItems.size() > 0) {
                                for (int k = 0; k < dictItems.size(); k++) {
                                    DictModel dictItem = dictItems.get(k);
                                    if (dictItem.getValue().indexOf(fldValue.toString()) > -1) {
                                        val = dictItem.getText();
                                        break;
                                    }
                                }
                            }
                            attribute.put(fldAlias, val);
                        } else {
                            attribute.put(fldAlias, fldValue.toString());
                        }
                    }
                    queryRecord.setAttributes(attribute);
                    queryRecords.add(queryRecord);
                }
            }
        }

        queryResult.setRecords(queryRecords);
        queryResult.setCurrent(pageNo);
        queryResult.setSize(pageSize);
        queryResult.setTotal(total);
        return queryResult;
    }


    private static List getListpaging(List list, int pageNo, int pageSize) {
        if (list == null || list.size() <= 0) {
            return new ArrayList<>(0);
        }
        //开始下标
        int startIndex = (pageNo - 1) * pageSize;
        //结束下标 subList()方法不包含结束下标的元素
        int endIndex = pageNo * pageSize;
        //list总条数
        int total = list.size();
        //总页数
        int pageCount = 0;
        //通过取余决定是否给总页数加1
        int num = total % pageSize;
        if (num == 0) {
            pageCount = total / pageSize;
        } else {
            pageCount = total / pageSize + 1;
        }
        //如果当前页是最后一页的话 要包含集合的最后一条数据，因为sublist方法本身结束的下标是不包含当前元素的
        if (pageNo == pageCount) {
            endIndex = total;
        }
        return list.subList(startIndex, endIndex);
    }

    /**
     * 通过文件类型查询地块信息
     *
     * @param wjbh
     * @return
     */
    //@AutoLog(value = "通用查询配置表-通过id查询")
    @ApiOperation(value = "通过文件类型查询地块信息-通过文件类型查询", notes = "通过文件类型查询地块信息-通过文件类型查询")
    @GetMapping(value = "/queryByWjbh")
    public Result<CommonQueryConfig> queryByWjbh(@RequestParam(name = "wjbh", required = true) String wjbh) {
        CommonQueryConfig commonQueryConfig = commonQueryConfigService.getById(wjbh);
        if (commonQueryConfig == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(commonQueryConfig);
    }


}
