using AngleSharp.Dom;
using Fw.Utility.UnifyResponse;
using Hotline.Api.Filter;
using Hotline.Application.Snapshot.Contracts;
using Hotline.Caching.Interfaces;
using Hotline.Caching.Services;
using Hotline.File;
using Hotline.Orders;
using Hotline.Repository.SqlSugar.Snapshot;
using Hotline.Settings;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Article;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.Settings;
using Hotline.Share.Dtos.Snapshot;
using Hotline.Share.Dtos.WebPortal;
using Hotline.Share.Enums.Order;
using Hotline.Share.Enums.Snapshot;
using Hotline.Share.Tools;
using Hotline.Snapshot;
using Hotline.Snapshot.IRepository;
using Hotline.ThirdAccountDomainServices.Interfaces;
using Hotline.Tools;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SharpCompress.Compressors.Xz;
using SqlSugar;
using SqlSugar.Extensions;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using XF.Domain.Authentications;
using XF.Domain.Exceptions;
using XF.Domain.Filters;
using XF.Domain.Repository;
using BulletinOutDto = Hotline.Share.Dtos.Article.BulletinOutDto;

namespace Hotline.Api.Controllers.Snapshot;

/// <summary>
/// 随手拍接口
/// </summary>
public class SnapshotController : BaseController
{
    private readonly IRepository<Order> _orderRepository;
    private readonly ISnapshotApplication _snapshotApplication;
    private readonly ISystemAreaDomainService _systemAreaDomainService;
    private readonly IIndustryRepository _industryRepository;
    private readonly IOrderDomainService _orderDomainService;
    private readonly IFileRepository _fileRepository;
    private readonly IOrderSnapshotRepository _orderSnapshotRepository;
    private readonly ISystemDicDataCacheManager _systemDicDataCacheManager;
    private readonly ISessionContext _sessionContext;
    private readonly IThirdAccountRepository _thirdAccountRepository;
    private readonly ILogger<SnapshotController> _logger;
    private readonly IRepository<SystemWebPageSetting> _webPageRepository;
    private readonly ISystemSettingCacheManager _systemSettingCacheManager;

    public SnapshotController(IRepository<Order> orderRepository, ISnapshotApplication snapshotApplication, ISystemAreaDomainService systemAreaDomainService, IIndustryRepository industryRepository, IOrderDomainService orderDomainService, IFileRepository fileRepository, IOrderSnapshotRepository orderSnapshotRepository, ISystemDicDataCacheManager systemDicDataCacheManager, ISessionContext sessionContext, IThirdAccountRepository thirdAccountRepository, ILogger<SnapshotController> logger, IRepository<SystemWebPageSetting> webPageRepository, ISystemSettingCacheManager systemSettingCacheManager)
    {
        _orderRepository = orderRepository;
        _snapshotApplication = snapshotApplication;
        _systemAreaDomainService = systemAreaDomainService;
        _industryRepository = industryRepository;
        _orderDomainService = orderDomainService;
        _fileRepository = fileRepository;
        _orderSnapshotRepository = orderSnapshotRepository;
        _systemDicDataCacheManager = systemDicDataCacheManager;
        _sessionContext = sessionContext;
        _thirdAccountRepository = thirdAccountRepository;
        _logger = logger;
        _webPageRepository = webPageRepository;
        _systemSettingCacheManager = systemSettingCacheManager;
    }

    /// <summary>
    /// 首页数据
    /// </summary>
    /// <returns></returns>
    [HttpGet("home")]
    [AllowAnonymous]
    public async Task<HomePageOutDto> GetHomePageAsync()
        => await _snapshotApplication.GetHomePageAsync();

    /// <summary>
    /// 获取页面设置
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("page/setting")]
    [AllowAnonymous]
    public async Task<IList<SystemWebPageSetting>> GetSystemWebPageAsync([FromQuery] SystemWebPageInDto dto)
        => await _webPageRepository.Queryable().Where(m => m.Name == dto.Name && m.PageType == dto.PageType).ToListAsync(HttpContext.RequestAborted);

    /// <summary>
    /// 行业界面基础信息
    /// </summary>
    /// <param name="id">行业Id</param>
    /// <returns></returns>
    [HttpGet("industry/base/{id}")]
    [AllowAnonymous]
    public async Task<IndustryBaseOutDto> GetIndustryBaseAsync(string id)
        => await _snapshotApplication.GetIndustryBaseAsync(id, HttpContext.RequestAborted);

    /// <summary>
    /// 添加随手拍工单
    /// </summary>
    /// <returns></returns>
    [HttpPost("order")]
    [LogFilterAlpha("添加随手拍工单")]
    public async Task<AddSnapshotOrderOutDto> AddOrderAsync([FromBody] AddSnapshotOrderInDto dto)
    {
        var minute = _systemSettingCacheManager.SnapshotIntervalMinutes;
        var timeout = await _orderRepository.Queryable().Where(m => m.CreatorId == _sessionContext.UserId
                        && DateTime.Now.AddMinutes(-minute) < m.CreationTime)
            .AnyAsync();
        if (timeout) throw UserFriendlyException.SameMessage($"请{minute}分钟后再提交工单");
        var ssp = _systemDicDataCacheManager.SourceChannel.FirstOrDefault(m => m.DicDataName == "随手拍")
            ?? throw UserFriendlyException.SameMessage("请添加[随手拍]来源.");
        var order = dto.Adapt<Order>();
        dto.ValidateObject();
        var industry = await _industryRepository.GetAsync(dto.IndustryId, HttpContext.RequestAborted)
            ?? throw UserFriendlyException.SameMessage("行业不存在:" + dto.IndustryId);
        order.AcceptTypeCode = industry.AcceptTypeCode;
        order.AcceptType = industry.AcceptType;
        order.FromGender = EGender.Unknown;
        order.Title = dto.GetTitle(industry.IndustryType, industry.TitleSuffix);
        order.Content = dto.GetContent(industry.IndustryType, _systemDicDataCacheManager.JobType);
        order.FromPhone = _sessionContext.Phone;
        order.Contact = _sessionContext.Phone;
        order.SourceChannel = ssp.DicDataName;
        order.SourceChannelCode = ssp.DicDataValue;
        order.FullAddress = dto.Address + dto.FullAddress;
        order.InitId();
        await _orderDomainService.AddAsync(order);
        if (dto.Files.NotNullOrEmpty())
        {
            order.FileJson = await _fileRepository.AddFileAsync(dto.Files, order.Id, HttpContext.RequestAborted);
            await _orderRepository.UpdateAsync(order);
        }
        var orderSnapshot = dto.Adapt<OrderSnapshot>();
        orderSnapshot.Id = order.Id;
        orderSnapshot.IndustryId = dto.IndustryId;
        orderSnapshot.IndustryName = industry.Name;
        orderSnapshot.CompanyName = dto.CompanyName;
        try
        {
            orderSnapshot.JobTypeName = _systemDicDataCacheManager.JobType.FirstOrDefault(m => m.DicDataValue == dto.JobType.ToString())?.DicDataName;
        }
        catch (Exception e)
        {
            _logger.LogError(e, $"添加随手拍工单, 获取JobTypeName异常. '{dto.JobType}'");
        }
        if (dto.StartWorkTime.NotNullOrEmpty()) orderSnapshot.StartWorkTime = dto.StartWorkTime.ObjToDate();
        if (dto.EndWorkTime.NotNullOrEmpty()) orderSnapshot.EndWorkTime = dto.EndWorkTime.ObjToDate();
        if (dto.Name.NotNullOrEmpty())
        {
            await _thirdAccountRepository.Updateable()
               .SetColumns(m => m.UserName, dto.Name)
               .Where(m => m.Id == _sessionContext.UserId)
               .ExecuteCommandAsync(HttpContext.RequestAborted);
        }
        await _orderSnapshotRepository.AddAsync(orderSnapshot);
        return order.Adapt<AddSnapshotOrderOutDto>();
    }

    /// <summary>
    /// 获取行业集合
    /// </summary>
    /// <returns></returns>
    [HttpGet("industry")]
    [AllowAnonymous]
    public async Task<IList<IndustryOutDto>> GetIndustresAsync()
        => await _snapshotApplication.GetIndustresAsync();

    /// <summary>
    /// 获取公开的工单集合
    /// </summary>
    /// <returns></returns>
    [HttpGet("order/published")]
    [AllowAnonymous]
    public async Task<IList<OrderPublishOutDto>> GetPublishOrderAsync([FromQuery] OrderPublishInDto dto)
        => await _snapshotApplication.GetOrderPublishAsync(dto, HttpContext.RequestAborted);

    /// <summary>
    /// 获取公开的工单详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("order/published/{id}")]
    [AllowAnonymous]
    public async Task<OrderPublishDetailOutDto> GetOrderPublishDetailAsync(string id)
        => await _snapshotApplication.GetOrderPublishDetailAsync(id, HttpContext.RequestAborted);

    /// <summary>
    /// 获取小程序公告列表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("bulletions")]
    [AllowAnonymous]
    public async Task<IReadOnlyList<BulletinListOutDto>> QueryBulletinsAsync([FromQuery] BulletinInDto dto)
        => await _snapshotApplication.GetBulletinsAsync(dto, HttpContext.RequestAborted);

    /// <summary>
    /// 获取小程序首页弹窗
    /// </summary>
    /// <returns></returns>
    [HttpGet("bulletions/popup")]
    [AllowAnonymous]
    public async Task<BulletinOutDto> GetBulletionPopupAsync()
        => await _snapshotApplication.GetBulletionPopupAsync(HttpContext.RequestAborted);

    /// <summary>
    /// 公告详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("bulletions/{id}")]
    [AllowAnonymous]
    public async Task<BulletinOutDto> QueryBulletionsDetailAsync(string id)
        => await _snapshotApplication.GetBulletinsDetailAsync(id);

    /// <summary>
    /// 获取用户页面数据
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpGet("user")]
    public async Task<SnapshotUserInfoOutDto> GetUserInfo()
        => await _snapshotApplication.GetSnapshotUserInfoAsync(HttpContext.RequestAborted);

    /// <summary>
    /// 获取我提交的线索列表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("order")]
    public async Task<IList<OrderOutDto>> QueryOrderListAsync([FromQuery] OrderInDto dto)
        => await _snapshotApplication.GetSnapshotOrdersAsync(dto, HttpContext.RequestAborted);

    /// <summary>
    /// 获取我提交的线索详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("order/{id}")]
    public async Task<OrderPublishDetailOutDto> QueryOrderListAsync(string id)
        => await _snapshotApplication.GetSnapshotOrderDetailAsync(id, HttpContext.RequestAborted);

    /// <summary>
    /// 获取回访详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("order/visit/{id}")]
    public async Task<IList<OrderVisitItemsOutDto>> GetOrderVisitDetailAsync(string id)
        => await _snapshotApplication.GetOrderVisitDetailAsync(id);

    /// <summary>
    /// 统计红包金额, 每月的总金额
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("redpack")]
    public async Task<IReadOnlyList<RedPackDateOutDto>> QueryRedPackDateAsync([FromQuery] RedPackDateInDto dto)
        => await _snapshotApplication.GetRedPackDateAsync(dto, HttpContext.RequestAborted);

    /// <summary>
    /// 用户领取红包总金额
    /// </summary>
    /// <returns></returns>
    [HttpGet("redpack/received")]
    public async Task<string> GetRedPackReceivedTotalAsync()
        => await _snapshotApplication.GetRedPackReceivedTotalAsync(HttpContext.RequestAborted);

    /// <summary>
    /// 获取当月详细红包列表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("redpack/month")]
    public async Task<IList<RedPackOutDto>> QueryRedPackDateAsync([FromQuery] RedPacksInDto dto)
        => await _snapshotApplication.GetRedPacksAsync(dto, HttpContext.RequestAborted);

    /// <summary>
    /// 获取随手拍电气焊动火作业待处理工单数量
    /// TODO 条件 电气焊作业申报
    /// </summary>
    /// <returns></returns>
    [HttpGet("wait_accept_count")]
    public async Task<int> GetSnapshotWaitForAcceptCountAsync()
    { return 0; }
    //=> await _orderRepository
    //        .CountAsync(m => m.SourceChannelCode == "ZGSSP" && m.Status == Share.Enums.Order.EOrderStatus.WaitForAccept);

    /// <summary>
    /// 获取区域
    /// </summary>
    /// <returns></returns>
    [HttpGet("area/tree")]
    [AllowAnonymous]
    public async Task<List<SystemAreaOutDto>> GetAreaTreeAsync()
        => (await _systemAreaDomainService.GetAreaTree()).Adapt<List<SystemAreaOutDto>>();

    /// <summary>
    /// 批量添加从业人员
    /// </summary>
    /// <param name="dtos"></param>
    /// <returns></returns>
    [HttpPost("practitioner")]
    public async Task AddPractitionerAsync([FromBody] IList<AddBatchPractitionerInDto> dtos)
        => await _snapshotApplication.AddPractitionerAsync(dtos);

    /// <summary>
    /// 获取从业人员详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("practitioner/{id}")]
    [AllowAnonymous]
    public async Task<PractitionerDetailOutDto> GetPractitionerDetailAsync(string id)
        => await _snapshotApplication.GetPractitionerDetailAsync(id, HttpContext.RequestAborted);

    /// <summary>
    /// 获取从业人员集合(每次随机)
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("practitioner")]
    [AllowAnonymous]
    public async Task<IList<PractitionerItemOutDto>> GetPractitionerDetailAsync([FromQuery] PractitionerItemInDto dto)
        => await _snapshotApplication.GetPractitionerItemsAsync(dto, HttpContext.RequestAborted);

    /// <summary>
    /// 志愿者上报
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpPost("report")]
    [LogFilterAlpha("志愿者上报")]
    public async Task<AddVolunteerReportOutDto> AddVolunteerReportAsync([FromBody] AddVolunteerReportInDto dto)
        => await _snapshotApplication.AddVolunteerReportAsync(dto, HttpContext.RequestAborted);

    /// <summary>
    /// 志愿者上报页面基础数据
    /// </summary>
    /// <param name="id">行业Id</param>
    /// <returns></returns>
    [HttpGet("report/base")]
    public Dictionary<string, dynamic> GetReportBaseAsync()
    {
        return new Dictionary<string, dynamic>
        {
            { "jobType", _systemDicDataCacheManager.JobType },
        };
    }

    /// <summary>
    /// 用户自己保存邀请码
    /// </summary>
    /// <returns></returns>
    [HttpPut("third/invitationcode")]
    public async Task SaveInvitationCodeAsync([FromBody] SaveInvitationCodeInDto dto)
        => await _snapshotApplication.SaveInvitationCodeAsync(dto);

    /// <summary>
    /// 网格员系统补推接口;
    /// 根据工单No推送到网格员系统, 多个使用,号分隔
    /// </summary>
    /// <param name="nos">工单No集合,多个使用 ',' 号分隔</param>
    /// <returns></returns>
    [HttpPut("guider/nos")]
    public async Task PostOrderGuiderSystemAsync([FromBody] string nos)
    {
        foreach (var no in nos.Split(','))
        {
            var orderId = await _orderRepository.Queryable()
                .Where(m => m.No == no)
                .Select(m => m.Id)
                .FirstAsync() ?? throw UserFriendlyException.SameMessage("工单不存在");
            await _snapshotApplication.PostOrderGuiderSystemAsync(orderId, HttpContext.RequestAborted);
        }
    }

    /// <summary>
    /// 获取消息集合
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("notification")]
    public async Task<IList<GetNotifyOutDto>> GetNotificationAsync([FromQuery] GetNotifyInDto dto)
        => await _snapshotApplication.GetNotificationAsync(dto, HttpContext.RequestAborted);

    /// <summary>
    /// 获取消息详情
    /// </summary>
    /// <returns></returns>
    [HttpGet("notification/{id}")]
    public async Task<BulletinOutDto> GetNotificationDetailsAsync(string id)
        => await _snapshotApplication.GetNotificationDetailsAsync(id, HttpContext.RequestAborted);


    #region 积分
    /// <summary>
    /// 积分榜
    /// </summary>
    /// <returns></returns>
    [HttpGet("points/rank")]
    public async Task<PointsRankOutDto> GetPointsRankAsync()
        => await _snapshotApplication.GetPointsRankAsync();

    /// <summary>
    /// 积分详情
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("points")]
    public async Task<IList<PointItemsOutDto>> GetPointItemsAsync([FromQuery] PointItemsInDto dto)
        => await _snapshotApplication.GetPointItemsAsync(dto, HttpContext.RequestAborted);

    /// <summary>
    /// 积分总计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("points/total")]
    public async Task<int> GetPointsTotalAsync([FromQuery] PointItemsInDto dto)
        => await _snapshotApplication.GetPointsTotalAsync(dto, HttpContext.RequestAborted);
    #endregion

    #region 第三方系统
    /// <summary>
    /// 接收网格员系统回调
    /// </summary>
    /// <returns></returns>
    [HttpPost("guider/reply")]
    [LogFilter("网格员系统回调")]
    [AllowAnonymous]
    public async Task SaveGuiderSystemReplayAsync([FromBody] GuiderSystemInDto dto)
    {
        await _snapshotApplication.SaveGuiderSystemReplyAsync(dto, HttpContext.RequestAborted);
    }

    /// <summary>
    /// 电气焊申报系统申报工单查询
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpPost("order/declare")]
    [AllowAnonymous]
    public async Task<OpenResponse> GetOrderDeclareItemsAsync([FromBody] OrderDeclareItemsInDto dto)
    {
        var disposeDate = dto.JsonData.AcceptContent.DisposeDate.ObjToDate();
        var industryId = await _industryRepository.Queryable()
            .Where(m => m.IndustryType == EIndustryType.Declare)
            .Select(m => m.Id)
            .ToListAsync();
        var query = _orderSnapshotRepository.Queryable()
            .LeftJoin<Order>((snapshot, order) => order.Id == snapshot.Id)
            .Where((snapshot, order) => industryId.Contains(snapshot.IndustryId))
            .WhereIF(dto.JsonData.AcceptContent.Tyep == 2, (snapshot, order) => order.CreationTime.Date == disposeDate.Date)
            .WhereIF(dto.JsonData.AcceptContent.Tyep == 1, (snapshot, order) => order.FiledTime != null && order.FiledTime.Value.Date == disposeDate.Date)
            .Select((snapshot, order) => new OrderDeclareItemsOutDto
            {
                AreaCode = order.AreaCode,
                AreaName = order.County,
                EventType = 0,
                WorkAddress = order.Address,
                CreatedTime = order.CreationTime,
                WorkType = snapshot.JobType.Value,
                Source = 1,
                WorkTimeStart = snapshot.StartWorkTime,
                WorkTimeStop = snapshot.EndWorkTime,
                OnsiteSituateDescription = order.Content,
                Name = order.FromName,
                Phone = order.FromPhone,
                EventId = order.No,
                PlaceType = snapshot.Workplace,
                Compliance = 1,
                CheckTime = order.RealCommunicationTime,
                CheckUser = order.RealHandlerName,
                CheckDept = order.FileUserOrgName,
                CheckPhone = order.RealHandlerPhone,
                LatLon = order.Latitude.ToString() + "," + order.Longitude.ToString(),
                Title = order.Title,
                CompanyType = snapshot.CompanyName,
                OperationPlace = snapshot.WorkplaceName
            });
        var result = await query.ToListAsync();


        return OpenResponse.Ok(new List<WebPortalDeResponse<List<OrderDeclareItemsOutDto>>>()
        {
            new() { code = "1", msg = "ok", data = result }
        });
    }

    #endregion
}
