using NPOI.POIFS.Properties;
using NPOI.SS.Formula.Functions;
using Shentun.Peis.ContactMethods;
using Shentun.Peis.ContactPersons;
using Shentun.Peis.CustomerOrgGroups;
using Shentun.Peis.CustomerOrgRegisters;
using Shentun.Peis.HelperDto;
using Shentun.Peis.Models;
using Shentun.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using TencentCloud.Ams.V20200608.Models;
using TencentCloud.Sqlserver.V20180328.Models;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
namespace Shentun.Peis.CustomerOrgs
{
    /// 
    /// 团检单位设置
    /// 
    public class CustomerOrgManager : DomainService
    {
        private readonly IRepository _repository;
        private readonly IRepository _patientRegisterRepository;
        private readonly IRepository _customerOrgRegisterRepository;
        private readonly IRepository _customerOrgGroupRepository;
        private readonly IRepository _contactPersonRepository;
        private readonly CustomerOrgRegisterManager _customerOrgRegisterManager;
        private readonly CustomerOrgGroupManager _customerOrgGroupManager;
        private readonly ContactPersonManager _contactPersonManager;
        public CustomerOrgManager(
            IRepository repository,
            IRepository patientRegisterRepository,
            IRepository customerOrgRegisterRepository,
            IRepository customerOrgGroupRepository,
            IRepository contactPersonRepository,
            CustomerOrgRegisterManager customerOrgRegisterManager,
            CustomerOrgGroupManager customerOrgGroupManager,
            ContactPersonManager contactPersonManager
            )
        {
            _repository = repository;
            this._patientRegisterRepository = patientRegisterRepository;
            this._customerOrgRegisterRepository = customerOrgRegisterRepository;
            this._customerOrgGroupRepository = customerOrgGroupRepository;
            this._contactPersonRepository = contactPersonRepository;
            this._customerOrgRegisterManager = customerOrgRegisterManager;
            this._customerOrgGroupManager = customerOrgGroupManager;
            this._contactPersonManager = contactPersonManager;
        }
        /// 
        /// 创建
        /// 
        /// 
        /// 
        public async Task CreateAsync(
          CustomerOrg entity
         )
        {
            DataHelper.CheckStringIsNull(entity.DisplayName, "名称");
            //await EntityHelper.CheckSameName(_repository, entity.DisplayName);
            #region 验证同名
            if (await _repository.FirstOrDefaultAsync(m => m.DisplayName == entity.DisplayName && m.ParentId == entity.ParentId) != null)
            {
                if (entity.ParentId == null)
                {
                    throw new UserFriendlyException("单位:" + entity.DisplayName + "已存在");
                }
                else
                {
                    throw new UserFriendlyException("同级目录下已存在:" + entity.DisplayName + "部门");
                }
            } 
            #endregion
            return new CustomerOrg
            {
                DisplayName = entity.DisplayName,
                SimpleCode = LanguageConverter.GetPYSimpleCode(entity.DisplayName),
                DisplayOrder = await EntityHelper.CreateMaxDisplayOrder(_repository),
                Accounts = entity.Accounts,
                Address = entity.Address,
                Bank = entity.Bank,
                Fax = entity.Fax,
                InvoiceName = entity.InvoiceName,
                IsLock = entity.IsLock,
                OrganizationUnitId = entity.OrganizationUnitId,
                OrgTypeId = entity.OrgTypeId,
                ParentId = entity.ParentId,
                PathCode = await CreatePathCode(entity.ParentId),
                PostalCode = entity.PostalCode,
                Remark = entity.Remark,
                ShortName = entity.ShortName,
                IsActive = entity.IsActive,
                Telephone = entity.Telephone
            };
        }
        /// 
        /// 更新
        /// 
        /// 
        /// 
        /// 
        public async Task UpdateAsync(
           CustomerOrg sourceEntity,
           CustomerOrg targetEntity
          )
        {
            DataHelper.CheckStringIsNull(sourceEntity.DisplayName, "名称");
            if (sourceEntity.DisplayName != targetEntity.DisplayName)
            {
                if (await _repository.FirstOrDefaultAsync(m => m.DisplayName == sourceEntity.DisplayName && m.ParentId == sourceEntity.ParentId) != null)
                {
                    if (sourceEntity.ParentId == null)
                    {
                        throw new UserFriendlyException("单位:" + sourceEntity.DisplayName + "已存在");
                    }
                    else
                    {
                        throw new UserFriendlyException("同级目录下已存在:" + sourceEntity.DisplayName + "部门");
                    }
                }
                targetEntity.DisplayName = sourceEntity.DisplayName;
                targetEntity.SimpleCode = LanguageConverter.GetPYSimpleCode(targetEntity.DisplayName);
            }
            targetEntity.Accounts = sourceEntity.Accounts;
            targetEntity.Address = sourceEntity.Address;
            targetEntity.Bank = sourceEntity.Bank;
            targetEntity.Fax = sourceEntity.Fax;
            targetEntity.InvoiceName = sourceEntity.InvoiceName;
            targetEntity.IsLock = sourceEntity.IsLock;
            targetEntity.OrganizationUnitId = sourceEntity.OrganizationUnitId;
            targetEntity.OrgTypeId = sourceEntity.OrgTypeId;
            //targetEntity.ParentId = targetEntity.ParentId;
            //targetEntity.PathCode = targetEntity.PathCode;
            targetEntity.PostalCode = sourceEntity.PostalCode;
            targetEntity.Remark = sourceEntity.Remark;
            targetEntity.ShortName = sourceEntity.ShortName;
            targetEntity.IsActive = sourceEntity.IsActive;
            targetEntity.Telephone = sourceEntity.Telephone;
        }
        /// 
        /// 修改排序  相邻之间
        /// 
        /// 需要修改的ID
        /// 目标ID
        public async Task UpdateSortAsync(Guid id, Guid targetid)
        {
            await EntityHelper.UpdateSort(_repository, id, targetid);
        }
        /// 
        /// 修改排序  置顶,置底
        /// 
        /// 需要修改的ID
        /// 修改方式:1 置顶   2 置底
        /// 
        public async Task UpdateManySortAsync(Guid id, int SortType)
        {
            await EntityHelper.UpdateManySortAsync(_repository, id, SortType);
        }
        /// 
        /// 修改排序  拖拽
        /// 
        /// 
        /// 
        /// 
        /// 
        public async Task UpdateSortManyAsync(UpdateSortManyDto input)
        {
            await EntityHelper.UpdateSortManyAsync(_repository, input);
        }
        /// 
        /// 自动生成pathcode
        /// 
        /// 
        /// 
        private async Task CreatePathCode(Guid? parentId)
        {
            string PathCode = "00001";
            //一级
            if (parentId == null || parentId == Guid.Empty)
            {
                //最大pathcode
                var LastPathCode = (await _repository.GetListAsync(o => o.ParentId == Guid.Empty || o.ParentId == null))
                        .OrderByDescending(o => o.CreationTime).FirstOrDefault();
                if (LastPathCode != null)
                {
                    PathCode = (Convert.ToInt32(LastPathCode.PathCode) + 1).ToString().PadLeft(5, '0');
                }
                else
                {
                    PathCode = "00001";
                }
            }
            else
            {
                //二级以及以上
                //上级pathcode
                var ParentPathCode = (await _repository.GetListAsync(o => o.Id == parentId)).FirstOrDefault().PathCode;
                //最大pathcode
                var LastPathCode = (await _repository.GetListAsync(o => o.ParentId == parentId))
                     .OrderByDescending(o => o.CreationTime).Select(s => s.PathCode).FirstOrDefault();
                if (!string.IsNullOrEmpty(LastPathCode))
                {
                    var MaxCode = LastPathCode.Split('.').Last();
                    PathCode = ParentPathCode + "." + (Convert.ToInt32(MaxCode) + 1).ToString().PadLeft(5, '0');
                }
                else
                {
                    PathCode = ParentPathCode + ".00001";
                }
            }
            return PathCode;
        }
        /// 
        /// 获取包含子级的ID
        /// 
        /// 
        /// 
        public async Task> GetCustomerOrgChildrenId(Guid CustomerOrgId)
        {
            var customerOrgEntList = await _repository.GetListAsync();
            List CustomerOrgIds = new List();
            GetChildren(customerOrgEntList, CustomerOrgId, CustomerOrgIds);
            return CustomerOrgIds;
        }
        private void GetChildren(List customerOrgEntList, Guid CustomerOrgId, List CustomerOrgIds)
        {
            CustomerOrgIds.Add(CustomerOrgId);
            var entlist = customerOrgEntList.Where(m => m.ParentId == CustomerOrgId).ToList();
            if (entlist.Count > 0)
            {
                foreach (var ent in entlist)
                {
                    GetChildren(customerOrgEntList, ent.Id, CustomerOrgIds);
                }
            }
        }
        /// 
        /// 检查是否有子节点数据
        /// 
        /// 返回字节点数量
        public async Task CheckIsChildren(Guid id)
        {
            var childrenCount = await _repository.CountAsync(m => m.ParentId == id);
            return childrenCount;
        }
        /// 
        /// 1.删除单位时候,判断是否已有人员登记(patient_register),已有的禁止删除。
        /// 2.删除单位的时候,删除单位体检次数。
        /// 
        /// 
        /// 
        /// 
        public async Task CheckAndDeleteAsync(Guid id)
        {
            var customerOrgEnt = await _repository.FirstOrDefaultAsync(m => m.Id == id);
            if (customerOrgEnt != null)
            {
                var patientRegisterEnt = await _patientRegisterRepository.FirstOrDefaultAsync(m => m.CustomerOrgId == id);
                if (patientRegisterEnt != null)
                {
                    throw new UserFriendlyException($"单位\"{customerOrgEnt.DisplayName}\"已被体检人员\"{patientRegisterEnt.PatientName}\"登记使用,不能删除");
                }
                var contactPersonList = await _contactPersonRepository.GetListAsync(m => m.CustomerOrgId == id);
                if (contactPersonList.Any())
                {
                    throw new UserFriendlyException($"单位\"{customerOrgEnt.DisplayName}\"下存在联系人\"{contactPersonList[0].DisplayName}\",不能删除");
                }
                //删除逻辑  
                //单位下的单位体检次数
                var customerOrgRegisters = await _customerOrgRegisterRepository.GetListAsync(m => m.CustomerOrgId == id);
                if (customerOrgRegisters.Any())
                {
                    //删除单位体检次数
                    foreach (var customerOrgRegister in customerOrgRegisters)
                    {
                        await _customerOrgRegisterManager.CheckAndDeleteAsync(customerOrgRegister.Id);
                    }
                }
                await _repository.DeleteAsync(id);
            }
            else
            {
                throw new UserFriendlyException("数据不存在");
            }
        }
    }
}