using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Infrastructure;
using Infrastructure.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Const;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.FireManagement.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Domain.FireManagement;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace OpenAuth.App.ServiceApp.FireManagement
{
    public class FireCodeH5App : SqlSugarBaseApp<FmSiteInfo, SugarDbContext>
    {
        public FireCodeH5App(ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<FmSiteInfo> repository, IAuth auth) : base(unitWork, repository, auth)
        {
            _auth = auth;
        }
        public async Task<Response<bool>> AddEnteringInfo(FmEnteringInfo info)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                info.Id = YitIdHelper.NextId();
                info.InTime = info.InTime.Year == 0001 ? DateTime.Now : info.InTime;
                if (info.RegistrationType == 0)
                    info.RegistrationType = 1;
                //出山登记，修改进山登记时的出山时间
                if (info.RegistrationType == 2)
                {
                    var oldinfo = await db.FmEnteringInfo.AsQueryable().Where(r => r.Phone == info.Phone).OrderByDescending(r => r.InTime).FirstAsync();
                    if (oldinfo != null)
                    {
                        oldinfo.OutTime = DateTime.Now;
                        await db.FmEnteringInfo.UpdateAsync(oldinfo);
                        info.InTime = oldinfo.InTime;
                        info.OutTime = DateTime.Now;
                        await db.FmEnteringInfo.InsertAsync(info);
                    }
                    else
                    {
                        info.OutTime = DateTime.Now;
                        await db.FmEnteringInfo.InsertAsync(info);
                    }
                }
                else
                {
                    await db.FmEnteringInfo.InsertAsync(info);
                }
                if (db.Commit())
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }
            }
        }
        public async Task<Response<PageInfo<List<dynamic>>>> LoadNameInfoByPhone(string phone, int pageIndex, int pageSize)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                RefAsync<int> totalNumber = 0;
                var query = await db.FmEnteringInfo.AsQueryable()
                    .Where(r => r.Phone == phone)
                    .Select<dynamic>(r => new
                    {
                        r.UserName,
                        r.Phone,
                        r.UserAddress,
                        r.CardNo
                    }).ToPageListAsync(pageIndex, pageSize, totalNumber);
                return new Response<PageInfo<List<dynamic>>>
                {
                    Result = new PageInfo<List<dynamic>> { Items = query, Total = totalNumber }
                };
            }
        }

        public async Task<Response<dynamic>> GetSiteInfo(long siteId)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                RefAsync<int> totalNumber = 0;
                var info = await db.FmSiteInfo.AsQueryable()
                    .Where(r => r.Id == siteId).Select<dynamic>(r => new
                    {
                        Id = r.Id.SelectAll(),
                        Accumulate = SqlFunc.Subqueryable<FmEnteringInfo>().Where(b => b.SiteId == r.Id).Count(),
                    }).FirstAsync();
                var userinfo = await db.FmSiteUser.AsQueryable()
                    .LeftJoin<SysUser>((a, b) => a.SiteUserId == b.Id.ToString()).Select<dynamic>((a, b) => new
                    {
                        Id = a.Id,
                        SiteUserId = a.SiteUserId,
                        SiteId = a.SiteId,
                        UserRole = a.UserRole,
                        Name = b.Name,
                        Phone = b.Account
                    }).ToListAsync();
                info.SiteUser = userinfo;
                return new Response<dynamic>
                {
                    Result = info
                };
            }
        }
        public async Task GetFireInfoAsync()
        {
            using (var client = new HttpClient())
            {
                string county = "费县";
                string url = $"http://221.2.83.254:9001/api/YingJiJu/LoadInfo?county={Uri.EscapeDataString(county)}&pageIndex=1&pageSize=10";

                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("text/plain"));
                try
                {
                    // 发起 GET 请求
                    HttpResponseMessage response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        string content = await response.Content.ReadAsStringAsync();
                        // 先反序列化为 JObject 以方便访问嵌套属性
                        var root = Newtonsoft.Json.Linq.JObject.Parse(content);

                        // 判断返回码
                        if (root["code"]?.ToString() != "200")
                        {
                            return;
                        }
                        // 解析 data 数组
                        var dataArray = root["data"]?.ToObject<List<YingJiJuResp>>();
                        if (dataArray == null || dataArray.Count == 0)
                        {
                            return;
                        }
                        using (SugarDbContext db = base.UnitWork.CreateContext())
                        {
                            var today = DateTime.Now.Date;
                            var tomorrow = today.AddDays(1);
                            var exitinfo = db.FmFireclueInfo
                                .AsQueryable()
                                .Count(a => a.ReportTime >= today && a.ReportTime < tomorrow);
                            int counter = exitinfo + 1;
                            List<FmFireclueInfo> fireInfo = new List<FmFireclueInfo>();
                            foreach (var item in dataArray)
                            {
                                var imgutls = ConvertAndReplaceUrls(item.images_path);
                                string excount = counter.ToString("D3");
                                string clueNo = $"LH{DateTime.Now:yyyyMMdd}{excount}J";
                                fireInfo.Add(new FmFireclueInfo
                                {
                                    Id = item.details_id,
                                    ReportPerson = "",
                                    ReportTime = item.start_time,
                                    Describe = item.detailed_address,
                                    Address = item.detailed_address,
                                    Lng = item.longitude.ToString(),
                                    Lat = item.latitude.ToString(),
                                    SourceType = (int)SourceType.高空瞭望,
                                    State = item.state == 0 ? 2 : 3,
                                    AreaName = item.county,
                                    DegreeType = 3,
                                    ClueNo = clueNo,
                                    Image = imgutls
                                });
                                counter++;
                                await db.FmFireclueinfoLog.InsertAsync(new FmFireclueinfoLog
                                {
                                    Id = YitIdHelper.NextId(),
                                    Fireclueid = item.details_id,
                                    Title = "火情线索上报",
                                    CreateTime = item.start_time,
                                    Content = item.detailed_address
                                });
                            }
                            await db.FmFireclueInfo.InsertOrUpdateAsync(fireInfo);
                            db.Commit();
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }


        public static string ConvertAndReplaceUrls(string jsonArrayString)
        {
            try
            {
                string raw = jsonArrayString.Replace("\\\"", "\"");
                var urls = JsonConvert.DeserializeObject<List<string>>(raw);
                if (urls == null || urls.Count == 0)
                    return string.Empty;
                for (int i = 0; i < urls.Count; i++)
                {
                    urls[i] = ReplaceIp(urls[i]);
                }

                return string.Join(",", urls);
            }
            catch (Exception ex)
            {
                return $"处理出错: {ex.Message}";
            }
        }

        private static string ReplaceIp(string url)
        {
            var ipRegex = new Regex(@"^http:\/\/\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b:\b[0-9]{1,5}\b\/");
            var match = ipRegex.Match(url);
            if (!match.Success) return url;

            string prefix = match.Value;
            return prefix switch
            {
                "http://10.176.126.121:8087/" => url.Replace(prefix, "http://221.2.83.254:7011/service1/"),
                "http://10.176.126.121:8089/" => url.Replace(prefix, "http://221.2.83.254:7011/service2/"),
                "http://10.176.126.121:8093/" => url.Replace(prefix, "http://221.2.83.254:7011/service3/"),
                "http://10.176.126.121:8085/" => url.Replace(prefix, "http://221.2.83.254:7011/service4/"),
                "http://10.176.126.121:8091/" => url.Replace(prefix, "http://221.2.83.254:7011/service5/"),
                "http://10.176.126.121:8088/" => url.Replace(prefix, "http://221.2.83.254:7011/service6/"),
                "http://10.176.126.121:8092/" => url.Replace(prefix, "http://221.2.83.254:7011/service7/"),
                "http://10.176.126.121:8094/" => url.Replace(prefix, "http://221.2.83.254:7011/service8/"),
                _ => url
            };
        }

        //public async Task<string> GetToken()
        //{
        //    using (var client = new HttpClient())
        //    {
        //        string url = "http://221.2.83.254:9001/api/YingJiJu/QueryFireToken?username=test&password=Bsh4oyWqURA57%2FKcppKqf2knhoUVI3sjGcZuTwUiVZmorKPbOYMkTpchoULYv1OnWVmMGq%2FtaKT9Z7UZBuGcZO%2BYnm33tWhTMQQFKS1k71d99GinTaJje%2FV9MDksDP%2B6Rj35mKvLGnFdbvdAxfOdyKodaIEdKjgIjUiSi5kpoiSn%2BwZ8knYpgTHsWHjWPL8j7zDJKOcBQUpyMyHFdMUOg6%2BGhp9dIrk98AqbdXy8owaQGdjmbcz0TyvfCWCiA53PQDGKH3qjSHHipUGHD2jWaMnx7gSV4ytMaH3X8P%2Bw7QxoZIVCDTB24E9OWNeopb53FAJOTnvO%2FK0JLg2K%2Buonlw%3D%3D";
        //        HttpResponseMessage response = await client.GetAsync(url);
        //        if (response.IsSuccessStatusCode)
        //        {
        //            var content = await response.Content.ReadAsStringAsync();
        //            return "";
        //        }

        //    }
        //}
    }
}
