using System.Dynamic;
using System.Net.Http.Headers;
using System.Text;
using System.Drawing;
using Flurl.Http;
using Infrastructure;
using Infrastructure.Extensions;
using Newtonsoft.Json;
using OpenAuth.App.ServiceApp.DroneCloudQuery;
using OpenAuth.App.ServiceApp.DroneCloudQueryManage.Request;
using OpenAuth.Repository.Domain;
using Quartz;
using SqlSugar;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Mvc;
using System;
using Microsoft.AspNetCore.Http;
using DocumentFormat.OpenXml.Drawing.Charts;
using System.Net.Http.Json;
using OpenAuth.App.ServiceApp.ShpGeo.Utils;
using System.Collections.Generic;
using Infrastructure.Helpers;
using OpenAuth.App.ServiceApp.Response;

namespace OpenAuth.App.ServiceApp.Jobs;

public class CloudQueryLandTask : 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 CloudQueryLandTask(OpenJobApp openJobApp, ISqlSugarClient sqlSugarClient)
    {
        _openJobApp = openJobApp;
        this.sqlclient = sqlSugarClient;
    }

    public async Task Execute(IJobExecutionContext context)
    {
        var jobId = context.MergedJobDataMap.GetString(Define.JOBMAPKEY);
        //todo:获取到定时任务的id，可以可以加入自己的自动任务逻辑
        //  获取云查询任务  调用接口
        using (var client = new HttpClient())
        {
            // 设置GET请求的URL
            var url = domain + "api/DroneCloudQuery/LoadDroneLandTask";
            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<DroneCloudLandTask>>>(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<DroneCloudLandTask>>>(result.Content
                        .ReadAsStringAsync().Result);
                    var geoserver = GeoUtil.GeoserverUrl;
                    var workspace = GeoUtil.Workspace;

                    foreach (var droneCloudTask in task.Result)

                    {
                        var queryId = droneCloudTask.QueryId;
                        Dictionary<string, Object> dict = new Dictionary<string, Object>();
                        string sql = $"select DISTINCT dlbm as  id,dlmc as name from geoserver371302";
                        var landtypelist = sqlclient.Ado.SqlQuery<DroneLandType>(sql);

                        var AddDroneLandType = domain + "api/DroneCloudQuery/AddDroneLandType";
                        var landreq = new AddOrUpdateDroneLandType
                        {
                            // 填充内容 
                            count = landtypelist.Count,
                            landList = landtypelist,
                        };
                        var landContent = new StringContent(JsonConvert.SerializeObject(landreq), Encoding.UTF8,
                            "application/json");
                        // 添加自定义的HTTP头
                        landContent.Headers.Add("X-Token", token);
                        await client.PostAsync(AddDroneLandType, landContent);

                        string sqljiaoji =
                            $"select ST_Force2D(b.geomstr) as geomstr from (\tselect st_astext( a.intersection) as geomstr from (\tSELECT ST_Intersection('" +
                            droneCloudTask.GeomData +
                            $"',st_astext(geometry)) AS intersection\r\nFROM   geoserver371302 ) a where a.intersection !='010300000000000000') b where b.geomstr like '%POLYGON%'";

                        string sqlheji =
                            $" select st_astext(st_union(c.geomstr)) from ( select ST_Force2D(b.geomstr) as geomstr from (\tselect st_astext( a.intersection) as geomstr from (\tSELECT ST_Intersection('" +
                            droneCloudTask.GeomData +
                            $"',st_astext(geometry)) AS intersection\r\nFROM   geoserver371302 ) a where a.intersection !='010300000000000000') b where b.geomstr like '%POLYGON%' ) c";
                        var jiaojistr = sqlclient.Ado.GetString(sqlheji);
                        string sqlchaji = $"select st_astext(a.intersection) from (\tSELECT ST_Difference('" +
                                          droneCloudTask.GeomData + "','" + jiaojistr + "') AS intersection ) a ";
                        var chajistr = sqlclient.Ado.GetString(sqlchaji);
                        dict.Add("jiaoji", jiaojistr);
                        dict.Add("chaji", chajistr);


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

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

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


    public async Task Execute1()
    {
        //todo:获取到定时任务的id，可以可以加入自己的自动任务逻辑
        //  获取云查询任务  调用接口
        using (var client = new HttpClient())
        {
            // 设置GET请求的URL
            var url = domain + "api/DroneCloudQuery/LoadDroneLandTask";
            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<DroneCloudLandTask>>>(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<DroneCloudLandTask>>>(result.Content
                        .ReadAsStringAsync().Result);
                    var geoserver = GeoUtil.GeoserverUrl;
                    var workspace = GeoUtil.Workspace;

                    foreach (var droneCloudTask in task.Result)

                    {
                        var queryId = droneCloudTask.QueryId;
                        Dictionary<string, Object> dict = new Dictionary<string, Object>();
                        string sql = $"select DISTINCT dlbm as  id,dlmc as name from geoserver371302";
                        var landtypelist = sqlclient.Ado.SqlQuery<DroneLandType>(sql);

                        var AddDroneLandType = domain + "api/DroneCloudQuery/AddDroneLandType";
                        var landreq = new AddOrUpdateDroneLandType
                        {
                            // 填充内容 
                            count = landtypelist.Count,
                            landList = landtypelist,
                        };
                        var landContent = new StringContent(JsonConvert.SerializeObject(landreq), Encoding.UTF8,
                            "application/json");
                        // 添加自定义的HTTP头
                        landContent.Headers.Add("X-Token", token);
                        await client.PostAsync(AddDroneLandType, landContent);

                        string sqljiaoji =
                            $"select ST_Force2D(b.geomstr) as geomstr from (\tselect st_astext( a.intersection) as geomstr from (\tSELECT ST_Intersection('" +
                            droneCloudTask.GeomData +
                            $"',st_astext(geometry)) AS intersection\r\nFROM   geoserver371302 ) a where a.intersection !='010300000000000000') b where b.geomstr like '%POLYGON%'";

                        string sqlheji =
                            $" select st_astext(st_union(c.geomstr)) from ( select ST_Force2D(b.geomstr) as geomstr from (\tselect st_astext( a.intersection) as geomstr from (\tSELECT ST_Intersection('" +
                            droneCloudTask.GeomData +
                            $"',st_astext(geometry)) AS intersection\r\nFROM   geoserver371302 ) a where a.intersection !='010300000000000000') b where b.geomstr like '%POLYGON%' ) c";
                        var jiaojistr = sqlclient.Ado.GetString(sqlheji);
                        string sqlchaji = $"select st_astext(a.intersection) from (\tSELECT ST_Difference('" +
                                          droneCloudTask.GeomData + "','" + jiaojistr + "') AS intersection ) a ";
                        var chajistr = sqlclient.Ado.GetString(sqlchaji);
                        dict.Add("jiaoji", jiaojistr);
                        dict.Add("chaji", chajistr);


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

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


        await Task.CompletedTask;
    }

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

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