using Hotline.Caching.Interfaces;
using Hotline.DI;
using Hotline.EventBus;
using Hotline.JudicialManagement;
using Hotline.JudicialManagement.Notifies;
using Hotline.Settings;
using Hotline.Share.Dtos;
using Hotline.Share.Enums.JudicialManagement;
using MapsterMapper;
using MediatR;
using XF.Domain.Repository;

namespace Hotline.Application.JudicialManagement
{
    [Injection(AppScopes = EAppScope.YiBin)]
    public class AddPassTheBuckOrderNotifyHandler : INotificationHandler<AddPassTheBuckOrderNotify>
    {
        private readonly IRepository<EnforcementOrderHander> _enforcementOrderHanderRepository;
        private readonly ISystemDicDataCacheManager _sysDicDataCacheManager;
        private readonly ISystemSettingCacheManager _systemSettingCacheManager;
        private readonly IRepository<JudicialManagementOrders> _judicialManagementOrdersRepository;
        private readonly IRepository<EnforcementOrdersHandler> _enforcementOrdersHandlerRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="enforcementOrderHanderRepository"></param>
        /// <param name="sysDicDataCacheManager"></param>
        /// <param name="systemSettingCacheManager"></param>
        /// <param name="judicialManagementOrdersRepository"></param>
        /// <param name="enforcementOrdersHandlerRepository"></param>
        /// <param name="mapper"></param>
        public AddPassTheBuckOrderNotifyHandler(IRepository<EnforcementOrderHander> enforcementOrderHanderRepository,
           ISystemDicDataCacheManager sysDicDataCacheManager,
           ISystemSettingCacheManager systemSettingCacheManager,
           IRepository<JudicialManagementOrders> judicialManagementOrdersRepository,
           IRepository<EnforcementOrdersHandler> enforcementOrdersHandlerRepository,
           IMapper mapper)
        {
            _enforcementOrderHanderRepository = enforcementOrderHanderRepository;
            _sysDicDataCacheManager = sysDicDataCacheManager;
            _systemSettingCacheManager = systemSettingCacheManager;
            _judicialManagementOrdersRepository = judicialManagementOrdersRepository;
            _enforcementOrdersHandlerRepository = enforcementOrdersHandlerRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="notification"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task Handle(AddPassTheBuckOrderNotify notification, CancellationToken cancellationToken)
        {
            var orgCode = notification.orgCode;
            var orgName = notification.orgName;
            var order = notification.order;

            if (string.IsNullOrEmpty(orgCode) || string.IsNullOrEmpty(orgName))
                return;

            //排除咨询件
            if (order.AcceptTypeCode != "35")
                return;
            //排除非电话来源
            if (order.SourceChannelCode != "RGDH")
                return;
            //如果部门为空排除
            if (string.IsNullOrEmpty(order.OrgLevelOneName) || string.IsNullOrEmpty(order.OrgLevelOneCode))
                return;

            //如果没开启则不处理
            var isOpenJudicialManagement = _systemSettingCacheManager.GetSetting(SettingConstants.IsOpenJudicialManagement)?.SettingValue[0];
            if (isOpenJudicialManagement != "true")
                return;

            ///获取系统配置的推诿次数
            var enforcementPassTheBuckNum = _systemSettingCacheManager.GetSetting(SettingConstants.EnforcementPassTheBuckNum)?.SettingValue[0];
            int CountNum = 2;
            if (enforcementPassTheBuckNum != null)
                CountNum = int.Parse(enforcementPassTheBuckNum);

            //如果是特定部门办理写入数据
            var JudicialManagementOrg = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.JudicialManagementOrg).Where(p => p.DicDataValue == orgCode);
            if (JudicialManagementOrg != null && JudicialManagementOrg.Any())
            {
                //第一次办理，直接写入数据
                var enforcementOrder = await _enforcementOrderHanderRepository.GetAsync(p => p.OrderId == order.Id && p.ActualHandleOrgCode == orgCode, cancellationToken);
                if (enforcementOrder == null)
                {
                    enforcementOrder = new EnforcementOrderHander()
                    {
                        OrderId = order.Id,
                        ActualHandleOrgName = orgName,
                        ActualHandleOrgCode = orgCode,
                        HandleNum = 1
                    };
                    await _enforcementOrderHanderRepository.AddAsync(enforcementOrder, cancellationToken);
                }
                else
                {
                    //多次办理，修改数据
                    enforcementOrder.ActualHandleOrgName = orgName;
                    enforcementOrder.ActualHandleOrgCode = orgCode;
                    enforcementOrder.HandleNum = enforcementOrder.HandleNum + 1;
                    await _enforcementOrderHanderRepository.UpdateAsync(enforcementOrder, cancellationToken);
                }

                //达到工单推诿计算次数
                if (enforcementOrder.HandleNum >= CountNum)
                {
                    //查找工单数据
                    var orderData = await _judicialManagementOrdersRepository.GetAsync(p => p.Id == order.Id, cancellationToken);
                    if (orderData == null)
                    {
                        orderData = new JudicialManagementOrders();
                        //处理工单
                        _mapper.Map(order, orderData);
                        orderData.Id = order.Id;
                        orderData.IsEnforcementOrder = order.IsEnforcementOrder.HasValue ? order.IsEnforcementOrder.Value : false;
                        orderData.IsTheClueTrue = null;
                        orderData.IsPassTheBuckOrder = true;
                        orderData.OrderSoure = EOrderSoure.Hotline;
                        List<Kv> kvs = new()
                        {
                            new Kv { Key = order.OrgLevelOneName, Value = order.OrgLevelOneCode }
                        };
                        orderData.EnforcementOrdersHandler = kvs;
                        await _judicialManagementOrdersRepository.AddAsync(orderData, cancellationToken);

                        //处理部门
                        EnforcementOrdersHandler enforcementOrdersHandler = new()
                        {
                            OrderId = order.Id,
                            OrderNo = order.No,
                            OrderSoure = EOrderSoure.Hotline,
                            OrgCode = order.OrgLevelOneCode,
                            OrgName = order.OrgLevelOneName
                        };
                        await _enforcementOrdersHandlerRepository.AddAsync(enforcementOrdersHandler, cancellationToken);

                    }
                    else
                    {
                        //有工单数据修改为推诿
                        if (orderData.IsPassTheBuckOrder != true)
                        {
                            orderData.IsPassTheBuckOrder = true;
                            await _judicialManagementOrdersRepository.UpdateAsync(orderData, cancellationToken);
                        }
                    }
                }
            }
        }
    }
}
