using MoYu.FriendlyException;
using MoYu.RemoteRequest.Extensions;
using Newtonsoft.Json.Linq;
using SafeCampus.Application.Manager.DeepelephManager;
using SafeCampus.Application.Services.Business.ClassTeacherService;
using SafeCampus.Application.Services.Business.PersonSetInfoService;

namespace SafeCampus.Web.Core.Controllers.Application.Business;
/// <summary>
/// 人员底库管理接口
/// </summary>
[Route("/business/[controller]")]
[ApiDescriptionSettings(ApiGroupConsts.SYSTEM_Business, Order = 99,Tag = "人员底库管理")]
public class DfieldApi : IDynamicApiController
{
    private readonly IDeepelephManager _deepelephManager;
    private readonly IClassTeacherService _classTeacherService;
    private readonly IPersonSetInfoService _personSetInfoService;

    public DfieldApi(IDeepelephManager deepelephManager, IClassTeacherService classTeacherService, IPersonSetInfoService personSetInfoService)
    {
        _deepelephManager = deepelephManager;
        _classTeacherService = classTeacherService;
        _personSetInfoService = personSetInfoService;
    }
    /// <summary>
    /// 创建底库
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> CreateDfieldA(ControllersNameInput input)
    {
        var personSetId = Guid.NewGuid().ToString("N");
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/create"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personSetId,
                personSetName = input.Name,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            await _personSetInfoService.Add(new PersonSetInfoDto{PersonSetId = personSetId ,PersonSetName = input.Name,MajorId = input.MajorId});
            return model["data"];
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 查询底库列表
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> QueryAll(long? majorId,string setName)
    {
        return await _personSetInfoService.GetPageList(majorId, setName);
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/queryAll"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            var list = model["data"];
            for (int i = 0; i < list.Count(); i++)
            {
                var models = await _classTeacherService.GetInfo(list[i]["personSetId"].ToString());
                if (models!=null)
                {
                    list[i]["userId"]= models.UserId;
                    list[i]["userName"]= models.Name;
                    list[i]["id"]= models.Id;
                }
                else
                {
                    list[i]["userId"] = null;
                    list[i]["userName"] =null;
                }
            }
            return list;
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    /// 删除底库
    /// </summary>
    /// <param name="id">底库id</param>
    /// <returns></returns>
    public async Task<dynamic> DeleteDfieldD(string id)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/delete"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personSetId= 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 _personSetInfoService.Delete(id);
            }
            return isOk;
        }

        throw Oops.Oh(model["message"].ToString());
    }
    /// <summary>
    ///  更新底库
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<dynamic> UpdateDfieldU(DfieldInput input)
    {
        var appSettings = App.GetOptionsMonitor<AppInfoOptions>();
        var str = await $"{appSettings.SXAPIURL}/dfield-api/ecology/person/set/update"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
                personSetId=input.Id,
                personSetName=input.Name
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            var isOk = model["data"].ToString() == input.Id;
            if (isOk)
            {
                await _personSetInfoService.Update(new PersonSetInfoDto
                {
                    PersonSetId = input.Id,
                    PersonSetName = input.Name,
                    MajorId = input.MajorId
                });
            }
            return isOk;
        }

        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/set/queryAll"
            .SetBody(new
            {
                token = _deepelephManager.GetToken(),
                tenantCode = appSettings.TenantCode,
                poiId = appSettings.PoiId,
            })
            .SetContentType("application/json")
            .PostAsAsync<string>();
        var model = JsonConvert.DeserializeObject<JObject>(str);
        if ((bool)model["success"])
        {
            var list = model["data"];
            foreach (var item in list)
            {
                await _personSetInfoService.Add(new PersonSetInfoDto
                {
                    PersonSetId = item["personSetId"].ToString(),
                    PersonSetName = item["personSetName"].ToString(),
                });
            }
            
        }
        return true;
    }
}