using System.Dynamic;
using System.Net.Http.Headers;
using System.Text;
using Flurl.Http;
using Infrastructure;
using Infrastructure.Helpers;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using OpenAuth.App.ServiceApp.DroneCloudQuery;
using OpenAuth.App.ServiceApp.DroneCloudQueryManage.Request;
using OpenAuth.App.ServiceApp.Response;
using OpenAuth.App.ServiceApp.ShpGeo.Utils;
using OpenAuth.Repository.Domain;
using Quartz;
using SqlSugar;

namespace OpenAuth.App.ServiceApp.Jobs;

public class CloudQueryTask : IJob
{
    private readonly OpenJobApp _openJobApp;

    private readonly string domain = GeoUtil.JobwebUrl;
    // private readonly string domain = "http://192.168.10.103:10041/";

    //private readonly string domain = "http://120.222.154.7:6050/"; 
    private string token = "";
    private readonly DroneCloudQueryApp _droneCloudQueryApp;
    private readonly ISqlSugarClient sqlclient;

    public CloudQueryTask(OpenJobApp openJobApp, ISqlSugarClient sqlSugarClient)
    {
        _openJobApp = openJobApp;
        this.sqlclient = sqlSugarClient;
    }

    public async Task Execute(IJobExecutionContext context)
    {
        var jobId = context.MergedJobDataMap.GetString(Define.JOBMAPKEY);
        //todo:获取到定时任务的id，可以可以加入自己的自动任务逻辑
        //  获取云查询任务  调用接口
        using (var client = new HttpClient())
        {
            // 设置GET请求的URL
            var url = domain + "api/DroneCloudQuery/LoadDroneTask";
            try
            {
                // 创建HttpRequestMessage对象
                var getTaskRequest = new HttpRequestMessage(HttpMethod.Get, url);
                if (token.Equals(""))
                {
                    // 堵塞查询
                    token = GetToken().Result;
                }


                // 添加Token到Header中
                getTaskRequest.Headers.Authorization =
                    new AuthenticationHeaderValue("X-Token", token);
                // 发送请求
                var getTaskResponse = client.SendAsync(getTaskRequest);
                // 阻塞当前线程直到任务完成
                var result = getTaskResponse.Result;
                if (result.IsSuccessStatusCode)
                {
                    var task = JsonConvert.DeserializeObject<Response<DroneCloudTaskResp>>(result.Content
                        .ReadAsStringAsync().Result);
                    // "code": 401
                    if (task.Code == 401)
                    {
                        // 堵塞查询
                        token = GetToken().Result;
                        // 添加Token到Header中
                        getTaskRequest.Headers.Authorization =
                            new AuthenticationHeaderValue("X-Token", token);
                        // 发送请求
                        getTaskResponse = client.SendAsync(getTaskRequest);

                        // 阻塞当前线程直到任务完成
                        result = getTaskResponse.Result;
                    }

                    task = JsonConvert.DeserializeObject<Response<DroneCloudTaskResp>>(result.Content
                        .ReadAsStringAsync().Result);
                    var geoserver = GeoUtil.GeoserverUrl;
                    var workspace = GeoUtil.Workspace;
                    // 处理图斑信息
                    foreach (var droneShpData in task.Result.droneShpDatas)
                    {
                        string sqlexist = $"select count(*) from drone_cloud_shp where gid=" + droneShpData.gid;

                        int countexist = sqlclient.Ado.GetInt(sqlexist);
                        if (countexist > 0)
                        {
                            string sqlupdate = $"update drone_cloud_shp set geom =" + "ST_GeomFromText('" +
                                               droneShpData.geom + "') where gid = " + droneShpData.gid;
                            sqlclient.Ado.ExecuteCommand(sqlupdate);
                        }
                        else
                        {
                            string sqlinsert =
                                $"insert into drone_cloud_shp(gid,id,geom,handle_status_id,handle_status_name,typename,original_case_no,case_no,is_intact,is_illegal) VALUES (" +
                                droneShpData.gid + ",'" + droneShpData.Id + "'," + "ST_GeomFromText('" +
                                droneShpData.geom + "')," + droneShpData.handle_status_id + "," + "'" +
                                droneShpData.handle_status_name + "','" +
                                droneShpData.typename + "','" + droneShpData.original_case_no + "','" +
                                droneShpData.case_no + "'," + droneShpData.is_intact + "," + droneShpData.is_illegal +
                                ")";
                            sqlclient.Ado.ExecuteCommand(sqlinsert);
                        }
                    }
                    // 处理任务信息
                    foreach (var droneCloudTask in task.Result.droneCloudTasks)
                    {
                        Dictionary<string, Object> dict = new Dictionary<string, Object>();

                        var queryId = droneCloudTask.QueryId;
                        var geomid = droneCloudTask.GeomId;
                        var caseNo = droneCloudTask.CaseNo;
                        var county_name = droneCloudTask.CountyName;
                        var geomids = geomid.Split(',');
                        string geomeids = "";
                        for (int i = 0; i < geomids.Length; i++)
                        {
                            if (i == geomids.Length - 1)
                            {
                                geomeids = geomeids + "'" + geomids[i] + "'";
                            }
                            else
                            {
                                geomeids = "'" + geomids[i] + "'," + geomeids;
                            }
                        }

                        //查询配置
                        string configsql = $"select * from drone_cloud_query_content where 1=1 and county_name='" +
                                           county_name + "'";

                        var configresult = sqlclient.Ado.SqlQuery<dynamic>(configsql);
                        if (configresult == null)
                        {
                            string configsql1 =
                                $"select * from drone_cloud_query_content where county_name in ('罗庄区','河东区','兰山区','莒南县')";
                            configresult = sqlclient.Ado.SqlQuery<dynamic>(configsql1);
                        }

                        string sqlgeom = $"SELECT count(*) from  drone_cloud_shp where gid  in (" + geomeids + ")";
                        var geomresult = sqlclient.Ado.GetInt(sqlgeom);
                        if (geomresult <= 0)
                        {
                            continue;
                        }

                        string sql =
                            $"SELECT\r\n  min(ST_XMin(geom)) AS min_x,\r\n  min(ST_YMin(geom)) AS min_y,\r\n " +
                            $" max(ST_XMax(geom)) AS max_x,\r\n  max(ST_YMax(geom)) AS max_y\r\nFROM\r\n  drone_cloud_shp where gid  in(" +
                            geomeids + ")";
                        var four = sqlclient.Ado.SqlQuerySingle<dynamic>(sql);

                        //double maxLat = double.Parse(four.max_x.ToString()) + 0.0015;
                        //double mixLat = double.Parse(four.min_x.ToString()) - 0.0015;
                        //double maxLng = double.Parse(four.max_y.ToString()) + 0.0015;
                        //double minLng = double.Parse(four.min_y.ToString()) - 0.0015;

                        double maxLat = double.Parse(four.max_x.ToString()) + 0.0003;
                        double mixLat = double.Parse(four.min_x.ToString()) - 0.0003;
                        double maxLng = double.Parse(four.max_y.ToString()) + 0.0003;
                        double minLng = double.Parse(four.min_y.ToString()) - 0.0003;
                        string fourpoint = "[" + mixLat + "," + maxLng + "]" + "," + "[" + maxLat + "," + maxLng + "]" +
                                           "," + "[" + maxLat + "," + minLng + "]" + "," + "[" + mixLat + "," + minLng +
                                           "]";
                        string bbox = mixLat + "," + minLng + "," + maxLat + "," + maxLng;
                        string url1 = geoserver + "/" + workspace +
                                      "/wms?service=WMS&version=1.1.0&request=GetMap&layers=";
                        List<Object> list = new List<Object>();
                        string uploadurl = domain + "api/Files/UploadSingle";
                        foreach (var item in configresult)
                        {
                            var mianjiziduan = item.area_field;
                            Dictionary<string, Object> obj = new Dictionary<string, Object>();
                            obj.Add("fourpoint", fourpoint);
                            obj.Add("name", item.name);
                            if (item.is_class == 0)
                            {
                                //计算面积
                                string mianjisql =
                                    $"select sum(c.have_intersection) from  (SELECT ST_Area(ST_Transform(st_setsrid(ST_Intersection(st_setsrid(a." +
                                    mianjiziduan +
                                    ", 4326),st_setsrid(b.geom, 4326)),4326),4527)) AS have_intersection from " +
                                    item.table_name + " a  ,(select geom from drone_cloud_shp where gid in (" +
                                    geomeids + ")" + ") b) c where c.have_intersection>0";
                                var mianjiResult = sqlclient.Ado.GetDouble(mianjisql);
                                obj.Add("sum", mianjiResult);
                                obj.Add("list", "");
                            }
                            else
                            {
                                //计算面积
                                /* string mianjisql1 = $"select sum(c.have_intersection) from  (SELECT ST_Area(ST_Intersection(st_setsrid(a." + mianjiziduan + ", 4326),st_setsrid(b.geom, 4326))) AS have_intersection from " + item.table_name + " a  ,(select geom from drone_cloud_shp where gid in (" + geomeids + ")" + ") b) c where c.have_intersection>0";
                                 Console.WriteLine(mianjisql1);
                                 var mianjiResult1 = sqlclient.Ado.GetDouble(mianjisql1);
                                 obj.Add("sum", mianjiResult1);*/
                                //计算面积
                                string mianjisql = $"select " + item.class_field +
                                                   " as type, sum(c.have_intersection) area from  (SELECT " +
                                                   item.class_field +
                                                   ", ST_Area(ST_Transform(st_setsrid(ST_Intersection(st_setsrid(a." +
                                                   mianjiziduan +
                                                   ", 4326),st_setsrid(b.geom, 4326) ),4326),4527)) AS have_intersection from " +
                                                   item.table_name +
                                                   " a ,(select geom from drone_cloud_shp where gid in (" + geomeids +
                                                   ")" + ") b) c where c.have_intersection>0 group by c." +
                                                   item.class_field;
                                Console.WriteLine(mianjisql);
                                var mianjiResult = sqlclient.Ado.SqlQuery<dynamic>(mianjisql);
                                obj.Add("list", mianjiResult);
                            }

                            string overlay = item.overlay;
                            string strinclude = "";
                            string ovserlay1 = "";
                            if (!string.IsNullOrEmpty(overlay))
                            {
                                string[] ovrStrs = overlay.Split(",");
                                int overCount = ovrStrs.Length;
                                for (int i = 0; i < ovrStrs.Length; i++)
                                {
                                    if ("天地图".Equals(ovrStrs[i]))
                                    {
                                        continue;
                                    }

                                    ovserlay1 = ovserlay1 + workspace + ":" + ovrStrs[i] + ",";
                                    strinclude = strinclude + "INCLUDE;";
                                }
                            }

                            string layers = ovserlay1 + workspace + ":" + item.table_name + "," + workspace +
                                            ":drone_cloud_shp";
                            string url2 = url1 + layers + "&CQL_FILTER =INCLUDE;" + strinclude + "case_no=" + caseNo +
                                          "&bbox=" + bbox +
                                          "&width=768&height=646&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE";
                            Console.WriteLine(url2);

                            var draftResult = url2.GetAsync().Result;
                            byte[] img = draftResult.GetBytesAsync().Result;
                            var content1 = new MultipartFormDataContent();
                            long localTimestamp =
                                ((DateTime.Now.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000);
                            var fileContent = new ByteArrayContent(img);
                            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                            {
                                Name = "file", // 这个名字要和Web API中的参数名一致
                                FileName = localTimestamp + ".png"
                            };
                            content1.Add(fileContent);
                            content1.Headers.Add("X-Token", token);
                            var response1 = await client.PostAsync(uploadurl, content1);
                            var imagecontent = JsonConvert.DeserializeObject<Response<SysUploadFile>>(response1.Content
                                .ReadAsStringAsync().Result);
                            SysUploadFile sysUploadFile = imagecontent.Result;
                            if (sysUploadFile == null)
                            {
                                obj.Add("url", "");
                            }
                            else
                            {
                                obj.Add("url", sysUploadFile.FilePath);
                            }

                            string layersxian = workspace + ":geoserverAdd," + workspace + ":drone_cloud_shp";
                            string url3 = url1 + layersxian + "&CQL_FILTER =INCLUDE;" + "case_no=" + caseNo + "&bbox=" +
                                          bbox +
                                          "&width=768&height=646&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE";
                            Console.WriteLine(url3);

                            var draftResultxian = url3.GetAsync().Result;
                            byte[] imgxian = draftResultxian.GetBytesAsync().Result;
                            var content1xian = new MultipartFormDataContent();
                            long localTimestampxian =
                                ((DateTime.Now.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000);
                            var fileContentxian = new ByteArrayContent(imgxian);
                            fileContentxian.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                            {
                                Name = "file", // 这个名字要和Web API中的参数名一致
                                FileName = localTimestampxian + ".png"
                            };
                            content1xian.Add(fileContentxian);
                            content1xian.Headers.Add("X-Token", token);
                            var responsexian = await client.PostAsync(uploadurl, content1xian);
                            var imagecontentxian = JsonConvert.DeserializeObject<Response<SysUploadFile>>(responsexian
                                .Content
                                .ReadAsStringAsync().Result);
                            SysUploadFile sysUploadFile1 = imagecontentxian.Result;
                            if (sysUploadFile1 == null)
                            {
                                obj.Add("urlxian", "");
                            }
                            else
                            {
                                obj.Add("urlxian", sysUploadFile1.FilePath);
                            }

                            /*    MemoryStream memStream = new MemoryStream(img);
                                Image imge = Image.FromStream(memStream);

                                imge.Save("D:/fwtool/" + "abc.png");*/

                            list.Add(obj);
                        }


                        //查询影像记录表
                        //string tifssql = $"select * from geo_tiff_manager where 1=1";

                        List<Object> listyx = new List<Object>();
                        string bianjiesql =
                            $"select c.have_intersection,c.date_dir,c.layer_name from  (SELECT ST_Intersects(st_setsrid(a.geometry, 4326),st_setsrid(b.geom, 4326) ) AS have_intersection,date_dir,layer_name from " +
                            "geo_tiff_manager" + " a ,(select geom from drone_cloud_shp where gid in (" + geomeids +
                            ")" + ") b) c where c.have_intersection=true";
                        Console.WriteLine(bianjiesql);
                        var tiffresult = sqlclient.Ado.SqlQuery<dynamic>(bianjiesql);
                        foreach (var item in tiffresult)
                        {
                            string layers = workspace + ":" + item.layer_name + "," + workspace + ":drone_cloud_shp";

                            Dictionary<string, Object> obj = new Dictionary<string, Object>();

                            //叠加影像

                            string tifurl = url1 + layers + "&CQL_FILTER =INCLUDE;" + "case_no=" + caseNo + "&bbox=" +
                                            bbox +
                                            "&width=768&height=646&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE";
                            var tifResult = tifurl.GetAsync().Result;
                            byte[] imgs = tifResult.GetBytesAsync().Result;
                            var content1 = new MultipartFormDataContent();
                            long localTimestamp =
                                ((DateTime.Now.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000);
                            var fileContent = new ByteArrayContent(imgs);
                            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                            {
                                Name = "file", // 这个名字要和Web API中的参数名一致
                                FileName = localTimestamp + ".png"
                            };
                            content1.Add(fileContent);
                            content1.Headers.Add("X-Token", token);
                            var response1 = await client.PostAsync(uploadurl, content1);
                            var imagecontent = JsonConvert.DeserializeObject<Response<SysUploadFile>>(response1.Content
                                .ReadAsStringAsync().Result);
                            SysUploadFile sysUploadFile = imagecontent.Result;
                            if (sysUploadFile == null)
                            {
                                obj.Add("url", "");
                            }
                            else
                            {
                                obj.Add("url", sysUploadFile.FilePath);
                            }

                            obj.Add("shijian", item.date_dir);
                            listyx.Add(obj);
                        }


                        dict.Add("result", list);
                        dict.Add("yingxiang", listyx);

                        // 调用接口存入query
                        var queryResult = dict;
                        var updateCloudQuery = domain + "api/DroneCloudQuery/UpdateCloudQuery";
                        var req = new CloudQueryReq
                        {
                            // 填充内容 
                            Id = queryId,
                            ReceiveContent = JsonConvert.SerializeObject(queryResult),
                            ReceiveTime = DateTime.Now
                        };
                        var content = new StringContent(JsonConvert.SerializeObject(req), Encoding.UTF8,
                            "application/json");
                        // 添加自定义的HTTP头
                        content.Headers.Add("X-Token", token);
                        await client.PostAsync(updateCloudQuery, content);
                    }

                    Console.WriteLine(result);
                }
            }
            catch (Exception e)
            {
                // 处理请求异常
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }

        _openJobApp.RecordRun(jobId);
        await Task.CompletedTask;
    }


    public async Task Execute1()
    {
        //todo:获取到定时任务的id，可以可以加入自己的自动任务逻辑
        //  获取云查询任务  调用接口
        using (var client = new HttpClient())
        {
            // 设置GET请求的URL
            var url = domain + "api/DroneCloudQuery/LoadDroneTask";
            try
            {
                // 创建HttpRequestMessage对象
                var getTaskRequest = new HttpRequestMessage(HttpMethod.Get, url);
                if (token.Equals(""))
                {
                    // 堵塞查询
                    token = GetToken().Result;
                }


                // 添加Token到Header中
                getTaskRequest.Headers.Authorization =
                    new AuthenticationHeaderValue("X-Token", token);
                // 发送请求
                var getTaskResponse = client.SendAsync(getTaskRequest);
                // 阻塞当前线程直到任务完成
                var result = getTaskResponse.Result;
                if (result.IsSuccessStatusCode)
                {
                    var task = JsonConvert.DeserializeObject<Response<DroneCloudTaskResp>>(result.Content
                        .ReadAsStringAsync().Result);
                    // "code": 401
                    if (task.Code == 401)
                    {
                        // 堵塞查询
                        token = GetToken().Result;
                        // 添加Token到Header中
                        getTaskRequest.Headers.Authorization =
                            new AuthenticationHeaderValue("X-Token", token);
                        // 发送请求
                        getTaskResponse = client.SendAsync(getTaskRequest);

                        // 阻塞当前线程直到任务完成
                        result = getTaskResponse.Result;
                    }

                    task = JsonConvert.DeserializeObject<Response<DroneCloudTaskResp>>(result.Content
                        .ReadAsStringAsync().Result);
                    var geoserver = GeoUtil.GeoserverUrl;
                    var workspace = GeoUtil.Workspace;
                    // 处理图斑信息
                    foreach (var droneShpData in task.Result.droneShpDatas)
                    {
                        string sqlexist = $"select count(*) from drone_cloud_shp where gid=" + droneShpData.gid;

                        int countexist = sqlclient.Ado.GetInt(sqlexist);
                        if (countexist > 0)
                        {
                            string sqlupdate = $"update drone_cloud_shp set geom =" + "ST_GeomFromText('" +
                                               droneShpData.geom + "') where gid = " + droneShpData.gid;
                            sqlclient.Ado.ExecuteCommand(sqlupdate);
                        }
                        else
                        {
                            string sqlinsert =
                                $"insert into drone_cloud_shp(gid,id,geom,handle_status_id,handle_status_name,typename,original_case_no,case_no,is_intact,is_illegal) VALUES (" +
                                droneShpData.gid + ",'" + droneShpData.Id + "'," + "ST_GeomFromText('" +
                                droneShpData.geom + "')," + droneShpData.handle_status_id + "," + "'" +
                                droneShpData.handle_status_name + "','" +
                                droneShpData.typename + "','" + droneShpData.original_case_no + "','" +
                                droneShpData.case_no + "'," + droneShpData.is_intact + "," + droneShpData.is_illegal +
                                ")";
                            sqlclient.Ado.ExecuteCommand(sqlinsert);
                        }
                    }
                    // 处理任务信息
                    foreach (var droneCloudTask in task.Result.droneCloudTasks)
                    {
                        Dictionary<string, Object> dict = new Dictionary<string, Object>();

                        var queryId = droneCloudTask.QueryId;
                        var geomid = droneCloudTask.GeomId;
                        var caseNo = droneCloudTask.CaseNo;
                        var county_name = droneCloudTask.CountyName;
                        var geomids = geomid.Split(',');
                        string geomeids = "";
                        for (int i = 0; i < geomids.Length; i++)
                        {
                            if (i == geomids.Length - 1)
                            {
                                geomeids = geomeids + "'" + geomids[i] + "'";
                            }
                            else
                            {
                                geomeids = "'" + geomids[i] + "'," + geomeids;
                            }
                        }

                        //查询配置
                        string configsql = $"select * from drone_cloud_query_content where 1=1 and county_name='" +
                                           county_name + "'";

                        var configresult = sqlclient.Ado.SqlQuery<dynamic>(configsql);
                        if (configresult == null)
                        {
                            string configsql1 =
                                $"select * from drone_cloud_query_content where county_name in ('罗庄区','河东区','兰山区','莒南县')";
                            configresult = sqlclient.Ado.SqlQuery<dynamic>(configsql1);
                        }

                        string sqlgeom = $"SELECT count(*) from  drone_cloud_shp where gid  in (" + geomeids + ")";
                        var geomresult = sqlclient.Ado.GetInt(sqlgeom);
                        if (geomresult <= 0)
                        {
                            continue;
                        }

                        string sql =
                            $"SELECT\r\n  min(ST_XMin(geom)) AS min_x,\r\n  min(ST_YMin(geom)) AS min_y,\r\n " +
                            $" max(ST_XMax(geom)) AS max_x,\r\n  max(ST_YMax(geom)) AS max_y\r\nFROM\r\n  drone_cloud_shp where gid  in(" +
                            geomeids + ")";
                        var four = sqlclient.Ado.SqlQuerySingle<dynamic>(sql);

                        double maxLat = double.Parse(four.max_x.ToString()) + 0.0015;
                        double mixLat = double.Parse(four.min_x.ToString()) - 0.0015;
                        double maxLng = double.Parse(four.max_y.ToString()) + 0.0015;
                        double minLng = double.Parse(four.min_y.ToString()) - 0.0015;
                        string fourpoint = "[" + mixLat + "," + maxLng + "]" + "," + "[" + maxLat + "," + maxLng + "]" +
                                           "," + "[" + maxLat + "," + minLng + "]" + "," + "[" + mixLat + "," + minLng +
                                           "]";
                        string bbox = mixLat + "," + minLng + "," + maxLat + "," + maxLng;
                        string url1 = geoserver + "/" + workspace +
                                      "/wms?service=WMS&version=1.1.0&request=GetMap&layers=";
                        List<Object> list = new List<Object>();
                        string uploadurl = domain + "api/Files/UploadSingle";
                        foreach (var item in configresult)
                        {
                            var mianjiziduan = item.area_field;
                            Dictionary<string, Object> obj = new Dictionary<string, Object>();
                            obj.Add("fourpoint", fourpoint);
                            obj.Add("name", item.name);
                            if (item.is_class == 0)
                            {
                                //计算面积
                                string mianjisql =
                                    $"select sum(c.have_intersection) from  (SELECT ST_Area(ST_Transform(st_setsrid(ST_Intersection(st_setsrid(a." +
                                    mianjiziduan +
                                    ", 4326),st_setsrid(b.geom, 4326)),4326),4527)) AS have_intersection from " +
                                    item.table_name + " a  ,(select geom from drone_cloud_shp where gid in (" +
                                    geomeids + ")" + ") b) c where c.have_intersection>0";
                                var mianjiResult = sqlclient.Ado.GetDouble(mianjisql);
                                obj.Add("sum", mianjiResult);
                                obj.Add("list", "");
                            }
                            else
                            {
                                //计算面积
                                /* string mianjisql1 = $"select sum(c.have_intersection) from  (SELECT ST_Area(ST_Intersection(st_setsrid(a." + mianjiziduan + ", 4326),st_setsrid(b.geom, 4326))) AS have_intersection from " + item.table_name + " a  ,(select geom from drone_cloud_shp where gid in (" + geomeids + ")" + ") b) c where c.have_intersection>0";
                                 Console.WriteLine(mianjisql1);
                                 var mianjiResult1 = sqlclient.Ado.GetDouble(mianjisql1);
                                 obj.Add("sum", mianjiResult1);*/
                                //计算面积
                                string mianjisql = $"select " + item.class_field +
                                                   " as type, sum(c.have_intersection) area from  (SELECT " +
                                                   item.class_field +
                                                   ", ST_Area(ST_Transform(st_setsrid(ST_Intersection(st_setsrid(a." +
                                                   mianjiziduan +
                                                   ", 4326),st_setsrid(b.geom, 4326) ),4326),4527)) AS have_intersection from " +
                                                   item.table_name +
                                                   " a ,(select geom from drone_cloud_shp where gid in (" + geomeids +
                                                   ")" + ") b) c where c.have_intersection>0 group by c." +
                                                   item.class_field;
                                Console.WriteLine(mianjisql);
                                var mianjiResult = sqlclient.Ado.SqlQuery<dynamic>(mianjisql);
                                obj.Add("list", mianjiResult);
                            }

                            string overlay = item.overlay;
                            string strinclude = "";
                            string ovserlay1 = "";
                            if (!string.IsNullOrEmpty(overlay))
                            {
                                string[] ovrStrs = overlay.Split(",");
                                int overCount = ovrStrs.Length;
                                for (int i = 0; i < ovrStrs.Length; i++)
                                {
                                    if ("天地图".Equals(ovrStrs[i]))
                                    {
                                        continue;
                                    }

                                    ovserlay1 = ovserlay1 + workspace + ":" + ovrStrs[i] + ",";
                                    strinclude = strinclude + "INCLUDE;";
                                }
                            }

                            string layers = ovserlay1 + workspace + ":" + item.table_name + "," + workspace +
                                            ":drone_cloud_shp";
                            string url2 = url1 + layers + "&CQL_FILTER =INCLUDE;" + strinclude + "case_no=" + caseNo +
                                          "&bbox=" + bbox +
                                          "&width=768&height=646&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE";
                            Console.WriteLine(url2);

                            var draftResult = url2.GetAsync().Result;
                            byte[] img = draftResult.GetBytesAsync().Result;
                            var content1 = new MultipartFormDataContent();
                            long localTimestamp =
                                ((DateTime.Now.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000);
                            var fileContent = new ByteArrayContent(img);
                            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                            {
                                Name = "file", // 这个名字要和Web API中的参数名一致
                                FileName = localTimestamp + ".png"
                            };
                            content1.Add(fileContent);
                            content1.Headers.Add("X-Token", token);
                            var response1 = await client.PostAsync(uploadurl, content1);
                            var imagecontent = JsonConvert.DeserializeObject<Response<SysUploadFile>>(response1.Content
                                .ReadAsStringAsync().Result);
                            SysUploadFile sysUploadFile = imagecontent.Result;
                            if (sysUploadFile == null)
                            {
                                obj.Add("url", "");
                            }
                            else
                            {
                                obj.Add("url", sysUploadFile.FilePath);
                            }

                            string layersxian = workspace + ":geoserverAdd," + workspace + ":drone_cloud_shp";
                            string url3 = url1 + layersxian + "&CQL_FILTER =INCLUDE;" + "case_no=" + caseNo + "&bbox=" +
                                          bbox +
                                          "&width=768&height=646&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE";
                            Console.WriteLine(url3);

                            var draftResultxian = url3.GetAsync().Result;
                            byte[] imgxian = draftResultxian.GetBytesAsync().Result;
                            var content1xian = new MultipartFormDataContent();
                            long localTimestampxian =
                                ((DateTime.Now.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000);
                            var fileContentxian = new ByteArrayContent(imgxian);
                            fileContentxian.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                            {
                                Name = "file", // 这个名字要和Web API中的参数名一致
                                FileName = localTimestampxian + ".png"
                            };
                            content1xian.Add(fileContentxian);
                            content1xian.Headers.Add("X-Token", token);
                            var responsexian = await client.PostAsync(uploadurl, content1xian);
                            var imagecontentxian = JsonConvert.DeserializeObject<Response<SysUploadFile>>(responsexian
                                .Content
                                .ReadAsStringAsync().Result);
                            SysUploadFile sysUploadFile1 = imagecontentxian.Result;
                            if (sysUploadFile1 == null)
                            {
                                obj.Add("urlxian", "");
                            }
                            else
                            {
                                obj.Add("urlxian", sysUploadFile1.FilePath);
                            }

                            /*    MemoryStream memStream = new MemoryStream(img);
                                Image imge = Image.FromStream(memStream);

                                imge.Save("D:/fwtool/" + "abc.png");*/

                            list.Add(obj);
                        }


                        //查询影像记录表
                        //string tifssql = $"select * from geo_tiff_manager where 1=1";

                        List<Object> listyx = new List<Object>();
                        string bianjiesql =
                            $"select c.have_intersection,c.date_dir,c.layer_name from  (SELECT ST_Intersects(st_setsrid(a.geometry, 4326),st_setsrid(b.geom, 4326) ) AS have_intersection,date_dir,layer_name from " +
                            "geo_tiff_manager" + " a ,(select geom from drone_cloud_shp where gid in (" + geomeids +
                            ")" + ") b) c where c.have_intersection=true";
                        Console.WriteLine(bianjiesql);
                        var tiffresult = sqlclient.Ado.SqlQuery<dynamic>(bianjiesql);
                        foreach (var item in tiffresult)
                        {
                            string layers = workspace + ":" + item.layer_name + "," + workspace + ":drone_cloud_shp";

                            Dictionary<string, Object> obj = new Dictionary<string, Object>();

                            //叠加影像

                            string tifurl = url1 + layers + "&CQL_FILTER =INCLUDE;" + "case_no=" + caseNo + "&bbox=" +
                                            bbox +
                                            "&width=768&height=646&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE";
                            var tifResult = tifurl.GetAsync().Result;
                            byte[] imgs = tifResult.GetBytesAsync().Result;
                            var content1 = new MultipartFormDataContent();
                            long localTimestamp =
                                ((DateTime.Now.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000);
                            var fileContent = new ByteArrayContent(imgs);
                            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                            {
                                Name = "file", // 这个名字要和Web API中的参数名一致
                                FileName = localTimestamp + ".png"
                            };
                            content1.Add(fileContent);
                            content1.Headers.Add("X-Token", token);
                            var response1 = await client.PostAsync(uploadurl, content1);
                            var imagecontent = JsonConvert.DeserializeObject<Response<SysUploadFile>>(response1.Content
                                .ReadAsStringAsync().Result);
                            SysUploadFile sysUploadFile = imagecontent.Result;
                            if (sysUploadFile == null)
                            {
                                obj.Add("url", "");
                            }
                            else
                            {
                                obj.Add("url", sysUploadFile.FilePath);
                            }

                            obj.Add("shijian", item.date_dir);
                            listyx.Add(obj);
                        }


                        dict.Add("result", list);
                        dict.Add("yingxiang", listyx);

                        // 调用接口存入query
                        var queryResult = dict;
                        var updateCloudQuery = domain + "api/DroneCloudQuery/UpdateCloudQuery";
                        var req = new CloudQueryReq
                        {
                            // 填充内容 
                            Id = queryId,
                            ReceiveContent = JsonConvert.SerializeObject(queryResult),
                            ReceiveTime = DateTime.Now
                        };
                        var content = new StringContent(JsonConvert.SerializeObject(req), Encoding.UTF8,
                            "application/json");
                        // 添加自定义的HTTP头
                        content.Headers.Add("X-Token", token);
                        await client.PostAsync(updateCloudQuery, content);
                    }

                    Console.WriteLine(result);
                }
            }
            catch (Exception e)
            {
                // 处理请求异常
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }


        await Task.CompletedTask;
    }

    public async Task<string> GetToken()
    {
        try
        {
            // 构建配置
            var configuration = ConfigHelper.GetConfigRoot();
            var password = configuration["LoginPasswd"];
            var getTokenUrl = domain + "api/Check/Login";
            using (var client = new HttpClient())
            {
                dynamic obj = new ExpandoObject();
                obj.account = "System";
                obj.password = password;
                obj.appKey = "openauth";
                var content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8,
                    "application/json");
                var result = client.PostAsync(getTokenUrl, content).Result;
                if (!result.IsSuccessStatusCode) return "";
                // {"result":{"returnUrl":null,"token":"b8387abf"},"message":"操作成功","code":200}
                var responseContent = await result.Content.ReadAsStringAsync();
                Console.WriteLine(responseContent);
                dynamic data = JsonConvert.DeserializeObject(responseContent);
                return data.result.token;
            }

            return "";
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}