using Infrastructure;
using Newtonsoft.Json;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.Algo.Request;
using OpenAuth.App.ServiceApp.Algo.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenAuth.App.ServiceApp.Algo
{

    public class DaHuaAiApp : SqlSugarBaseApp<LasaAlgorithmsRepository, SugarDbContext>
    {
        public DaHuaAiApp(ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<LasaAlgorithmsRepository> repository, IAuth auth) : base(unitWork, repository, auth)
        {
        }

        #region 大华算法
        //分析两次航线图片
        public async Task<Response<List<dynamic>>> BehaviorAlarm(string firstId, string secondId)
        {
            using (var db = UnitWork.CreateContext())
            {
                //var imageList1 = await db.LasaMediaFile.AsQueryable().Where(r => r.TaskId == firstId && r.AbsoluteAltitude != 0 && r.AbsoluteAltitude != null).ToListAsync();
                //var imageList2 = await db.LasaMediaFile.AsQueryable().Where(r => r.TaskId == secondId && r.AbsoluteAltitude != 0 && r.AbsoluteAltitude != null).ToListAsync();
                var imageList1 = await db.LasaMediaFile.AsQueryable().Where(r => r.Id == firstId && r.AbsoluteAltitude != 0 && r.AbsoluteAltitude != null).ToListAsync();
                var imageList2 = await db.LasaMediaFile.AsQueryable().Where(r => r.Id == secondId && r.AbsoluteAltitude != 0 && r.AbsoluteAltitude != null).ToListAsync();
                List<dynamic> dataList = new List<dynamic>();
                for (int i = 0; i < imageList1.Count; i++)
                {
                    dataList.Add(new
                    {
                        @event = "event.capturePic",
                        uid = "1",
                        channelCode = "sdhc04",
                        recordId = "kQUXlb1Y8oDgCpZSo7l2yG175617335006157587",
                        sourceId = "kQUXlb1Y8oDgCpZSo7l2yG175617335006157587",
                        taskSource = 1,
                        taskId = "8ab0e1e213234a848e20d0d335559786",
                        capTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                        taskTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                        imageInfo = new
                        {
                            imgSize = 1667235,
                            imgWidth = 4032,
                            imgHeight = 3024
                        },
                        imageInfoList = new[]
                        {
                            new {
                                imgUrl = "http://175.27.168.120:6013/test/"+imageList1[i].ObjectKey,
                                imgSize = imageList1[i].Size,
                                imgWidth = imageList1[i].Width,
                                imgHeight = imageList1[i].Height,
                                imgType = 0,
                                longitude = imageList1[i].Lng,
                                absAltitude = imageList1[i].AbsoluteAltitude,
                                latitude = imageList1[i].Lat,
                                zoom =  imageList1[i].DigitalZoomRatio,
                                yaw = imageList1[i].GimbalYawDegree,
                                pitch = imageList1[i].GimbalPitchDegree,
                                roll = imageList1[i].GimbalRollDegree,
                                focalLength = imageList1[i].FocalLength
                            },
                            new {
                                imgUrl = "http://175.27.168.120:6013/test/"+imageList2[i].ObjectKey,
                                imgSize = imageList2[i].Size,
                                imgWidth = imageList2[i].Width,
                                imgHeight = imageList2[i].Height,
                                imgType = 1,
                                longitude =imageList2[i].Lng,
                                absAltitude =  imageList2[i].AbsoluteAltitude,//拍摄绝对高度
                                latitude = imageList2[i].Lat,
                                zoom = imageList2[i].DigitalZoomRatio,//放大倍率
                                yaw =imageList2[i].GimbalYawDegree,//偏航角？
                                pitch = imageList2[i].GimbalPitchDegree,//滚角？
                                roll = imageList2[i].GimbalRollDegree,
                                focalLength = imageList2[i].FocalLength//焦距
                            }
                        }
                    });
                }
                return new Response<List<dynamic>>
                {
                    Result = dataList,
                    Message = "获取数据成功"
                };
            }
        }
        public async Task<Response<bool>> AddDaHuaImg(string info)
        {
            using (var db = UnitWork.CreateContext())
            {
                var data = JsonConvert.DeserializeObject<dynamic>(info);
                LasaAiAchievement lasaAiAchievement = new LasaAiAchievement();
                lasaAiAchievement.Id = Guid.NewGuid().ToString();
                lasaAiAchievement.Title = "疑似耕地破坏";
                lasaAiAchievement.CreateTime = DateTime.Now;
                lasaAiAchievement.AiModel = "DaHuaAi";
                var imageList = data.imageInfoList;
                foreach (var item in imageList)
                {
                    //插入详情
                    LasaAiAchievementDetail lasaAiAchievementDetail = new LasaAiAchievementDetail()
                    {
                        Id = Guid.NewGuid().ToString(),
                        Image = item.imgUrl,
                        AiAchievementId = lasaAiAchievement.Id
                    };
                    lasaAiAchievement.Lat = item.latitude;
                    lasaAiAchievement.Lng = item.longitude;
                    lasaAiAchievement.Cover = item.imgUrl;
                    await db.LasaAiAchievementDetail.InsertAsync(lasaAiAchievementDetail);
                }

                //await db.LasaAiAchievement.InsertAsync(lasaAiAchievement);
                if (db.Commit())
                    return new Response<bool>
                    {
                        Result = true,
                        Message = "添加成功"
                    };
                else
                    return new Response<bool>
                    {
                        Result = false,
                        Message = "添加失败"
                    };
            }
        }

        #endregion


        #region 本地模型
        public async Task<Response<bool>> AddImgOld(string taskid, string path, string tag)
        {
            using (var db = UnitWork.CreateContext())
            {
                var info = await db.LasaAiAchievement.GetFirstAsync(r => r.TaskId == taskid);
                if (info == null)
                {
                    LasaAiAchievement lasaAiAchievement = new LasaAiAchievement();
                    lasaAiAchievement.Id = Guid.NewGuid().ToString();
                    var tags = JsonConvert.DeserializeObject<List<TagItem>>(tag);
                    var confidence = tags.Select(r => r.confidence).Max();
                    foreach (var item in tags)
                    {
                        if (item.class_id == 1 || item.class_id == 2 || item.class_id == 3 || item.class_id == 5 || item.class_id == 6 || item.class_id == 6)
                        {
                            lasaAiAchievement.Title = "疑似车辆入侵";
                        }
                    }
                    lasaAiAchievement.CreateTime = DateTime.Now;
                    lasaAiAchievement.TaskId = taskid;
                    lasaAiAchievement.AiModel = "yolo12x";
                    lasaAiAchievement.ConfidenceLevel = confidence;
                    await db.LasaAiAchievement.InsertAsync(lasaAiAchievement);
                    //插入详情
                    LasaAiAchievementDetail lasaAiAchievementDetail = new LasaAiAchievementDetail()
                    {
                        Id = Guid.NewGuid().ToString(),
                        Image = "http://175.27.168.120:6013/test/" + path,
                        AiAchievementId = lasaAiAchievement.Id
                    };
                    await db.LasaAiAchievementDetail.InsertAsync(lasaAiAchievementDetail);
                }
                else
                {
                    //插入详情
                    LasaAiAchievementDetail lasaAiAchievementDetail = new LasaAiAchievementDetail()
                    {
                        Id = Guid.NewGuid().ToString(),
                        Image = path,
                        AiAchievementId = info.Id
                    };
                    await db.LasaAiAchievementDetail.InsertAsync(lasaAiAchievementDetail);
                }
                if (db.Commit())
                    return new Response<bool>
                    {
                        Result = true,
                        Message = "添加成功"
                    };
                else
                    return new Response<bool>
                    {
                        Result = false,
                        Message = "添加失败"
                    };
            }
        }
        public async Task<Response<bool>> AddImg(string taskid, string path, List<TagItem> tag)
        {
            using (var db = UnitWork.CreateContext())
            {
                foreach (var item in tag)
                {
                    var info = await db.LasaAiAchievement.GetFirstAsync(r => r.TaskId == taskid && r.Tag == item.class_id.ToString());
                    if (info == null)
                    {
                        LasaAiAchievement lasaAiAchievement = new LasaAiAchievement();
                        lasaAiAchievement.Id = Guid.NewGuid().ToString();
                        lasaAiAchievement.CreateTime = DateTime.Now;
                        lasaAiAchievement.TaskId = taskid;
                        lasaAiAchievement.AiModel = "yolo12x";
                        lasaAiAchievement.Tag = item.class_id.ToString();
                        if (item.class_id == 1 || item.class_id == 2 || item.class_id == 3 || item.class_id == 5 || item.class_id == 6 || item.class_id == 7)
                        {
                            lasaAiAchievement.Title = "车辆识别";
                        }
                        else if (item.class_id == 0)
                        {
                            lasaAiAchievement.Title = "人员识别";
                        }
                        else
                        {
                            lasaAiAchievement.Title = "其他识别";
                        }
                        //var confidence = tag.Select(r => r.confidence).Max();
                        var confidence = item.confidence;
                        if (confidence < 0.3)
                        {
                            break;
                        }
                        lasaAiAchievement.ConfidenceLevel = (float)Math.Round(confidence, 2) * 100;

                        //插入详情
                        LasaAiAchievementDetail lasaAiAchievementDetail = new LasaAiAchievementDetail()
                        {
                            Id = Guid.NewGuid().ToString(),
                            Image = "http://175.27.168.120:6013/test/" + path,
                            AiAchievementId = lasaAiAchievement.Id
                        };
                        lasaAiAchievement.Cover = "http://175.27.168.120:6013/test/" + path;
                        lasaAiAchievement.Lat = (float)35.135026;
                        lasaAiAchievement.Lng = (float)118.296182;
                        await db.LasaAiAchievement.InsertAsync(lasaAiAchievement);
                        await db.LasaAiAchievementDetail.InsertAsync(lasaAiAchievementDetail);
                    }
                    else
                    {
                        //插入详情
                        LasaAiAchievementDetail lasaAiAchievementDetail = new LasaAiAchievementDetail()
                        {
                            Id = Guid.NewGuid().ToString(),
                            Image = "http://175.27.168.120:6013/test/" + path,
                            AiAchievementId = info.Id
                        };
                        await db.LasaAiAchievementDetail.InsertAsync(lasaAiAchievementDetail);
                    }

                }
                if (db.Commit())
                    return new Response<bool>
                    {
                        Result = true,
                        Message = "添加成功"
                    };
                else
                    return new Response<bool>
                    {
                        Result = false,
                        Message = "添加失败"
                    };
            }
        }
        #endregion


    }
}
