package org.jeecg.modules.geoAnalysis.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esri.core.geometry.Geometry;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.MapGeometry;
import com.esri.core.geometry.WktExportFlags;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import kotlin.reflect.jvm.internal.impl.util.collectionUtils.ScopeUtilsKt;
import lombok.extern.slf4j.Slf4j;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;


import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;


import org.geotools.feature.FeatureCollections;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.commonQueryConfig.entity.CommonQueryConfig;
import org.jeecg.modules.geoAnalysis.dto.DrawMapByPointDto;
import org.jeecg.modules.geoAnalysis.dto.DrawMapDto;
import org.jeecg.modules.geoAnalysis.entity.DetailsResult;
import org.jeecg.modules.geoAnalysis.entity.Fldalias;
import org.jeecg.modules.geoAnalysis.entity.GeoAnalysis;
import org.jeecg.modules.geoAnalysis.entity.ZYFXPZB;
import org.jeecg.modules.geoAnalysis.service.IGeoAnlysisService;
import org.jeecg.modules.geoAnalysis.service.impl.GeoAnalysisServiceImpl;
import org.jeecg.modules.geoAnalysis.vo.GeometryVo;
import org.jeecg.modules.gis.lochistory.entity.LocHistory;
import org.jeecg.modules.gis.lochistory.service.ILocHistoryService;
import org.jeecg.modules.util.ZipUtils;
import org.locationtech.jts.io.WKTReader;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.*;

@Api(tags = "分析")
@RestController
@RequestMapping("/geoAnalysis/Analysis")
@Slf4j
public class GeoAnalysisController extends JeecgController<GeoAnalysis, IGeoAnlysisService> {
    @Autowired
    GeoAnalysisServiceImpl geoAnalysisService;

    /**
     * 通过获取坐标串进行分析
     *
     * @return
     */
    @AutoLog(value = "")
    @ApiOperation(value = " 通过获取坐标串进行分析", notes = " 通过获取坐标串进行分析")
    @GetMapping(value = "/DrawMap")
    public Result<?> DrawMapByzb( DrawMapDto drawMapDto) throws JsonProcessingException {
        HashMap<String,Object> wk=new HashMap<>();
        List<Object> rings=new ArrayList<>();
        rings.add(drawMapDto.getGeoJson());
        wk.put("wkid",4490);
        String jsonString = "{\"rings\":[" + drawMapDto.getGeoJson() + "],\"spatialReference\":{\"wkid\":4490}}";
        //System.out.println(jsonString);
        Geometry geometry = GeometryEngine.jsonToGeometry(jsonString).getGeometry();
        String drawWkt = GeometryEngine.geometryToWkt(geometry, WktExportFlags.wktExportPolygon);
        log.info(drawWkt);
        String[] split = drawMapDto.getAtableename().split(",");
        ArrayList<ZYFXPZB> yj_kszlq = new ArrayList<>();
        //省属地块,省直地块参数(atableename: sz_dkxx,ss_dkxx)
        if (drawMapDto.getAtableename().contains(",")) {
            for (String s : split) {
                //占压分析配置表
                ZYFXPZB zyfxpzb = geoAnalysisService.SelectByTbs(drawMapDto.getTable(), s);
                yj_kszlq.add(zyfxpzb);
            }
        } else {
            //占压分析配置表
            ZYFXPZB zyfxpzb = geoAnalysisService.SelectByTbs(drawMapDto.getTable(), drawMapDto.getAtableename());
            yj_kszlq.add(zyfxpzb);
        }
        ArrayList<GeoAnalysis> geoAnalyses = geoAnalysisService.DrawMap(yj_kszlq, drawWkt);
        System.out.println(geoAnalyses);
        return Result.OK("成功", geoAnalyses);
    }

    /**
     * 通过获取表名和坐标分析
     *
     * @return
     */
    @AutoLog(value = "")
    @ApiOperation(value = " 通过获取表名和坐标分析", notes = " 通过获取表名和坐标分析")
    @GetMapping(value = "/DrawMapByid")
    public Result<?> DrawMapByid(DrawMapByPointDto drawMapDto) {
        ArrayList<ZYFXPZB> yj_kszlq = new ArrayList<>();
        if (drawMapDto.getAtableename().contains(",")) {
            String[] split = drawMapDto.getAtableename().split(",");
            for (String s : split) {
                ZYFXPZB zyfxpzb = geoAnalysisService.SelectByTbs(drawMapDto.getTable(), s);
                yj_kszlq.add(zyfxpzb);
            }
        } else {
            ZYFXPZB zyfxpzb = geoAnalysisService.SelectByTbs(drawMapDto.getTable(), drawMapDto.getAtableename());
            yj_kszlq.add(zyfxpzb);
        }
        ArrayList<GeoAnalysis> geoAnalyses = geoAnalysisService.DrawMapByShape(yj_kszlq, drawMapDto.getGeoJson(), drawMapDto.getTable());
        System.out.println(geoAnalyses);
        return Result.OK("成功", geoAnalyses);
    }

    /**
     * 通过获取表名查询分析图层
     *
     * @return
     */
    @AutoLog(value = "")
    @ApiOperation(value = " 通过获取表名查询分析图层", notes = " 通过获取表名查询分析图层")
    @GetMapping(value = "/SelectByTb")
    public Result<?> SelectByTb(@RequestParam(name = "table", required = false) String table) {
        List<ZYFXPZB> zyfxpzbs = geoAnalysisService.SelectByTb(table);
        return Result.OK("成功", zyfxpzbs);
    }

    /**
     * @return
     * @Author lihongrui
     * @Description 导出shape文件
     * @Date 10:36 2023/8/3
     * @Param
     */
    @AutoLog(value = "")
    @ApiOperation(value = " 导出shape文件", notes = " 导出shape文件")
    @GetMapping(value = "/exportShapes")
    public Result<?> exportShapes(HttpServletResponse response, @RequestParam(name = "id", required = false) String id) {
        Boolean aBoolean = geoAnalysisService.exportShps(response, id);
        return Result.OK("成功", aBoolean);
    }

    /**
     * 分析查看详情信息
     *
     * @return
     */
    @AutoLog(value = "")
    @ApiOperation(value = " 分析查看详情信息", notes = " 分析查看详情信息")
    @GetMapping(value = "/SelectDetails")
    public Result<?> SelectDetails(@RequestParam(name = "table", required = false) String table, @RequestParam(name = "objectid", required = false) String objectid) {
       /* objectid="1175,1832";
        table="征地图斑";*/
        LinkedHashMap<String, String> maps = new LinkedHashMap<>();
        String[] split = null;
        String objectids = null;
        HashMap<String, Object> map = new HashMap<>();
        String tables = null;
        if (objectid.contains(",")) {
            split = objectid.split(",");
        } else {
            split = new String[]{objectid};
        }
        ArrayList<String> arr = new ArrayList<>();
        ArrayList<DetailsResult> arrayList = new ArrayList<>();
        ArrayList<CommonQueryConfig> list = geoAnalysisService.SelectByTable(table);
        for (CommonQueryConfig commonQueryConfig : list) {
            String fldalias = commonQueryConfig.getFldalias();
            String unit = commonQueryConfig.getUnit();
            String fldname = commonQueryConfig.getFldname();
            Integer pre = commonQueryConfig.getPre();
            StringBuilder filed = new StringBuilder();
            if (commonQueryConfig.getUnit() != null) {
                filed.append(fldalias);
                filed.append("（" + unit + "）");
            } else {
                filed.append(fldalias);
            }
            maps.put(commonQueryConfig.getFldname(), filed.toString());
            if (commonQueryConfig.getPre() != null) {
                commonQueryConfig.setFldname("round(" + fldname + "," + pre + ") as " + fldname);
            }
            arr.add(commonQueryConfig.getFldname());
            tables = commonQueryConfig.getAnalysistablename();
        }
        for (String s : split) {
            DetailsResult result1 = new DetailsResult();
            result1.setFldalia(maps);
            map.put("table", tables);
            map.put("shape", arr);
            map.put("id", s);
            HashMap<String, Object> hashMaps = geoAnalysisService.SelectDetails(map);
            for (String s1 : hashMaps.keySet()) {
                if (hashMaps.get(s1) instanceof Clob) {
                    Clob clob = (Clob) hashMaps.get(s1);
                    try {
                        hashMaps.put(s1, clob.getSubString((long) 1, (int) clob.length()));
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
            result1.setResult(hashMaps);
            arrayList.add(result1);
        }
        System.out.println(arrayList);
        return Result.OK("成功", arrayList);
    }


}


