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 OpenAuth.App.ServiceApp.Response;
using System.Globalization;
using Infrastructure.Helpers;
using OpenAuth.App.Request;

namespace OpenAuth.App.ServiceApp.Jobs;

public class CloudQueryTimeTask : 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 CloudQueryTimeTask(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/AddTubanshixiang";
            try
            {
                // 创建HttpRequestMessage对象
                var getTaskRequest = new HttpRequestMessage(HttpMethod.Get, url);
                if (token.Equals(""))
                {
                    // 堵塞查询
                    token = GetToken().Result;
                }
                string sqlcount = "select count(a.*)  from (select DISTINCT\tdate_dir from geo_tiff_manager) a";
                string shifouchongfu = "select date_count from datecount_record where id=1 ";
                var piccount = sqlclient.Ado.GetInt(sqlcount);
                var date_count = sqlclient.Ado.GetInt(shifouchongfu);
                if (piccount != date_count)
                {
                    string updatecount = "update datecount_record set date_count=" + piccount + " where id=1";
                    sqlclient.Ado.ExecuteCommand(updatecount);
                    string sqldate = "select date_dir from geo_tiff_manager GROUP BY date_dir";
                    var datelist = sqlclient.Ado.SqlQuery<string>(sqldate);
                    string format = "yyyyMMdd";
                    List<DroneTuBanshixiang> req = new List<DroneTuBanshixiang>();
                    foreach (var item in datelist)
                    {
                        if (string.IsNullOrEmpty(item))
                        {
                            continue;
                        }
                        DateTime dateTime = DateTime.ParseExact(item, format, CultureInfo.InvariantCulture);
                        DroneTuBanshixiang shixiang = new DroneTuBanshixiang();
                        shixiang.Id = Guid.NewGuid().ToString();
                        shixiang.Name = item;
                        shixiang.Time = dateTime;
                        req.Add(shixiang);
                    }
                    var content = new StringContent(JsonConvert.SerializeObject(req), Encoding.UTF8,
                        "application/json");
                    // 添加自定义的HTTP头
                    content.Headers.Add("X-Token", token);
                    await client.PostAsync(url, content);



                }
                else
                {
                    return;
                }





            }
            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/AddTubanshixiang";
            try
            {
                // 创建HttpRequestMessage对象
                var getTaskRequest = new HttpRequestMessage(HttpMethod.Get, url);
                if (token.Equals(""))
                {
                    // 堵塞查询
                    token = GetToken().Result;
                }
                string sqlcount = "select count(a.*)  from (select DISTINCT\tdate_dir from geo_tiff_manager) a";
                string shifouchongfu = "select date_count from datecount_record where id=1 ";
                var piccount = sqlclient.Ado.GetInt(sqlcount);
                var date_count = sqlclient.Ado.GetInt(shifouchongfu);
                if (piccount!=date_count)
                {
                    string updatecount = "update datecount_record set date_count=" + piccount + " where id=1";
                    sqlclient.Ado.ExecuteCommand(updatecount);
                    string sqldate = "select date_dir from geo_tiff_manager GROUP BY date_dir";
                    var datelist = sqlclient.Ado.SqlQuery<string>(sqldate);                 
                    string format = "yyyyMMdd";
                    List<DroneTuBanshixiang> req = new List<DroneTuBanshixiang>();
                    foreach (var item in datelist)
                    {
                        if (string.IsNullOrEmpty(item))
                        {
                            continue;
                        }
                        DateTime dateTime = DateTime.ParseExact(item, format, CultureInfo.InvariantCulture);
                        DroneTuBanshixiang shixiang = new DroneTuBanshixiang();
                        shixiang.Id = Guid.NewGuid().ToString();
                        shixiang.Name = item;
                        shixiang.Time = dateTime;
                        req.Add (shixiang);
                    }
                    var content = new StringContent(JsonConvert.SerializeObject(req), Encoding.UTF8,
                        "application/json");
                    // 添加自定义的HTTP头
                    content.Headers.Add("X-Token", token);
                    await client.PostAsync(url, content);



                }
                else
                {
                    return;
                }

                
                    

                
            }
            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;
        }
    }
}