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

namespace SafeCampus.Web.Core.Controllers.Application.Business;
/// <summary>
/// 重点人员库接口
/// </summary>
[ApiDescriptionSettings(ApiGroupConsts.SYSTEM_Business, Order = 88, Tag = "重点人员库")]
[Route("/business/keyPersonnel")]
[RolePermission]
public class KeyPersonnelController
{
    private readonly IDeepelephManager _deepelephManager;

    public KeyPersonnelController(IDeepelephManager deepelephManager)
    {
        _deepelephManager = deepelephManager;
    }

    /// <summary>
    /// 新增人员
    /// </summary>
    /// <param name="info">人员信息</param>
    /// <returns></returns>
    public async Task<dynamic> CreatePersonA(PersonModel info)
    {
        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 = Guid.NewGuid().ToString("N"),
                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"])
        {
            await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/bind"
                .SetBody(new
                {
                    token = _deepelephManager.GetToken(),
                    tenantCode = appSettings.TenantCode,
                    poiId = appSettings.PoiId,
                    personSetId = SafeCampusConst.ZDRY,
                    personIds = new List<string> { model["data"].ToString() }
                })
                .SetContentType("application/json")
                .PostAsAsync<string>();
            //var model1 = JsonConvert.DeserializeObject<JObject>(str);
            //if ((bool)model1["success"])
            //{
            //    return model["data"];
            //}
            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"])
        {
            return model["data"].ToString() == id;
        }

        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"])
        {
            return model["data"];
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 分页查询人员信息
    /// </summary>
    /// <param name="search">查询条件</param>
    /// <returns></returns>
    public async Task<dynamic> PageQuery(PersonSearch 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 =SafeCampusConst.ZDRY,
                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)
    {
        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"])
        {
            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"])
        {
            return true;
        }

        throw Oops.Oh(model["message"].ToString());
    }
}