//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2023-06-01 13:42:25 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------

using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ZiggyCreatures.Caching.Fusion;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// InternationalizationService
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Common")]
    public class InternationalizationService(IRepository<Internationalization> _internationalizationRepository,
        IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer, IFusionCache _fusionCache) : BaseService, IInternationalizationService
    {


        /// <summary>
        /// 前端国际化内容接口
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<IEnumerable<InternationalizationSimpleDto>> GetFrontInternationalizationList()
        {
            var cacheList = await _fusionCache.GetOrDefaultAsync<List<InternationalizationSimpleDto>>(CacheKeys.FrontInternational);

            //if(cacheList != null && cacheList.Count!=0)
            //{
            //    return cacheList;
            //}
            //else
            {
                var list = await _internationalizationRepository.Where(t => t.InternationalizationType == 0).Select(t => new InternationalizationSimpleDto()
                {
                    Code = t.Code,
                    Value = t.Value,
                    ValueCN = t.ValueCN,
                    FrontType = t.FrontType,
                    Description = t.Description,
                }).ToListAsync();

                await _fusionCache.SetAsync<List<InternationalizationSimpleDto>>(CacheKeys.FrontInternational, list, TimeSpan.FromDays(1));

                return list;
            }

        }

        /// <summary>
        /// 前端批量提交，后端判断不存在就添加，存在就更新
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<IResponseOutput> BatchAddOrUpdateFrontInternationalization(List<BatchInternationalizationDto> batchList)
        {
            foreach (var item in batchList)
            {
                var find = await _internationalizationRepository.FirstOrDefaultAsync(t => t.Code == item.Code && t.Description == item.Description && t.InternationalizationType == 0);

                if (find != null)
                {
                    _mapper.Map(item, find);
                }
                else
                {
                    var mapItem = _mapper.Map<Internationalization>(item);
                    mapItem.InternationalizationType = 0;

                    // 0 是预翻译  1是已确认  2是后端废弃
                    mapItem.State = 0;

                    await _internationalizationRepository.AddAsync(mapItem);
                }
            }
            await _internationalizationRepository.SaveChangesAsync();

            //清理缓存
            await _fusionCache.SetAsync<List<InternationalizationSimpleDto>>(CacheKeys.FrontInternational, new List<InternationalizationSimpleDto>(), TimeSpan.FromDays(1));

            return ResponseOutput.Ok();
        }

        [HttpPost]
        public async Task<PageOutput<InternationalizationView>> GetInternationalizationList(InternationalizationQuery inQuery)
        {

            var internationalizationQueryable = _internationalizationRepository
                .WhereIf(inQuery.Description != null, t => t.Description.Contains(inQuery.Description))
                 .WhereIf(inQuery.Module != null, t => t.Module.Contains(inQuery.Module))
                 .WhereIf(inQuery.PublishLogId != null, t => t.PublishLogId == inQuery.PublishLogId)
                .WhereIf(inQuery.Code != null, t => t.Code.Contains(inQuery.Code))
                .WhereIf(inQuery.State != null, t => t.State == inQuery.State)
                .WhereIf(inQuery.InternationalizationType != null, t => t.InternationalizationType == inQuery.InternationalizationType)
                .WhereIf(inQuery.Value != null, t => t.Value.Contains(inQuery.Value))
                .WhereIf(inQuery.ValueCN != null, t => t.ValueCN.Contains(inQuery.ValueCN))
                .ProjectTo<InternationalizationView>(_mapper.ConfigurationProvider);

            var pageList = await internationalizationQueryable
            .ToPagedListAsync(inQuery);

            return pageList;
        }

        /// <summary>
        /// 后端之前批量添加接口
        /// </summary>
        /// <param name="batchAdd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> BatchAddInternationalization(BatchAddInternationalization batchAdd)
        {
            foreach (var item in batchAdd.AddList)
            {

                var mapItem = _mapper.Map<InternationalizationAddOrEdit>(item);

                mapItem.InternationalizationType = batchAdd.InternationalizationType;
                mapItem.State = batchAdd.State;

                var verifyExp1 = new EntityVerifyExp<Internationalization>()
                {
                    VerifyExp = t => t.Code == mapItem.Code && t.InternationalizationType == mapItem.InternationalizationType,

                    VerifyMsg = $"该类型已有{item.Code}名称的国际化标识",
                    IsVerify = true
                };

                var entity = await _internationalizationRepository.InsertOrUpdateAsync(mapItem, false, verifyExp1);
            }

            await _internationalizationRepository.SaveChangesAsync();

            //清理缓存
            await _fusionCache.SetAsync<List<InternationalizationSimpleDto>>(CacheKeys.FrontInternational, new List<InternationalizationSimpleDto>(), TimeSpan.FromDays(1));

            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 前后端添加的时候，区分了，前端判断重复多了多了一个路由  路由+标识唯一
        /// </summary>
        /// <param name="addOrEditInternationalization"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> AddOrUpdateInternationalization(InternationalizationAddOrEdit addOrEditInternationalization)
        {
            var internationalizationType = addOrEditInternationalization.InternationalizationType;

            //后端验证标识重复与否
            var verifyExp1 = new EntityVerifyExp<Internationalization>()
            {
                VerifyExp = t => t.Code == addOrEditInternationalization.Code && t.InternationalizationType == addOrEditInternationalization.InternationalizationType,

                VerifyMsg = $"该类型已有{addOrEditInternationalization.Code}名称的国际化标识",
                IsVerify = true /*internationalizationType == 1*/
            };

            //前端验证标识重复与否
            //var verifyExp2 = new EntityVerifyExp<Internationalization>()
            //{
            //    VerifyExp = t => t.Code == addOrEditInternationalization.Code && t.InternationalizationType == addOrEditInternationalization.InternationalizationType && t.Description == addOrEditInternationalization.Description,

            //    VerifyMsg = $"该类型已有{addOrEditInternationalization.Description}下的{addOrEditInternationalization.Code}名称的国际化标识",
            //    IsVerify = internationalizationType == 0
            //};

            var entity = await _internationalizationRepository.InsertOrUpdateAsync(addOrEditInternationalization, true, verifyExp1/*, verifyExp2*/);

            if (addOrEditInternationalization.InternationalizationType == 1)
            {
                await InternationalizationHelper.AddOrUpdateJsonKeyValueAsync(entity.Code, addOrEditInternationalization.Value, addOrEditInternationalization.ValueCN, addOrEditInternationalization.Description);
            }
            else
            {
                //清理缓存
                await _fusionCache.SetAsync<List<InternationalizationSimpleDto>>(CacheKeys.FrontInternational, new List<InternationalizationSimpleDto>(), TimeSpan.FromDays(1));
            }
            return ResponseOutput.Ok(entity.Id.ToString());

        }


        [HttpDelete("{internationalizationId:guid}")]
        public async Task<IResponseOutput> DeleteInternationalization(Guid internationalizationId)
        {
            var success = await _internationalizationRepository.DeleteFromQueryAsync(t => t.Id == internationalizationId, true);

            //清理缓存
            await _fusionCache.SetAsync<List<InternationalizationSimpleDto>>(CacheKeys.FrontInternational, new List<InternationalizationSimpleDto>(), TimeSpan.FromDays(1));
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 批量更新状态和发布版本
        /// </summary>
        /// <param name="inCommand"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IResponseOutput> BatchUpdateInternationalInfo(BatchUpdateInfoCommand inCommand)
        {
            await _internationalizationRepository.BatchUpdateNoTrackingAsync(t => inCommand.IdList.Contains(t.Id), t => new Internationalization() { State = inCommand.State, PublishLogId = inCommand.PublishLogId });

            return ResponseOutput.Ok();
        }


    }
}
