using AutoMapper;
using LinqKit;
using Ropin.Inspection.Common;
using Ropin.Inspection.Common.Accessor.Interface;
using Ropin.Inspection.Model;
using Ropin.Inspection.Model.Entities;
using Ropin.Inspection.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Ropin.Inspection.Service
{
    public class TsysLicenseService : ITsysLicenseService
    {
        private readonly ITsysLicenseRepository _repository;
        private readonly ITsysLicenseTypePrivRepository _tsysLicenseTypePrivRepository;
        private readonly IMapper _mapper;
        private readonly IClaimsAccessor _claims;
        public TsysLicenseService(IClaimsAccessor claims, ITsysLicenseRepository repository, ITsysLicenseTypePrivRepository tsysLicenseTypePrivRepository, IMapper mapper)
        {
            _repository = repository;
            _tsysLicenseTypePrivRepository = tsysLicenseTypePrivRepository;
            _mapper = mapper;
            _claims = claims;
        }
        public async Task CreateOneAsync(TsysLicenseViewModel viewModel)
        {
            var content = _mapper.Map<TSYS_License>(viewModel);
            content.C_ID = Guid.NewGuid();
            content.C_Code = viewModel.C_TypeCode + Guid.NewGuid().ToString();
            content.C_CreateBy = _claims.ApiUserId;
            content.D_CreateOn = DateTime.Now;
            content.C_Status = "1";
            _repository.Create(content);
            var result = await _repository.SaveAsync();
            if (!result)
            {
                throw new Exception("创建失败");
            }
        }

        public async Task DeleteAsync(Guid id)
        {
            var content = await _repository.GetByIdAsync(id);
            if (content == null)
            {
                throw new Exception("数据库中没有此数据");
            }
            //_repository.Delete(content);
            //var result = await _repository.SaveAsync();
            content.C_LastUpdatedBy = _claims.ApiUserId;
            content.D_LastUpdatedOn = DateTime.Now;
            content.C_Status = "0";
            _repository.Update(content);
            var result = await _repository.SaveAsync();
            if (!result)
            {
                throw new Exception("删除失败");
            }
        }
        public async Task<IEnumerable<TsysLicenseViewModel>> GetAllAsync()
        {
            var pagedList = await _repository.GetAllAsync();
            var contentDtoList = _mapper.Map<IEnumerable<TsysLicenseViewModel>>(pagedList.ToList());
            return contentDtoList.ToList();
        }
        public async Task<IEnumerable<TsysLicenseViewModel>> GetAllByOrgTypeAsync()
        {
            IEnumerable<TSYS_License> pagedList;
            //if (_claims.OrgTypeCode == "PARTY_TYPE_005")
            if (_claims.LicenseTypeCode == TsysLicenseType.SYSTEM)
            {
                pagedList = await _repository.GetAllAsync();
            }
            else
            {
                pagedList = await _repository.GetByConditionAsync(a => a.C_Code.Equals(_claims.Linsence));
            }
            var contentDtoList = _mapper.Map<IEnumerable<TsysLicenseViewModel>>(pagedList.ToList());
            return contentDtoList.ToList();
        }

        public async Task<IEnumerable<TsysLicenseViewModel>> GetConditionAsync(TsysLicenseSearchModel searchModel)
        {
            var predicate = PredicateBuilder.New<TSYS_License>(true);//查询条件,推荐后台使用这种方式灵活筛选
            #region 添加条件查询
            if (!string.IsNullOrEmpty(searchModel.C_Status))
            {
                predicate = predicate.And(i => i.C_Status.Equals(searchModel.C_Status));
            }
            if (!string.IsNullOrEmpty(searchModel.C_Name))
            {
                predicate = predicate.And(i => i.C_Name.Contains(searchModel.C_Name));
            }
            #endregion
            var list = await _repository.GetPageAsync(predicate, "I_Sort", searchModel.IsPagination, searchModel.PageIndex, searchModel.PageSize);
            searchModel.TotalCount = list.Totals;
            var dtoList = _mapper.Map<List<TSYS_License>, List<TsysLicenseViewModel>>(list.Rows);
            return dtoList;
        }

        public async Task<TsysLicenseViewModel> GetByIdAsync(Guid id)
        {
            var content = await _repository.GetByIdAsync(id);
            var contentDto = _mapper.Map<TsysLicenseViewModel>(content);
            return contentDto;
        }


        public async Task UpdateAsync(Guid id, TsysLicenseUpdateModel updateModel)
        {
            var content = await _repository.GetByIdAsync(id);
            if (content == null)
            {
                throw new Exception("没有此数据");
            }
            content.C_LastUpdatedBy = _claims.ApiUserId;
            content.D_LastUpdatedOn = DateTime.Now;
            _mapper.Map(updateModel, content, typeof(TsysLicenseUpdateModel), typeof(TSYS_License));
            _repository.Update(content);
            var result = await _repository.SaveAsync();
            if (!result)
            {
                throw new Exception("更新失败");
            }
        }

        public Task<int> UpdateOneAsync(TsysLicenseViewModel viewModel, params string[] fields)
        {
            throw new NotImplementedException();
        }

        public Task<bool> IsExistAsync(Guid id)
        {
            throw new NotImplementedException();
        }

        public Task<IEnumerable<TsysLicenseViewModel>> GetByConditionAsync(Expression<Func<TsysLicenseViewModel, bool>> expression)
        {
            throw new NotImplementedException();
        }
        public async Task CreateLicenseTypeOneAsync(TSYS_LicenseType content)
        {
            var model = _repository.GetLicenseTypeByCode(content.C_Code);
            if (model!=null)
            {
                throw new Exception("编号已存在");
            }
            content.C_CreateBy = _claims.ApiUserId;
            content.D_CreateOn = DateTime.Now;
            content.C_Status = "1";
           await  _repository.CreateLicenseTypeAsync(content);
            var result = await _repository.SaveAsync();
            if (!result)
            {
                throw new Exception("创建失败");
            }
        }
        public async Task UpdateLicenseTypeAsync(string id, TSYS_LicenseType updateModel)
        {
            var content = _repository.GetLicenseTypeByCode(id);
            if (content == null)
            {
                throw new Exception("没有此数据");
            }
            content.C_Name = updateModel.C_Name;
            content.I_MaxMemberQty = updateModel.I_MaxMemberQty;
            content.I_MaxSpotQty = updateModel.I_MaxSpotQty;
            content.I_MaxFileSize = updateModel.I_MaxFileSize;
            content.I_Sort = updateModel.I_Sort;
            content.C_Remark = updateModel.C_Remark;
            content.C_LastUpdatedBy = _claims.ApiUserId;
            content.D_LastUpdatedOn = DateTime.Now;
            _repository.UpdateLicenseType(content);
            var result = await _repository.SaveAsync();
            if (!result)
            {
                throw new Exception("更新失败");
            }
        }
        public Task<IList<TsysLicenseTypeViewModel>> GetALLLicenseType()
        {
            var v =  _repository.GetALLLicenseType();
            var list = _mapper.Map<IList<TsysLicenseTypeViewModel>>(v);
            return Task.FromResult(list) ;
        }
        public Task<TsysLicenseTypePrivViewModel> GetLicensePrivByType(string typeCode)
        {
            if(null == typeCode)
                return _repository.GetLicensePrivByType(_claims.LicenseTypeCode);
            else
                return _repository.GetLicensePrivByType(typeCode);

        }
        public Task<IEnumerable<LicenseTypePrivViewModel>> GetLicensePrivsByTypeIdAsync(string typeId)
        {
            var v = _repository.GetLicensePrivsByTypeIdAsync(typeId);
            return v;
        }
        public async Task CreateLicensePrivByType(string typeCode, IEnumerable<string> privCodes)
        {
            //if (typeCode.Equals("SYSTEM"))
            if (_claims.LicenseTypeCode != "SYSTEM" && typeCode.Equals("SYSTEM"))
            {
                throw new Exception("禁止设置管理员权限");
            }
            var privs =  await _tsysLicenseTypePrivRepository.GetByConditionAsync(i=>i.C_LicenseTypeCode == typeCode);
            await _tsysLicenseTypePrivRepository.RemoveRangeAsync(privs);
            var licenseTypePrivs = new List<TSYS_LicenseTypePriv>();
            foreach (var permissionId in privCodes)
            {
                licenseTypePrivs.Add(
                    new TSYS_LicenseTypePriv
                    {
                        C_LicenseTypeCode = typeCode,
                        C_PrivilegeCode = permissionId,
                        C_CreateBy = _claims.ApiUserId,
                        D_CreateOn = DateTime.Now
                    }
                );
            }
            await _tsysLicenseTypePrivRepository.CreateRangeAsync(licenseTypePrivs);
        }
    }
}