using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Dynamic;
using System.Net.Http.Headers;
using System.Text;
using Flurl.Http;
using Infrastructure;
using Infrastructure.Extensions;
using Infrastructure.Helpers;
using Microsoft.AspNetCore.Mvc.TagHelpers.Cache;
using NetTopologySuite.Geometries;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
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 Org.BouncyCastle.Crypto.IO;
using Quartz;
using SqlSugar;

namespace OpenAuth.App.ServiceApp.Jobs;

public class CloudQueryScreenshotTask : 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 CloudQueryScreenshotTask(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/DroneCaseInfoTask/LoadDroneCaseInfoTask";
            var piciUrl = domain + "api/DroneCaseInfoTask/LoadDataBaseInfo";
            var updateUrl = domain + "api/DroneCaseInfoTask/UpdateDroneCaseInfo";
            var updateUrlCk = domain + "api/DroneCaseInfoTask/UpdateDroneCaseInfoMinerals";
            var updateTaskProcess = domain + "api/DroneCaseInfoTask/UpdateDroneCaseInfoTask";
            var uploadurl = domain + "api/Files/UploadSingle";
            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<List<ResultItem>>>(result.Content
                        .ReadAsStringAsync().Result);
                    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<List<ResultItem>>>(result.Content.ReadAsStringAsync()
                        .Result);
                    // 遍历批次任务
                    for (var i = 0; i < task.Result.Count; i++)
                    {
                        var item = task.Result[i];
                        var picihao = item.Picihao; // 批次号
                        var caseinfoids = item.Caseinfoids;
                        string shifouchongfu = "select count(*) from picihao_record where picihao='" + picihao + "'";
                        var piccount = sqlclient.Ado.GetInt(shifouchongfu);
                        if (piccount > 0)
                        {
                            continue;
                        }
                        else
                        {
                            string picichongfu = "INSERT INTO picihao_record (\"picihao\") VALUES ('" + picihao + "') ";
                            sqlclient.Ado.ExecuteCommand(picichongfu);
                        }

                        var all = false;
                        string[] infoidslist = { };
                        if ("0".Equals(caseinfoids))
                        {
                            all = true;
                        }
                        else
                        {
                            infoidslist = caseinfoids.Split(',');
                        }

                        var shpids = item.Shplayerids;
                        var geomids = shpids.Split(",");
                        var page = 1;
                        var limit = 100;
                        piciUrl += $"?page={page}&&limit={limit}&&picihao={picihao}";
                        var piciRequest = new HttpRequestMessage(HttpMethod.Get, piciUrl);
                        if (token.Equals(""))
                        {
                            // 堵塞查询
                            token = GetToken().Result;
                        }

                        // 添加Token到Header中
                        piciRequest.Headers.Authorization =
                            new AuthenticationHeaderValue("X-Token", token);
                        // 发送请求
                        var getTaskResponse1 = client.SendAsync(piciRequest);
                        // 阻塞当前线程直到任务完成

                        var result1 = getTaskResponse1.Result;
                        var task1 = JsonConvert.DeserializeObject<Response<PageInfo<List<DroneCaseInfoImport>>>>(result1
                            .Content.ReadAsStringAsync()
                            .Result);


                        var geoserver = GeoUtil.GeoserverUrl;
                        var workspace = GeoUtil.Workspace;
                        // task1 为请示结果
                        var importList = new ArrayList(task1.Result.Total);
                        // 分页处理
                        // 判断是否有下一页
                        int readCount = (page - 1) * limit + task1.Result.Items.Count;
                        var flag = true;
                        while (readCount <= task1.Result.Total)
                        {
                            // 处理图斑信息
                            foreach (var droneShpData in all
                                         ? task1.Result.Items
                                         : task1.Result.Items.Where(a => infoidslist.Contains(a.Id)))
                            {
                                //存储图斑信息
                                string sqlexist = $"select count(*) from drone_cloud_screenshot where id='" +
                                                  droneShpData.Id + "'";

                                int countexist = sqlclient.Ado.GetInt(sqlexist);
                                if (countexist > 0)
                                {
                                    //面
                                    string sqlupdate = $"update drone_cloud_screenshot set geometry =" +
                                                       "ST_GeomFromText('" +
                                                       droneShpData.geom + "') where id = '" + droneShpData.Id + "'";
                                    sqlclient.Ado.ExecuteCommand(sqlupdate);
                                    //点
                                    string sqlupdate1 = $"update drone_cloud_screenshot_point set geometry =" +
                                                        "ST_GeomFromText('Point(" +
                                                        droneShpData.lat + " " + droneShpData.lng + ")') where id = '" +
                                                        droneShpData.Id + "'";
                                    sqlclient.Ado.ExecuteCommand(sqlupdate1);
                                }
                                else
                                {
                                    //面
                                    string sqlinsert =
                                        $"insert into drone_cloud_screenshot(id,geometry,case_no,picihao) VALUES (" +
                                        "" + "'" + droneShpData.Id + "'," + "ST_GeomFromText('" +
                                        droneShpData.geom + "'),'" + droneShpData.case_no + "'," + "'" +
                                        droneShpData.picihao + "'" +
                                        ")";
                                    sqlclient.Ado.ExecuteCommand(sqlinsert);
                                    //点
                                    string sqlinsert1 =
                                        $"insert into drone_cloud_screenshot_point(id,geometry,case_no,picihao) VALUES (" +
                                        "" + "'" + droneShpData.Id + "'," + "ST_GeomFromText('Point(" +
                                        droneShpData.lat + " " + droneShpData.lng + ")'),'" + droneShpData.case_no +
                                        "'," +
                                        "'" +
                                        droneShpData.picihao + "'" +
                                        ")";
                                    sqlclient.Ado.ExecuteCommand(sqlinsert1);
                                }
                            }

                            // 处理任务信息
                            foreach (var droneCloudTask in all
                                         ? task1.Result.Items
                                         : task1.Result.Items.Where(a => infoidslist.Contains(a.Id)))
                            {
                                Dictionary<string, Object> dict = new Dictionary<string, Object>();
                                var geomid = droneCloudTask.Id;
                                var caseNo = droneCloudTask.case_no;

                                string shixiang = "";
                                string gengditupian = "";
                                string tuditupian = "";

                                string sqlbianjian =
                                       $"SELECT\r\n  min(ST_XMin(geometry)) AS min_x,\r\n  min(ST_YMin(geometry)) AS min_y,\r\n " +
                                       $" max(ST_XMax(geometry)) AS max_x,\r\n  max(ST_YMax(geometry)) AS max_y\r\nFROM\r\n  drone_cloud_screenshot where id  in('" +
                                       geomid + "')";
                                var four = sqlclient.Ado.SqlQuerySingle<dynamic>(sqlbianjian);

                                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 bbox = mixLat + "," + minLng + "," + maxLat + "," + maxLng;
                                string url1 = geoserver + "/" + workspace +
                                              "/wms?service=WMS&version=1.1.0&request=GetMap&layers=";
                                for (int i1 = 0; i1 < geomids.Length; i1++)
                                {
                                    //查询配置
                                    string configsql =
                                        $"select * from drone_cloud_query_content where 1=1 and layer='" +
                                        geomids[i1] + "'";
                                    var configresult = sqlclient.Ado.SqlQuerySingle<dynamic>(configsql);
                                    string sqlgeom = $"SELECT count(*) from  drone_cloud_screenshot where id  in ('" +
                                                     geomid + "')";
                                    var geomresult = sqlclient.Ado.GetInt(sqlgeom);
                                    if (geomresult <= 0)
                                    {
                                        continue;
                                    }


                                    List<Object> list = new List<Object>();



                                    var mianjiziduan = configresult.area_field;
                                    Dictionary<string, Object> obj = new Dictionary<string, Object>();

                                    obj.Add("name", configresult.name);

                                    JObject xzqh = GetOrgAreaByPoint((decimal)droneCloudTask.lng, (decimal)droneCloudTask.lat);

                                    var communityname = xzqh["communityname"].ToString();
                                    double mianjiResult = 0.0d;
                                    if ("耕地".Equals(configresult.name) || "基本农田".Equals(configresult.name))
                                    {
                                        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.geometry, 4326)),4326),4527)) AS have_intersection from (" +
                                     $"select geometry from  " + configresult.table_name + $" d where d.zldwmc ='" + communityname +
                                      "') a  ,(select geometry from drone_cloud_screenshot where id in ('" +
                                      geomid + "')" + ") b) c where c.have_intersection>0";
                                        mianjiResult = sqlclient.Ado.GetDouble(mianjisql);
                                        Console.WriteLine(mianjisql);
                                    }
                                    else
                                    {
                                        //计算面积
                                        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.geometry, 4326)),4326),4527)) AS have_intersection from " +
                                            configresult.table_name +
                                            " a  ,(select geometry from drone_cloud_screenshot where id in ('" +
                                            geomid + "')" + ") b) c where c.have_intersection>0";
                                        mianjiResult = sqlclient.Ado.GetDouble(mianjisql);
                                    }

                                    obj.Add("sum", mianjiResult);
                                    obj.Add("list", "");




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

                                    List<Object> listyx = new List<Object>();



                                    //后时相
                                    string bianjiesql1 =
                                        $"select c.have_intersection,c.date_dir,c.layer_name from  (SELECT ST_Intersects(st_setsrid(a.geometry, 4326),st_setsrid(b.geometry, 4326) ) AS have_intersection,date_dir,layer_name from " +
                                        "geo_tiff_manager" +
                                        " a ,(select geometry from drone_cloud_screenshot where id in ('" +
                                        geomid +
                                        "')" + ") b) c where c.have_intersection=true and date_dir='" +
                                        item.Houshixiang.ToString("yyyyMMdd") + "'";
                                    Console.WriteLine(bianjiesql1);
                                    var tiffresult1 = sqlclient.Ado.SqlQuery<dynamic>(bianjiesql1);

                                    foreach (var item1 in tiffresult1)
                                    {
                                        if ("基本农田".Equals(configresult.name) && string.IsNullOrEmpty(gengditupian))
                                        {
                                            if (mianjiResult > 0)
                                            {
                                                string layers =
                                                    workspace + ":" + item1.layer_name + "," + workspace + ":" +
                                                    configresult.table_name + "," + workspace +
                                                    ":drone_cloud_screenshot," + workspace +
                                                    ":drone_cloud_screenshot_point";
                                                string url2 =
                                                    url1 + layers + "&CQL_FILTER =INCLUDE;INCLUDE;" + "" + "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)
                                                {
                                                }
                                                else
                                                {
                                                    gengditupian = sysUploadFile.FilePath;
                                                }
                                            }
                                        }

                                        if (string.IsNullOrEmpty(tuditupian))
                                        {
                                            string layers =
                                                workspace + ":" + item1.layer_name + "," + workspace +
                                                ":geoserverAddPort" + "," + workspace +
                                                ":drone_cloud_screenshot," + workspace +
                                                ":drone_cloud_screenshot_point";
                                            string url2 =
                                                url1 + layers + "&CQL_FILTER =INCLUDE;INCLUDE;" + "" + "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)
                                            {
                                            }
                                            else
                                            {
                                                tuditupian = sysUploadFile.FilePath;
                                            }
                                        }

                                    }

                                    if ("农用地".Equals(configresult.name))
                                    {
                                        if (mianjiResult > 0)
                                        {
                                            decimal mianji = (decimal)mianjiResult;
                                            var resultmianji = Math.Round(mianji * 0.0015m, 2).ToString();
                                            droneCloudTask.nongyongdi_area = resultmianji;
                                        }
                                    }

                                    if ("耕地".Equals(configresult.name))
                                    {
                                        if (mianjiResult > 0)
                                        {

                                            decimal mianji = (decimal)mianjiResult;
                                            var resultmianji = Math.Round(mianji * 0.0015m, 2).ToString();
                                            droneCloudTask.gengdi_area = resultmianji;
                                        }
                                    }

                                    if ("基本农田".Equals(configresult.name))
                                    {
                                        if (mianjiResult > 0)
                                        {

                                            decimal mianji = (decimal)mianjiResult;
                                            var resultmianji = Math.Round(mianji * 0.0015m, 2).ToString();
                                            droneCloudTask.yongjiujibennongtian_area = resultmianji;
                                        }
                                    }

                                    if ("生态红线".Equals(configresult.name))
                                    {
                                        if (mianjiResult > 0)
                                        {
                                            decimal mianji = (decimal)mianjiResult;
                                            var resultmianji = Math.Round(mianji * 0.0015m, 2).ToString();
                                            droneCloudTask.shengtaibaohuhongxian_area = resultmianji;
                                        }
                                    }





                                    if ("违法采矿".Equals(droneCloudTask.subjectname))
                                    {
                                        flag = false;
                                    }



                                }
                                //前时相
                                string bianjiesql =
                                    $"select c.have_intersection,c.date_dir,c.layer_name from  (SELECT ST_Intersects(st_setsrid(a.geometry, 4326),st_setsrid(b.geometry, 4326) ) AS have_intersection,date_dir,layer_name from " +
                                    "geo_tiff_manager" +
                                    " a ,(select geometry from drone_cloud_screenshot where id in ('" +
                                    geomid +
                                    "')" + ") b) c where c.have_intersection=true and date_dir='" +
                                    item.Qianshixiang.ToString("yyyyMMdd") + "'";
                                Console.WriteLine(bianjiesql);
                                var tiffresult = sqlclient.Ado.SqlQuery<dynamic>(bianjiesql);
                                Bitmap bitmap1 = null;
                                Bitmap bitmap2 = null;
                                MemoryStream ms1 = new MemoryStream();
                                MemoryStream ms2 = new MemoryStream();
                                foreach (var item1 in tiffresult)
                                {
                                    string layers1 = workspace + ":" + item1.layer_name + "," + workspace +
                                                     ":drone_cloud_screenshot," + workspace +
                                                     ":drone_cloud_screenshot_point";

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

                                    //叠加影像

                                    string tifurl = url1 + layers1 + "&CQL_FILTER =INCLUDE;INCLUDE;" + "case_no=" +
                                                    caseNo + "&bbox=" +
                                                    bbox +
                                                    "&width=768&height=646&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE";
                                    Console.WriteLine(tifurl);
                                    var tifResult = tifurl.GetAsync().Result;

                                    byte[] imgs = tifResult.GetBytesAsync().Result;
                                    if (imgs == null || imgs.Length == 0)
                                    {
                                        continue;
                                    }
                                    MemoryStream memStream = new MemoryStream(imgs);

                                    using (Image originalImage = Image.FromStream(memStream))
                                    {
                                        // 创建一个新的位图对象
                                        using (bitmap1 = new Bitmap(originalImage))
                                        {
                                            // 创建绘图对象
                                            using (Graphics graphics = Graphics.FromImage(bitmap1))
                                            {
                                                // 设置绘图质量
                                                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                                                graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                                                // 获取当前时间
                                                var zifuchuan = "前时相:" + item.Qianshixiang.ToString("yyyy-MM-dd");

                                                // 设置字体和颜色
                                                Font font = new Font("Arial", 24, FontStyle.Bold);
                                                Brush brush = new SolidBrush(Color.FromArgb(128, 255, 0, 0)); // 半透明白色

                                                // 计算文字位置
                                                SizeF textSize = graphics.MeasureString(zifuchuan, font);
                                                PointF position = new PointF(10, 10);

                                                // 绘制时间水印
                                                graphics.DrawString(zifuchuan, font, brush, position);
                                            }
                                            bitmap1.Save(ms1, ImageFormat.Png);


                                        }
                                        if (bitmap1 != null)
                                        {
                                            break;
                                        }
                                    }
                                    /*  var content2 = new MultipartFormDataContent();
                                      long localTimestamp1 =
                                          ((DateTime.Now.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000);
                                      var fileContent1 = new ByteArrayContent(byteArray);
                                      fileContent1.Headers.ContentDisposition =
                                          new ContentDispositionHeaderValue("form-data")
                                          {
                                              Name = "file", // 这个名字要和Web API中的参数名一致
                                              FileName = localTimestamp1 + ".png"
                                          };
                                      content2.Add(fileContent1);
                                      content2.Headers.Add("X-Token", token);
                                      var response2 = await client.PostAsync(uploadurl, content2);
                                      var imagecontent1 = JsonConvert.DeserializeObject<Response<SysUploadFile>>(
                                          response2
                                              .Content
                                              .ReadAsStringAsync().Result);
                                      SysUploadFile sysUploadFile1 = imagecontent1.Result;
                                      if (sysUploadFile1 == null)
                                      {
                                          continue;
                                      }
                                      else
                                      {
                                          shixiang = sysUploadFile1.FilePath;
                                          break;
                                      }*/
                                }

                                //后时相
                                string bianjiesqlhou =
                                    $"select c.have_intersection,c.date_dir,c.layer_name from  (SELECT ST_Intersects(st_setsrid(a.geometry, 4326),st_setsrid(b.geometry, 4326) ) AS have_intersection,date_dir,layer_name from " +
                                    "geo_tiff_manager" +
                                    " a ,(select geometry from drone_cloud_screenshot where id in ('" +
                                    geomid +
                                    "')" + ") b) c where c.have_intersection=true and date_dir='" +
                                    item.Houshixiang.ToString("yyyyMMdd") + "'";
                                Console.WriteLine(bianjiesqlhou);
                                var tiffresulthou = sqlclient.Ado.SqlQuery<dynamic>(bianjiesqlhou);

                                foreach (var item1 in tiffresulthou)
                                {
                                    string layers1 = workspace + ":" + item1.layer_name + "," + workspace +
                                                   ":drone_cloud_screenshot," + workspace +
                                                   ":drone_cloud_screenshot_point";

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

                                    //叠加影像

                                    string tifurl = url1 + layers1 + "&CQL_FILTER =INCLUDE;INCLUDE;" + "case_no=" +
                                                    caseNo + "&bbox=" +
                                                    bbox +
                                                    "&width=768&height=646&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE";
                                    Console.WriteLine(tifurl);
                                    var tifResult = tifurl.GetAsync().Result;
                                    byte[] imgs = tifResult.GetBytesAsync().Result;
                                    MemoryStream memStream = new MemoryStream(imgs);
                                    if (imgs == null || imgs.Length == 0)
                                    {
                                        continue;
                                    }
                                    using (Image originalImage = Image.FromStream(memStream))
                                    {
                                        // 创建一个新的位图对象
                                        using (bitmap2 = new Bitmap(originalImage))
                                        {
                                            // 创建绘图对象
                                            using (Graphics graphics = Graphics.FromImage(bitmap2))
                                            {
                                                // 设置绘图质量
                                                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                                                graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                                                // 获取当前时间
                                                var zifuchuan = "后时相:" + item.Houshixiang.ToString("yyyy-MM-dd");

                                                // 设置字体和颜色
                                                Font font = new Font("Arial", 24, FontStyle.Bold);
                                                Brush brush = new SolidBrush(Color.FromArgb(128, 255, 0, 0)); // 半透明白色

                                                // 计算文字位置
                                                SizeF textSize = graphics.MeasureString(zifuchuan, font);
                                                PointF position = new PointF(10, 10);

                                                // 绘制时间水印
                                                graphics.DrawString(zifuchuan, font, brush, position);
                                            }

                                            // 保存带有时间水印的图片
                                            // using (MemoryStream ms = new MemoryStream())

                                            // 将 Bitmap 保存到内存流中
                                            bitmap2.Save(ms2, ImageFormat.Png); // 选择合适的图像格式

                                            // 将内存流转换为字节数组
                                            // byteArray = ms.ToArray();


                                        }
                                        if (bitmap2 != null)
                                        {
                                            break;
                                        }
                                    }

                                }

                                byte[] byteArray;
                                if (bitmap1 != null && bitmap2 != null)
                                {

                                    using (Image originalImage = Image.FromStream(ms1))
                                    using (Image originalImage1 = Image.FromStream(ms2))
                                    {
                                        // 创建一个新的位图对象
                                        using (Bitmap bitmap3 = new Bitmap(originalImage))
                                        using (Bitmap bitmap4 = new Bitmap(originalImage1))
                                        {
                                            int newWidth = bitmap3.Width + bitmap4.Width;
                                            int newHeight = Math.Max(bitmap3.Height, bitmap4.Height);

                                            // 创建一个新的 Bitmap 对象，用于存储合并后的图片
                                            using (Bitmap mergedImage = new Bitmap(newWidth, newHeight))
                                            {
                                                // 使用 Graphics 对象在新的 Bitmap 上绘制内容
                                                using (Graphics g = Graphics.FromImage(mergedImage))
                                                {
                                                    // 绘制第一张图片
                                                    g.DrawImage(bitmap3, 0, 0);

                                                    // 绘制第二张图片，从第一张图片的右侧开始
                                                    g.DrawImage(bitmap4, bitmap3.Width, 0);
                                                }
                                                using (MemoryStream ms = new MemoryStream())
                                                {
                                                    mergedImage.Save(ms, ImageFormat.Png);
                                                    byteArray = ms.ToArray();
                                                }
                                                // 保存合并后的图片

                                            }
                                        }
                                    }

                                    var content2 = new MultipartFormDataContent();
                                    long localTimestamp1 =
                                        ((DateTime.Now.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000);
                                    var fileContent1 = new ByteArrayContent(byteArray);
                                    fileContent1.Headers.ContentDisposition =
                                        new ContentDispositionHeaderValue("form-data")
                                        {
                                            Name = "file", // 这个名字要和Web API中的参数名一致
                                            FileName = localTimestamp1 + ".png"
                                        };
                                    content2.Add(fileContent1);
                                    content2.Headers.Add("X-Token", token);
                                    var response2 = await client.PostAsync(uploadurl, content2);
                                    var imagecontent1 = JsonConvert.DeserializeObject<Response<SysUploadFile>>(
                                        response2
                                            .Content
                                            .ReadAsStringAsync().Result);
                                    SysUploadFile sysUploadFile1 = imagecontent1.Result;
                                    if (sysUploadFile1 == null)
                                    {

                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(shixiang))
                                        {
                                            shixiang = shixiang + "," + sysUploadFile1.FilePath;
                                        }
                                        else
                                        {
                                            shixiang = sysUploadFile1.FilePath;
                                        }


                                    }

                                }


                                if (!string.IsNullOrEmpty(gengditupian))
                                {
                                    if (!string.IsNullOrEmpty(shixiang))
                                    {
                                        shixiang = shixiang + "," + gengditupian;
                                    }
                                }

                                if (!string.IsNullOrEmpty(tuditupian))
                                {
                                    if (!string.IsNullOrEmpty(shixiang))
                                    {
                                        shixiang = shixiang + "," + tuditupian;
                                    }
                                }


                                droneCloudTask.casepic = shixiang;
                                importList.Add(droneCloudTask);
                                try
                                {
                                    var process = (importList.Count / task1.Result.Total) * 100;
                                    //调用接口传输进度
                                    var taskId = item.Id;
                                    client.GetAsync(updateTaskProcess + $"?id={taskId}&&rate={process}");
                                }
                                finally
                                {
                                }
                            }

                            Console.WriteLine(result);
                            // 取下一页任务
                            if (readCount < task1.Result.Total)
                            {
                                page++;
                                piciUrl += $"?page={page}&&limit={limit}&&picihao={picihao}";
                                piciRequest = new HttpRequestMessage(HttpMethod.Get, piciUrl);
                                getTaskResponse1 = client.SendAsync(piciRequest);
                                // 阻塞当前线程直到任务完成
                                result1 = getTaskResponse1.Result;
                                task1 = JsonConvert.DeserializeObject<Response<PageInfo<List<DroneCaseInfoImport>>>>(
                                    result1
                                        .Content.ReadAsStringAsync()
                                        .Result);
                            }
                            else if (readCount == task1.Result.Total)
                            {
                                break;
                            }
                        }
                        string delPicihao = "delete from picihao_record where picihao='" + picihao + "'";
                        sqlclient.Ado.ExecuteCommand(delPicihao);
                        // 调用接口存入query
                        var req = new
                        {
                            task = item,
                            importlist = importList
                        };
                        var content = new StringContent(JsonConvert.SerializeObject(req), Encoding.UTF8,
                            "application/json");
                        // 添加自定义的HTTP头
                        content.Headers.Add("X-Token", token);
                        if (flag)
                        {
                            await client.PostAsync(updateUrl, content);
                        }
                        else
                        {
                            await client.PostAsync(updateUrlCk, content);
                        }

                    }
                }
            }
            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/DroneCaseInfoTask/LoadDroneCaseInfoTask";
            var piciUrl = domain + "api/DroneCaseInfoTask/LoadDataBaseInfo";
            var updateUrl = domain + "api/DroneCaseInfoTask/UpdateDroneCaseInfo";
            var updateUrlCk = domain + "api/DroneCaseInfoTask/UpdateDroneCaseInfoMinerals";
            var updateTaskProcess = domain + "api/DroneCaseInfoTask/UpdateDroneCaseInfoTask";
            var uploadurl = domain + "api/Files/UploadSingle";
            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<List<ResultItem>>>(result.Content
                        .ReadAsStringAsync().Result);
                    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<List<ResultItem>>>(result.Content.ReadAsStringAsync()
                        .Result);
                    // 遍历批次任务
                    for (var i = 0; i < task.Result.Count; i++)
                    {
                        var item = task.Result[i];
                        var picihao = item.Picihao; // 批次号
                        var caseinfoids = item.Caseinfoids;
                        string shifouchongfu = "select count(*) from picihao_record where picihao='"+picihao+"'";
                        var piccount = sqlclient.Ado.GetInt(shifouchongfu);
                        if (piccount > 0)
                        {
                            continue;
                        }
                        else {
                            string picichongfu = "INSERT INTO picihao_record (\"picihao\") VALUES ('" + picihao + "') ";
                            sqlclient.Ado.ExecuteCommand(picichongfu);
                        }
                        
                        var all = false;
                        string[] infoidslist = { };
                        if ("0".Equals(caseinfoids))
                        {
                            all = true;
                        }
                        else
                        {
                            infoidslist = caseinfoids.Split(',');
                        }

                        var shpids = item.Shplayerids;
                        var geomids = shpids.Split(",");
                        var page = 1;
                        var limit = 100;
                        piciUrl += $"?page={page}&&limit={limit}&&picihao={picihao}";
                        var piciRequest = new HttpRequestMessage(HttpMethod.Get, piciUrl);
                        if (token.Equals(""))
                        {
                            // 堵塞查询
                            token = GetToken().Result;
                        }

                        // 添加Token到Header中
                        piciRequest.Headers.Authorization =
                            new AuthenticationHeaderValue("X-Token", token);
                        // 发送请求
                        var getTaskResponse1 = client.SendAsync(piciRequest);
                        // 阻塞当前线程直到任务完成

                        var result1 = getTaskResponse1.Result;
                        var task1 = JsonConvert.DeserializeObject<Response<PageInfo<List<DroneCaseInfoImport>>>>(result1
                            .Content.ReadAsStringAsync()
                            .Result);


                        var geoserver = GeoUtil.GeoserverUrl;
                        var workspace = GeoUtil.Workspace;
                        // task1 为请示结果
                        var importList = new ArrayList(task1.Result.Total);
                        // 分页处理
                        // 判断是否有下一页
                        int readCount = (page - 1) * limit + task1.Result.Items.Count;
                        var flag = true;
                        while (readCount <= task1.Result.Total)
                        {
                            // 处理图斑信息
                            foreach (var droneShpData in all
                                         ? task1.Result.Items
                                         : task1.Result.Items.Where(a => infoidslist.Contains(a.Id)))
                            {
                                //存储图斑信息
                                string sqlexist = $"select count(*) from drone_cloud_screenshot where id='" +
                                                  droneShpData.Id + "'";

                                int countexist = sqlclient.Ado.GetInt(sqlexist);
                                if (countexist > 0)
                                {
                                    //面
                                    string sqlupdate = $"update drone_cloud_screenshot set geometry =" +
                                                       "ST_GeomFromText('" +
                                                       droneShpData.geom + "') where id = '" + droneShpData.Id + "'";
                                    sqlclient.Ado.ExecuteCommand(sqlupdate);
                                    //点
                                    string sqlupdate1 = $"update drone_cloud_screenshot_point set geometry =" +
                                                        "ST_GeomFromText('Point(" +
                                                        droneShpData.lat + " " + droneShpData.lng + ")') where id = '" +
                                                        droneShpData.Id + "'";
                                    sqlclient.Ado.ExecuteCommand(sqlupdate1);
                                }
                                else
                                {
                                    //面
                                    string sqlinsert =
                                        $"insert into drone_cloud_screenshot(id,geometry,case_no,picihao) VALUES (" +
                                        "" + "'" + droneShpData.Id + "'," + "ST_GeomFromText('" +
                                        droneShpData.geom + "'),'" + droneShpData.case_no + "'," + "'" +
                                        droneShpData.picihao + "'" +
                                        ")";
                                    sqlclient.Ado.ExecuteCommand(sqlinsert);
                                    //点
                                    string sqlinsert1 =
                                        $"insert into drone_cloud_screenshot_point(id,geometry,case_no,picihao) VALUES (" +
                                        "" + "'" + droneShpData.Id + "'," + "ST_GeomFromText('Point(" +
                                        droneShpData.lat + " " + droneShpData.lng + ")'),'" + droneShpData.case_no +
                                        "'," +
                                        "'" +
                                        droneShpData.picihao + "'" +
                                        ")";
                                    sqlclient.Ado.ExecuteCommand(sqlinsert1);
                                }
                            }

                            // 处理任务信息
                            foreach (var droneCloudTask in all
                                         ? task1.Result.Items
                                         : task1.Result.Items.Where(a => infoidslist.Contains(a.Id)))
                            {
                                Dictionary<string, Object> dict = new Dictionary<string, Object>();
                                var geomid = droneCloudTask.Id;
                                var caseNo = droneCloudTask.case_no;

                                string shixiang = "";
                                string gengditupian = "";
                                string tuditupian = "";

                                string sqlbianjian =
                                       $"SELECT\r\n  min(ST_XMin(geometry)) AS min_x,\r\n  min(ST_YMin(geometry)) AS min_y,\r\n " +
                                       $" max(ST_XMax(geometry)) AS max_x,\r\n  max(ST_YMax(geometry)) AS max_y\r\nFROM\r\n  drone_cloud_screenshot where id  in('" +
                                       geomid + "')";
                                var four = sqlclient.Ado.SqlQuerySingle<dynamic>(sqlbianjian);

                                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 bbox = mixLat + "," + minLng + "," + maxLat + "," + maxLng;
                                string url1 = geoserver + "/" + workspace +
                                              "/wms?service=WMS&version=1.1.0&request=GetMap&layers=";
                                for (int i1 = 0; i1 < geomids.Length; i1++)
                                {
                                    //查询配置
                                    string configsql =
                                        $"select * from drone_cloud_query_content where 1=1 and layer='" +
                                        geomids[i1] + "'";
                                    var configresult = sqlclient.Ado.SqlQuerySingle<dynamic>(configsql);
                                    string sqlgeom = $"SELECT count(*) from  drone_cloud_screenshot where id  in ('" +
                                                     geomid + "')";
                                    var geomresult = sqlclient.Ado.GetInt(sqlgeom);
                                    if (geomresult <= 0)
                                    {
                                        continue;
                                    }

                                   
                                    List<Object> list = new List<Object>();
                                   


                                    var mianjiziduan = configresult.area_field;
                                    Dictionary<string, Object> obj = new Dictionary<string, Object>();

                                    obj.Add("name", configresult.name);

                                    JObject xzqh = GetOrgAreaByPoint((decimal)droneCloudTask.lng, (decimal)droneCloudTask.lat);

                                    var communityname = xzqh["communityname"].ToString();
                                    double mianjiResult = 0.0d;
                                    if ("耕地".Equals(configresult.name) || "基本农田".Equals(configresult.name))
                                    {
                                        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.geometry, 4326)),4326),4527)) AS have_intersection from (" +
                                     $"select geometry from  "+configresult.table_name + $" d where d.zldwmc ='"+communityname+
                                      "') a  ,(select geometry from drone_cloud_screenshot where id in ('" +
                                      geomid + "')" + ") b) c where c.have_intersection>0";
                                         mianjiResult = sqlclient.Ado.GetDouble(mianjisql);
                                        Console.WriteLine(mianjisql);
                                    }
                                    else {
                                        //计算面积
                                        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.geometry, 4326)),4326),4527)) AS have_intersection from " +
                                            configresult.table_name +
                                            " a  ,(select geometry from drone_cloud_screenshot where id in ('" +
                                            geomid + "')" + ") b) c where c.have_intersection>0";
                                         mianjiResult = sqlclient.Ado.GetDouble(mianjisql);
                                    }
                                   
                                    obj.Add("sum", mianjiResult);
                                    obj.Add("list", "");

                                   


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

                                    List<Object> listyx = new List<Object>();
                                   


                                    //后时相
                                    string bianjiesql1 =
                                        $"select c.have_intersection,c.date_dir,c.layer_name from  (SELECT ST_Intersects(st_setsrid(a.geometry, 4326),st_setsrid(b.geometry, 4326) ) AS have_intersection,date_dir,layer_name from " +
                                        "geo_tiff_manager" +
                                        " a ,(select geometry from drone_cloud_screenshot where id in ('" +
                                        geomid +
                                        "')" + ") b) c where c.have_intersection=true and date_dir='" +
                                        item.Houshixiang.ToString("yyyyMMdd") + "'";
                                    Console.WriteLine(bianjiesql1);
                                    var tiffresult1 = sqlclient.Ado.SqlQuery<dynamic>(bianjiesql1);
                                   
                                    foreach (var item1 in tiffresult1)
                                    {
                                        if ("基本农田".Equals(configresult.name) && string.IsNullOrEmpty(gengditupian))
                                        {
                                            if (mianjiResult > 0)
                                            {
                                                string layers =
                                                    workspace + ":" + item1.layer_name + "," + workspace + ":" +
                                                    configresult.table_name + "," + workspace +
                                                    ":drone_cloud_screenshot," + workspace +
                                                    ":drone_cloud_screenshot_point";
                                                string url2 =
                                                    url1 + layers + "&CQL_FILTER =INCLUDE;INCLUDE;" + "" + "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)
                                                {
                                                }
                                                else
                                                {
                                                    gengditupian = sysUploadFile.FilePath;
                                                }
                                            }
                                        }

                                        if (string.IsNullOrEmpty(tuditupian))
                                        {
                                            string layers =
                                                workspace + ":" + item1.layer_name + "," + workspace +
                                                ":geoserverAddPort" + "," + workspace +
                                                ":drone_cloud_screenshot," + workspace +
                                                ":drone_cloud_screenshot_point";
                                            string url2 =
                                                url1 + layers + "&CQL_FILTER =INCLUDE;INCLUDE;" + "" + "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)
                                            {
                                            }
                                            else
                                            {
                                                tuditupian = sysUploadFile.FilePath;
                                            }
                                        }

                                    }

                                    if ("农用地".Equals(configresult.name))
                                    {
                                        if (mianjiResult > 0)
                                        {
                                            decimal mianji = (decimal)mianjiResult;
                                          var resultmianji =   Math.Round(mianji * 0.0015m, 2).ToString();
                                            droneCloudTask.nongyongdi_area = resultmianji;
                                        }
                                    }

                                    if ("耕地".Equals(configresult.name))
                                    {
                                        if (mianjiResult > 0)
                                        {

                                            decimal mianji = (decimal)mianjiResult;
                                            var resultmianji = Math.Round(mianji * 0.0015m, 2).ToString();
                                            droneCloudTask.gengdi_area = resultmianji;
                                        }
                                    }

                                    if ("基本农田".Equals(configresult.name))
                                    {
                                        if (mianjiResult > 0)
                                        {

                                            decimal mianji = (decimal)mianjiResult;
                                            var resultmianji = Math.Round(mianji * 0.0015m, 2).ToString();
                                            droneCloudTask.yongjiujibennongtian_area = resultmianji;
                                        }
                                    }

                                    if ("生态红线".Equals(configresult.name))
                                    {
                                        if (mianjiResult > 0)
                                        {
                                            decimal mianji = (decimal)mianjiResult;
                                            var resultmianji = Math.Round(mianji * 0.0015m, 2).ToString();
                                            droneCloudTask.shengtaibaohuhongxian_area = resultmianji;
                                        }
                                    }


                              
                                  

                                    if ("违法采矿".Equals(droneCloudTask.subjectname))
                                    {
                                        flag = false;
                                    }

                                               
                                    
                                }
                                //前时相
                                string bianjiesql =
                                    $"select c.have_intersection,c.date_dir,c.layer_name from  (SELECT ST_Intersects(st_setsrid(a.geometry, 4326),st_setsrid(b.geometry, 4326) ) AS have_intersection,date_dir,layer_name from " +
                                    "geo_tiff_manager" +
                                    " a ,(select geometry from drone_cloud_screenshot where id in ('" +
                                    geomid +
                                    "')" + ") b) c where c.have_intersection=true and date_dir='" +
                                    item.Qianshixiang.ToString("yyyyMMdd") + "'";
                                Console.WriteLine(bianjiesql);
                                var tiffresult = sqlclient.Ado.SqlQuery<dynamic>(bianjiesql);
                                Bitmap bitmap1 = null;
                                Bitmap bitmap2 = null;
                                MemoryStream ms1 = new MemoryStream();
                                MemoryStream ms2 = new MemoryStream();
                                foreach (var item1 in tiffresult)
                                {
                                    string layers1 = workspace + ":" + item1.layer_name + "," + workspace +
                                                     ":drone_cloud_screenshot," + workspace +
                                                     ":drone_cloud_screenshot_point";

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

                                    //叠加影像

                                    string tifurl = url1 + layers1 + "&CQL_FILTER =INCLUDE;INCLUDE;" + "case_no=" +
                                                    caseNo + "&bbox=" +
                                                    bbox +
                                                    "&width=768&height=646&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE";
                                    Console.WriteLine(tifurl);
                                    var tifResult = tifurl.GetAsync().Result;

                                    byte[] imgs = tifResult.GetBytesAsync().Result;
                                    if (imgs == null || imgs.Length == 0)
                                    {
                                        continue;
                                    }
                                    MemoryStream memStream = new MemoryStream(imgs);
                          
                                    using (Image originalImage = Image.FromStream(memStream))
                                    {
                                        // 创建一个新的位图对象
                                        using ( bitmap1 = new Bitmap(originalImage))
                                        {
                                            // 创建绘图对象
                                            using (Graphics graphics = Graphics.FromImage(bitmap1))
                                            {
                                                // 设置绘图质量
                                                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                                                graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                                                // 获取当前时间
                                                var zifuchuan = "前时相:" + item.Qianshixiang.ToString("yyyy-MM-dd");

                                                // 设置字体和颜色
                                                Font font = new Font("Arial", 24, FontStyle.Bold);
                                                Brush brush = new SolidBrush(Color.FromArgb(128, 255, 0, 0)); // 半透明白色

                                                // 计算文字位置
                                                SizeF textSize = graphics.MeasureString(zifuchuan, font);
                                                PointF position = new PointF(10,10);

                                                // 绘制时间水印
                                                graphics.DrawString(zifuchuan, font, brush, position);
                                            }
                                            bitmap1.Save(ms1, ImageFormat.Png);

                                            
                                        }
                                        if (bitmap1!=null)
                                        {
                                            break;
                                        }
                                    }
                                  /*  var content2 = new MultipartFormDataContent();
                                    long localTimestamp1 =
                                        ((DateTime.Now.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000);
                                    var fileContent1 = new ByteArrayContent(byteArray);
                                    fileContent1.Headers.ContentDisposition =
                                        new ContentDispositionHeaderValue("form-data")
                                        {
                                            Name = "file", // 这个名字要和Web API中的参数名一致
                                            FileName = localTimestamp1 + ".png"
                                        };
                                    content2.Add(fileContent1);
                                    content2.Headers.Add("X-Token", token);
                                    var response2 = await client.PostAsync(uploadurl, content2);
                                    var imagecontent1 = JsonConvert.DeserializeObject<Response<SysUploadFile>>(
                                        response2
                                            .Content
                                            .ReadAsStringAsync().Result);
                                    SysUploadFile sysUploadFile1 = imagecontent1.Result;
                                    if (sysUploadFile1 == null)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        shixiang = sysUploadFile1.FilePath;
                                        break;
                                    }*/
                                }

                                //后时相
                                string bianjiesqlhou =
                                    $"select c.have_intersection,c.date_dir,c.layer_name from  (SELECT ST_Intersects(st_setsrid(a.geometry, 4326),st_setsrid(b.geometry, 4326) ) AS have_intersection,date_dir,layer_name from " +
                                    "geo_tiff_manager" +
                                    " a ,(select geometry from drone_cloud_screenshot where id in ('" +
                                    geomid +
                                    "')" + ") b) c where c.have_intersection=true and date_dir='" +
                                    item.Houshixiang.ToString("yyyyMMdd") + "'";
                                Console.WriteLine(bianjiesqlhou);
                                var tiffresulthou = sqlclient.Ado.SqlQuery<dynamic>(bianjiesqlhou);
                            
                                foreach (var item1 in tiffresulthou)
                                {
                                    string layers1 = workspace + ":" + item1.layer_name + "," + workspace +
                                                   ":drone_cloud_screenshot," + workspace +
                                                   ":drone_cloud_screenshot_point";

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

                                    //叠加影像

                                    string tifurl = url1 + layers1 + "&CQL_FILTER =INCLUDE;INCLUDE;" + "case_no=" +
                                                    caseNo + "&bbox=" +
                                                    bbox +
                                                    "&width=768&height=646&srs=EPSG:4326&format=image/png&TRANSPARENT=TRUE";
                                    Console.WriteLine(tifurl);
                                    var tifResult = tifurl.GetAsync().Result;
                                    byte[] imgs = tifResult.GetBytesAsync().Result;
                                    MemoryStream memStream = new MemoryStream(imgs);
                                    if (imgs==null||imgs.Length==0)
                                    {
                                        continue;
                                    }
                                    using (Image originalImage = Image.FromStream(memStream))
                                    {
                                        // 创建一个新的位图对象
                                        using ( bitmap2 = new Bitmap(originalImage))
                                        {
                                            // 创建绘图对象
                                            using (Graphics graphics = Graphics.FromImage(bitmap2))
                                            {
                                                // 设置绘图质量
                                                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                                                graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                                                // 获取当前时间
                                                var zifuchuan = "后时相:" + item.Houshixiang.ToString("yyyy-MM-dd");

                                                // 设置字体和颜色
                                                Font font = new Font("Arial", 24, FontStyle.Bold);
                                                Brush brush = new SolidBrush(Color.FromArgb(128, 255, 0, 0)); // 半透明白色

                                                // 计算文字位置
                                                SizeF textSize = graphics.MeasureString( zifuchuan, font);
                                                PointF position = new PointF(10,10);

                                                // 绘制时间水印
                                                graphics.DrawString(zifuchuan, font, brush, position);
                                            }

                                            // 保存带有时间水印的图片
                                           // using (MemoryStream ms = new MemoryStream())
                                            
                                                // 将 Bitmap 保存到内存流中
                                                bitmap2.Save(ms2, ImageFormat.Png); // 选择合适的图像格式

                                                // 将内存流转换为字节数组
                                               // byteArray = ms.ToArray();
                                            
                                         
                                        }
                                        if (bitmap2 != null)
                                        {
                                            break;
                                        }
                                    }
                                  
                                }

                                byte[] byteArray;
                                if (bitmap1 != null && bitmap2 != null)
                                {

                                    using (Image originalImage = Image.FromStream(ms1))
                                    using (Image originalImage1 = Image.FromStream(ms2))
                                    {
                                        // 创建一个新的位图对象
                                        using (Bitmap bitmap3 = new Bitmap(originalImage))
                                        using (Bitmap bitmap4 = new Bitmap(originalImage1))
                                        {
                                            int newWidth = bitmap3.Width + bitmap4.Width;
                                            int newHeight = Math.Max(bitmap3.Height, bitmap4.Height);

                                            // 创建一个新的 Bitmap 对象，用于存储合并后的图片
                                            using (Bitmap mergedImage = new Bitmap(newWidth, newHeight))
                                            {
                                                // 使用 Graphics 对象在新的 Bitmap 上绘制内容
                                                using (Graphics g = Graphics.FromImage(mergedImage))
                                                {
                                                    // 绘制第一张图片
                                                    g.DrawImage(bitmap3, 0, 0);

                                                    // 绘制第二张图片，从第一张图片的右侧开始
                                                    g.DrawImage(bitmap4, bitmap3.Width, 0);
                                                }
                                                using (MemoryStream ms = new MemoryStream())
                                                {
                                                    mergedImage.Save(ms, ImageFormat.Png);
                                                    byteArray = ms.ToArray();
                                                }
                                                // 保存合并后的图片

                                            }
                                        }
                                    }
                                     
                                    var content2 = new MultipartFormDataContent();
                                    long localTimestamp1 =
                                        ((DateTime.Now.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000);
                                    var fileContent1 = new ByteArrayContent(byteArray);
                                    fileContent1.Headers.ContentDisposition =
                                        new ContentDispositionHeaderValue("form-data")
                                        {
                                            Name = "file", // 这个名字要和Web API中的参数名一致
                                            FileName = localTimestamp1 + ".png"
                                        };
                                    content2.Add(fileContent1);
                                    content2.Headers.Add("X-Token", token);
                                    var response2 = await client.PostAsync(uploadurl, content2);
                                    var imagecontent1 = JsonConvert.DeserializeObject<Response<SysUploadFile>>(
                                        response2
                                            .Content
                                            .ReadAsStringAsync().Result);
                                    SysUploadFile sysUploadFile1 = imagecontent1.Result;
                                    if (sysUploadFile1 == null)
                                    {

                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(shixiang))
                                        {
                                            shixiang = shixiang + "," + sysUploadFile1.FilePath;
                                        }
                                        else
                                        {
                                            shixiang = sysUploadFile1.FilePath;
                                        }


                                    }

                                }


                                if (!string.IsNullOrEmpty(gengditupian))
                                {
                                    if (!string.IsNullOrEmpty(shixiang))
                                    {
                                        shixiang = shixiang + "," + gengditupian;
                                    }
                                }

                                if (!string.IsNullOrEmpty(tuditupian))
                                {
                                    if (!string.IsNullOrEmpty(shixiang))
                                    {
                                        shixiang = shixiang + "," + tuditupian;
                                    }
                                }


                                droneCloudTask.casepic = shixiang;
                                importList.Add(droneCloudTask);
                                try
                                {
                                    var process = (importList.Count / task1.Result.Total) * 100;
                                    //调用接口传输进度
                                    var taskId = item.Id;
                                    client.GetAsync(updateTaskProcess + $"?id={taskId}&&rate={process}");
                                }
                                finally
                                {
                                }
                            }

                            Console.WriteLine(result);
                            // 取下一页任务
                            if (readCount < task1.Result.Total)
                            {
                                page++;
                                piciUrl += $"?page={page}&&limit={limit}&&picihao={picihao}";
                                piciRequest = new HttpRequestMessage(HttpMethod.Get, piciUrl);
                                getTaskResponse1 = client.SendAsync(piciRequest);
                                // 阻塞当前线程直到任务完成
                                result1 = getTaskResponse1.Result;
                                task1 = JsonConvert.DeserializeObject<Response<PageInfo<List<DroneCaseInfoImport>>>>(
                                    result1
                                        .Content.ReadAsStringAsync()
                                        .Result);
                            }
                            else if (readCount == task1.Result.Total)
                            {
                                break;
                            }
                        }
                        string delPicihao = "delete from picihao_record where picihao='" + picihao + "'";
                        sqlclient.Ado.ExecuteCommand(delPicihao);
                        // 调用接口存入query
                        var req = new
                        {
                            task = item,
                            importlist = importList
                        };
                        var content = new StringContent(JsonConvert.SerializeObject(req), Encoding.UTF8,
                            "application/json");
                        // 添加自定义的HTTP头
                        content.Headers.Add("X-Token", token);
                        if (flag)
                        {
                            await client.PostAsync(updateUrl, content);
                        }
                        else
                        {
                            await client.PostAsync(updateUrlCk, content);
                        }
                     
                    }
                }
            }
            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;
        }
    }


    public JObject GetOrgAreaByPoint(decimal lng, decimal lat)
    {
        //县id
        string countyid = "";
        string countyname = "";
        //镇id
        string streetid = "";
        string streetname = "";
        //村id
        string communityid = "";
        string communityname = "";

        //SqlSugar实例
        using (var db = sqlclient)
        {
            //查询坐标属于哪个县
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat($" SELECT xzqdm,xzqmc FROM \"shp_drone_county\" where ST_Within(st_geomfromtext('POINT({lng} {lat})',4326), ST_SetSRID(geom,4326))");
            var countyList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
            if (countyList.Count > 0)
            {
                //县名称
                countyname = countyList[0].xzqmc;
                //县id
                countyid = countyList[0].xzqdm;
            }

            //查询坐标属于哪个镇
            sql = new StringBuilder();
            sql.AppendFormat($" SELECT xzqdm,xzqmc FROM \"shp_drone_town\" where ST_Within(st_geomfromtext('POINT({lng} {lat})',4326), ST_SetSRID(geom,4326))");
            var streetList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
            if (streetList.Count > 0)
            {
                //镇名称
                streetname = streetList[0].xzqmc;
                //镇id
                streetid = streetList[0].xzqdm;
            }

            if (!string.IsNullOrEmpty(streetid))
            {
                //查询组织机构属于哪个村
                sql = new StringBuilder();
                sql.AppendFormat($" SELECT zldwdm,zldwmc FROM \"shp_drone_community\" where ST_Within(st_geomfromtext('POINT({lng} {lat})',4326), ST_SetSRID(geom,4326))");
                var communityidList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
                if (communityidList.Count > 0)
                {
                    //村名称
                    communityname = communityidList[0].zldwmc;
                    //村id
                    communityid = communityidList[0].zldwdm;
                }
            }

            //拼接json数据，返回到前台
            JObject obj = new JObject();

            obj.Add("countyid", countyid);
            obj.Add("countyname", countyname);
            obj.Add("streetid", streetid);
            obj.Add("streetname", streetname);
            obj.Add("communityid", communityid);
            obj.Add("communityname", communityname);

            return obj;
        }
    }
}