using Hotline.Caching.Interfaces;
using Hotline.JudicialManagement;
using Hotline.Settings;
using SqlSugar;
using XF.Domain.Constants;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.JudicialManagement
{
    public class EnforcementApplication : IEnforcementApplication, IScopeDependency
    {
        private readonly IRepository<EnforcementOrderHander> _enforcementOrderHanderRepository;
        private readonly IRepository<EnforcementOrders> _enforcementOrdersRepository;
        private readonly IRepository<EnforcementHotspot> _enforcementHotspotRepository;
        private readonly ISystemDicDataCacheManager _sysDicDataCacheManager;
        private readonly ISystemSettingCacheManager _systemSettingCacheManager;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="enforcementOrderHanderRepository"></param>
        /// <param name="enforcementOrdersRepository"></param>
        /// <param name="enforcementHotspotRepository"></param>
        /// <param name="sysDicDataCacheManager"></param>
        /// <param name="systemSettingCacheManager"></param>
        public EnforcementApplication(IRepository<EnforcementOrderHander> enforcementOrderHanderRepository,
           IRepository<EnforcementOrders> enforcementOrdersRepository,
          IRepository<EnforcementHotspot> enforcementHotspotRepository,
        ISystemDicDataCacheManager sysDicDataCacheManager,
       ISystemSettingCacheManager systemSettingCacheManager)
        {
            _enforcementOrderHanderRepository = enforcementOrderHanderRepository;
            _enforcementOrdersRepository = enforcementOrdersRepository;
            _enforcementHotspotRepository = enforcementHotspotRepository;
            _sysDicDataCacheManager = sysDicDataCacheManager;
            _systemSettingCacheManager = systemSettingCacheManager;
        }

        /// <summary>
        /// 司法行政监督管理-工单写入
        /// </summary>
        /// <param name="order"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task AddEnforcementOrderAsync(Hotline.Orders.Order order, CancellationToken cancellationToken)
        {
            //排除咨询件
            if (order.AcceptTypeCode == "10")
                return;

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

            bool isAdd = false;
            //如果是行政执法类工单，写入数据
            if (order.IsEnforcementOrder.HasValue && order.IsEnforcementOrder.Value)
                isAdd = true;

            //如果是特定热点写入数据
            if (await _enforcementHotspotRepository.AnyAsync(p => p.Id == order.HotspotId, cancellationToken))
                isAdd = true;

            //如果是特定部门办理写入数据
            var JudicialManagementOrg = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.JudicialManagementOrg).Where(p => p.DicDataValue.Trim() == order.OrgLevelOneCode);

            if (JudicialManagementOrg != null && JudicialManagementOrg.Any())
                isAdd = true;

            //需要添加
            if (isAdd)
            {
                var orderData = await _enforcementOrdersRepository.GetAsync(p => p.Id == order.Id, cancellationToken);
                if (orderData == null)
                {
                    EnforcementOrders enforcementOrders = new EnforcementOrders()
                    {
                        Id = order.Id,
                        OrderNo = order.No,
                        IsEnforcementOrder = order.IsEnforcementOrder.HasValue ? order.IsEnforcementOrder.Value : false,
                        IsTheClueTrue = null,
                        IsPassTheBuckOrder = false
                    };

                    await _enforcementOrdersRepository.AddAsync(enforcementOrders, cancellationToken);
                }
                else
                {
                    //是否需要更新数据
                }
            }

        }

        /// <summary>
        /// 判断处理推诿工单
        /// </summary>
        /// <param name="order"></param>
        /// <param name="orgCode"></param>
        /// <param name="orgName"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task AddPassTheBuckOrderAsync(Hotline.Orders.Order order, string orgCode, string orgName, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(orgCode) || string.IsNullOrEmpty(orgName))
                return;

            //排除咨询件
            if (order.AcceptTypeCode == "10")
                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 _enforcementOrdersRepository.GetAsync(p => p.Id == order.Id, cancellationToken);
                    if (orderData == null)
                    {
                        //没有工单数据，直接写入
                        EnforcementOrders enforcementOrders = new()
                        {
                            Id = order.Id,
                            OrderNo = order.No,
                            IsEnforcementOrder = order.IsEnforcementOrder.HasValue ? order.IsEnforcementOrder.Value : false,
                            IsTheClueTrue = null,
                            IsPassTheBuckOrder = true
                        };
                        await _enforcementOrdersRepository.AddAsync(orderData, cancellationToken);
                    }
                    else
                    {
                        //有工单数据修改为推诿
                        if (orderData.IsPassTheBuckOrder != true)
                        {
                            orderData.IsPassTheBuckOrder = true;
                            await _enforcementOrdersRepository.UpdateAsync(orderData, cancellationToken);
                        }
                    }
                }
            }

        }
    }
}
