using MoYu.FriendlyException;
using MoYu.RemoteRequest;
using MoYu.RemoteRequest.Extensions;
using Newtonsoft.Json.Linq;
using SafeCampus.Application.Manager.DeepelephManager;
using SafeCampus.Application.Services.Business.PersonFacesService;
using SafeCampus.Application.Services.Business.PersonInfoService;
using SafeCampus.Web.Core.Controllers.Application.Business.Dto.Person;

namespace SafeCampus.Web.Core.Controllers.Application.Business;
/// <summary>
/// 人员管理接口
/// </summary>
[Route("/business/[controller]")]
[ApiDescriptionSettings(ApiGroupConsts.SYSTEM_Business, Order = 98,Tag = "人员管理")]
public class PersonApi : IDynamicApiController
{
    private readonly IDeepelephManager _deepelephManager;
    private readonly IPersonInfoService _personInfoService;
    private readonly IPersonFacesService _personFacesService;

    public PersonApi(IDeepelephManager deepelephManager, IPersonInfoService personInfoService, IPersonFacesService personFacesService)
    {
        _deepelephManager = deepelephManager;
        _personInfoService = personInfoService;
        _personFacesService = personFacesService;
    }
    /// <summary>
    /// 新增人员
    /// </summary>
    /// <param name="info">人员信息</param>
    /// <returns></returns>
    public async Task<dynamic> CreatePersonA(PersonModel info)
    {
        info.Faces = info.Faces.Select(x => new Faces {faceId = Guid.NewGuid().ToString("N"),faceUrl = x.faceUrl}).ToList();
        var personId = Guid.NewGuid().ToString("N");
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/create"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personId = personId,
                age = info.Age,
                name = info.Name,
                gender = info.Gender,
                phone = info.Phone,
                exData = info.ExData,
                faces = info.Faces
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            var person = new PersonInfoDto
            {
                PersonId = personId,
                Age = info.Age,
                Name = info.Name,
                Gender = info.Gender,
                Phone = info.Phone,
                CreateTime = DateTime.Now,
                ExtData = info.ExData,
                FaceSizeLimit = 60,
                QualityScore = 30,
            };
            if (!string.IsNullOrEmpty(info.PersonSetId))
            {
                await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/bind"
                    .SetBody(new
                    {
                        token = _deepelephManager.GetToken(),
                        tenantCode = appSettings.TenantCode,
                        poiId = appSettings.PoiId,
                        personSetId = info.PersonSetId,
                        personIds = new List<string> { model["data"].ToString() }
                    })
                    .SetContentType("application/json")
                    .PostAsAsync<string>();
                person.PersonSetId=info.PersonSetId;
            }
            await _personInfoService.Add(person);
            await _personFacesService.BatchAdd(info.Faces.Select(x => new PersonFaces
            {
                FaceId = x.faceId,
                FaceUrl = x.faceUrl,
                PersonId = personId
            }).ToList());
            return model["data"];
        }
        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 人脸图片上传
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<dynamic> UploadFile([FromForm] BaseFileInput input)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var jsonparam = JsonConvert.SerializeObject(new
        {
            token = _deepelephManager.GetToken(),
            tenantCode = appSettings.TenantCode,
            poiId = appSettings.PoiId,
            usageScenario = "personSet"
        });
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/common/upload-file"
            .SetFiles(HttpFile.Create("file", input.File.OpenReadStream(), input.File.FileName))
            .SetBody(new
            {
                param = jsonparam
            })
            .SetContentType("multipart/form-data")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            var strCheck = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/faceQuality/check"
                .SetBody(new
                {
                    token = _deepelephManager.GetToken(),
                    tenantCode = appSettings.TenantCode,
                    poiId = appSettings.PoiId,
                    faceSizeLimit = 60,
                    qualityScore = 30,
                    faceUrl = model["data"]["httpUrl"].ToString()
                })
                .SetContentType("application/json")
                .PostAsAsync<string>();
            var modelCheck = JsonConvert.DeserializeObject<JObject>(strCheck);
            if ((bool)modelCheck["success"])
            {
                if ((bool)modelCheck["data"]["pass"])
                {
                    return model["data"]["httpUrl"].ToString();
                }
                throw Oops.Oh(modelCheck["data"]["message"].ToString());
            }
            else
            {
                throw Oops.Oh("人脸效验失败!");
            }
        }
        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 删除人员
    /// </summary>
    /// <param name="personId"></param>
    /// <returns></returns>
    public async Task<dynamic> DeletePersonD(string id)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/delete"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personId = id,

            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            var isOk = model["data"].ToString() == id;
            if (isOk)
            {
                await _personInfoService.Delete(id);
            }
            return isOk;
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 更新人员信息
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    public async Task<dynamic> UpdatePersionU(PersonModel info)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/createOrOverride"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personId = info.PersonId,
                age = info.Age,
                name = info.Name,
                gender = info.Gender,
                phone = info.Phone,
                exData = info.ExData,
                faces = info.Faces
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            var person = new PersonInfoDto
            {
                PersonId = info.PersonId,
                Age = info.Age,
                Name = info.Name,
                Gender = info.Gender,
                Phone = info.Phone,
                CreateTime = DateTime.Now,
                ExtData = info.ExData,
                FaceSizeLimit = 60,
                QualityScore = 30,
            };
            if (!string.IsNullOrEmpty(info.PersonSetId))
            {
                person.PersonSetId = info.PersonSetId;
                var perInfo = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/query"
                    .SetBody(new
                    {
                        token = _deepelephManager.GetToken(),
                        tenantCode = appSettings.TenantCode,
                        poiId = appSettings.PoiId,
                        personId = info.PersonId,
                    })
                    .SetContentType("application/json")
                    .PostAsAsync<string>();
                var permodel = JsonConvert.DeserializeObject<JObject>(perInfo);
                if ((bool)permodel["success"])
                {
                    if (permodel["data"]["personSets"].Count() > 0)
                    {
                        var old = permodel["data"]["personSets"][0]["personSetId"].ToString();
                        if (old != info.PersonSetId)
                        {
                            //解绑旧班级
                            await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/unbind"
                                .SetBody(new
                                {
                                    token = _deepelephManager.GetToken(),
                                    tenantCode = appSettings.TenantCode,
                                    poiId = appSettings.PoiId,
                                    personId = info.PersonId,
                                    personSetId = old,
                                })
                                .SetContentType("application/json")
                                .PostAsAsync<string>();
                            //绑定新班级
                            await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/bind"
                                .SetBody(new
                                {
                                    token = _deepelephManager.GetToken(),
                                    tenantCode = appSettings.TenantCode,
                                    poiId = appSettings.PoiId,
                                    personSetId = info.PersonSetId,
                                    personIds = new List<string> { info.PersonId }
                                })
                                .SetContentType("application/json")
                                .PostAsAsync<string>();
                        }
                    }
                    else
                    {
                        //绑定新班级
                        await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/bind"
                            .SetBody(new
                            {
                                token = _deepelephManager.GetToken(),
                                tenantCode = appSettings.TenantCode,
                                poiId = appSettings.PoiId,
                                personSetId = info.PersonSetId,
                                personIds = new List<string> { model["data"].ToString() }
                            })
                            .SetContentType("application/json")
                            .PostAsAsync<string>();
                    }
                }
            }

            await _personInfoService.Update(person);
            await _personFacesService.BatchAdd(info.Faces.Select(x => new PersonFaces
            {
                FaceId = x.faceId,
                FaceUrl = x.faceUrl,
                PersonId = info.PersonId
            }).ToList());
            return model["data"];
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 分页查询人员信息
    /// </summary>
    /// <param name="search">查询条件</param>
    /// <returns></returns>
    public async Task<dynamic> PageQuery(PersonInfoSearch search)
    {
        return await _personInfoService.GetPageList(search);
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/pageQuery"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personSetId = search.PersonSetId,
                //personId = search.PersonId,
                personName = search.PersonName,
                pageIndex = search.PageNum,
                pageSize = search.PageSize,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if (!(bool)model["success"]) throw Oops.Oh(model["message"].ToString());
        if (model["data"] != null)
        {
            return new
            {
                pageNum = search.PageNum,
                pageSize = model["pageSize"],
                total = model["totalCount"],
                pages = model["pageIndex"],
                list = model["data"]
            };
        }
        return new
        {
            pageNum = search.PageNum,
            pageSize = 0,
            total = 0,
            pages = 0,
            list = new List<string>()
        };
    }
    /// <summary>
    /// 查看人员详情
    /// </summary>
    /// <param name="personId">人员id</param>
    /// <returns></returns>
    public async Task<dynamic> GetPersionById(ControllersIdInput input)
    {
        return await _personInfoService.GetInfo(input.Id);
        var appSettings = App.GetOptionsMonitor < AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/query"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personId = input.Id,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            if (model["data"]["personSets"].Count() > 0)
            {
                model["data"]["personSetId"] = model["data"]["personSets"][0]["personSetId"];
                model["data"]["personSetName"] = model["data"]["personSets"][0]["personSetName"];
            }
            else
            {
                model["data"]["personSetId"] = null;
                model["data"]["personSetName"] = null;
            }
            return model["data"];
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 添加人脸
    /// </summary>
    /// <param name="info">人脸信息</param>
    /// <returns></returns>
    public async Task<dynamic> AddFaceA(PersonFaceInfo info)
    {
       
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/addFace"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personId = info.PersonId,
                info.faceSizeLimit,
                info.qualityScore,
                faces = new List<Faces>
                {
                   new Faces
                   {
                       faceUrl = info.faceUrl,
                       faceId=Guid.NewGuid().ToString("N"),
                   }
                }
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            var faceModel = new PersonFaces { PersonId = info.PersonId, FaceId = Guid.NewGuid().ToString("N"), FaceUrl = info.faceUrl };
            await _personFacesService.Add(faceModel);
            return true;
        }
        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    ///  删除人脸
    /// </summary>
    /// <param name="info">删除信息</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<dynamic> DeleteFaceD(PersonFaceDel info)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/removeFace"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                info.personId,
                info.faceIds
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            await _personFacesService.Delete(info.personId, info.faceIds);
            return true;
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 人员和底库绑定
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    public async Task<dynamic> PersonBindDfie(PersonDfieDfie info)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/bind"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personSetId = info.PersonSetId,
                personIds = info.PersonIds
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            await _personInfoService.UpdateSet(info.PersonIds, info.PersonSetId);
            return true;
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 人员与底库解绑
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> PersonUnBindDfie(PersonUnBindDfieInput input)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/unbind"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personId = input.PersonId,
                personSetId = input.PersonSetId,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            await _personInfoService.UpdateSet(new List<string>{ input.PersonId}, null);
            return true;
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 人员数据同步
    /// </summary>
    /// <returns></returns>
    public async Task<bool> SyncData()
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/pageQuery"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                pageIndex =1,
                pageSize = 1000,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if (!(bool)model["success"]) throw Oops.Oh(model["message"].ToString());
        if (model["data"] != null)
        {
            foreach (var item in model["data"])
            {
                var personModel = new PersonInfoDto
                {
                    PersonId = item["personId"]?.ToString(),
                    Age = (int)item["age"],
                    Name = item["name"]?.ToString(),
                    Gender = item["gender"]?.ToString(),
                    Phone = item["phone"]?.ToString(),
                    CreateTime = DateTime.Now,
                    ExtData = item["extData"]?.ToString(),
                    FaceSizeLimit = 60,
                    QualityScore = 30,
                    PersonSetId = item["personSets"]?[0]?["personSetId"]?.ToString()
                };
                if (item["faces"]?.Count()>0)
                {
                    var list = new List<PersonFaces>();
                    foreach (var faceItem in item["faces"])
                    {
                        var face = new PersonFaces
                        {
                            FaceId = faceItem["faceId"]?.ToString(),
                            FaceUrl = faceItem["faceUrl"]?.ToString(),
                            PersonId = item["personId"]?.ToString(),
                            Tag = faceItem["tag"]?.ToString(),
                        };
                        var signImg = Path.Combine(Directory.GetCurrentDirectory(), "Files", App.Configuration["AppInfo:PersonImg"], face.FaceId + ".jpg");
                        await face.FaceUrl.GetToSaveAsync(signImg);
                        face.FaceUrl = $"/Files/{App.Configuration["AppInfo:PersonImg"]}/{face.FaceId}.jpg";
                        list.Add(face);
                    }
                    await _personFacesService.BatchAdd(list);
                }
                var oldmodel = await _personInfoService.GetInfo(personModel.PersonId);
                if (oldmodel==null)
                {
                    await _personInfoService.Add(personModel);
                }
            }
        }
        return true;
    }
}