//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2021-11-11 11:04:54 
//     对此文件的更改可能会导致不正确的行为,并且如果重新生成代码,这些更改将会丢失。
//--------------------------------------------------------------------
using IRaCIS.Core.Infrastructure;
using Microsoft.AspNetCore.Mvc;
namespace IRaCIS.Core.Application.Contracts
{
    /// 
    /// 系统QC 问题管理
    /// 	
    [ApiExplorerSettings(GroupName = "Image")]
    public class QCQuestionConfigureService(IRepository _qcQuestionRepository,
        IRepository _trialQCQuestionRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IQCQuestionService
    {
        /// 
        /// 父问题  下拉框选项  需要排除自己  、把自己设置为父亲 (互为父亲) 、是自己孙辈的(明明是自己子孙,却设置为自己父亲)
        /// 
        /// 
        /// 
        [HttpPost]
        public async Task> GetQCQuestionSelectList(QCQuestionFilterSelect trialQCQuestionFilterSelect)
        {
            //设置父亲的时候,不允许设置为自己的孙子   这种会形成环
            var initList = await _qcQuestionRepository
                 .WhereIf(trialQCQuestionFilterSelect.TypeArray.Count() > 0, t => trialQCQuestionFilterSelect.TypeArray.Contains(t.Type))
                 .WhereIf(trialQCQuestionFilterSelect.Id != null, t => t.Id != trialQCQuestionFilterSelect.Id && t.ParentId != trialQCQuestionFilterSelect.Id)
                .OrderBy(t => t.ShowOrder).Select(x => new TrialQCQuestionSelect()
                {
                    ShowOrder = x.ShowOrder,
                    Id = x.Id,
                    ParentId = x.ParentId,
                    QuestionName = x.QuestionName,
                    LanguageType = x.LanguageType,
                    TypeValue = x.TypeValue,
                }).ToListAsync();
            //父亲的序号肯定要比自己小
            if (trialQCQuestionFilterSelect.Id != null)
            {
                var selectItem = initList.FirstOrDefault(t => t.Id == trialQCQuestionFilterSelect.Id);
                initList = initList.WhereIf(selectItem != null, t => t.Id != selectItem!.Id && t.ShowOrder < selectItem.ShowOrder).ToList();
            }
            var exceptList = GetChildId(trialQCQuestionFilterSelect.Id ?? Guid.Empty, initList);
            return initList.Where(t => !exceptList.Contains(t.Id)).ToList();
        }
        private List GetChildId(Guid parentId, List list)
        {
            var ids = new List();
            var childIds = list.Where(t => t.ParentId == parentId).Select(t => t.Id).ToList();
            foreach (var childId in childIds)
            {
                ids.AddRange(childId);
                var childs = GetChildId(childId, list);
                ids.AddRange(childs);
            }
            return ids;
        }
        [HttpPost]
        public async Task> GetQCQuestionConfigureList(QCQuestionQuery queryQCQuestionConfigure)
        {
            var QCQuestionQueryable = _qcQuestionRepository
                .WhereIf(queryQCQuestionConfigure.IsEnable != null, x => x.IsEnable == queryQCQuestionConfigure.IsEnable)
                .WhereIf(!string.IsNullOrWhiteSpace(queryQCQuestionConfigure.QuestionName), t => t.QuestionName.Contains(queryQCQuestionConfigure.QuestionName))
                .WhereIf(!string.IsNullOrWhiteSpace(queryQCQuestionConfigure.Type), t => t.Type.Contains(queryQCQuestionConfigure.Type))
                   .WhereIf(queryQCQuestionConfigure.LanguageType != null, t => t.LanguageType == queryQCQuestionConfigure.LanguageType)
                .WhereIf(queryQCQuestionConfigure.IsDefeaultViewParent == true, t => t.ParentId == null)
                .OrderByDescending(x => x.LanguageType)
                .ThenBy(t => t.ShowOrder)
                .ProjectTo(_mapper.ConfigurationProvider);
            var defalutSortArray = new string[] { nameof(QCQuestionConfigureView.LanguageType) + " desc", nameof(QCQuestionConfigureView.ShowOrder) };
            return await QCQuestionQueryable.ToPagedListAsync(queryQCQuestionConfigure, defalutSortArray);
        }
        public async Task AddOrUpdateQCQuestionConfigure(QCQuestionAddOrEdit addOrEditQCQuestionConfigure)
        {
            if (await _qcQuestionRepository.AnyAsync(x => x.Id != addOrEditQCQuestionConfigure.Id && x.ShowOrder == addOrEditQCQuestionConfigure.ShowOrder))
            {
                //---序号重复,操作失败
                throw new BusinessValidationFailedException(_localizer["QCQuestion_DuplicateIndexFailed"]);
            }
            var entity = await _qcQuestionRepository.InsertOrUpdateAsync(addOrEditQCQuestionConfigure, true);
            return ResponseOutput.Ok(entity.Id.ToString());
        }
        [HttpDelete("{qCQuestionConfigureId:guid}")]
        public async Task DeleteQCQuestionConfigure(Guid qCQuestionConfigureId)
        {
            if (await _qcQuestionRepository.AnyAsync(x => x.ParentId == qCQuestionConfigureId))
            {
                //---当前任务存在子问题,删除失败
                throw new BusinessValidationFailedException(_localizer["QCQuestion_HasChildQuestion"]);
            }
            await _qcQuestionRepository.DeleteFromQueryAsync(t => t.Id == qCQuestionConfigureId, true);
            return ResponseOutput.Ok();
        }
        /// 
        /// 获取问题预览
        /// 
        /// 
        /// 
        ///  传TrialId为获取项目的 
        ///  不传为获取系统的
        /// 
        /// 
        [HttpPost]
        public async Task> GetQuestionView(QCQuestionViewInDto inDto)
        {
            var question = new List();
            if (inDto.TrialId != null)
            {
                question = await _trialQCQuestionRepository.Where(x => x.TrialId == inDto.TrialId && x.IsEnable).OrderBy(x => x.ShowOrder).ProjectTo
                    (_mapper.ConfigurationProvider, new
                    {
                        isEn_Us = _userInfo.IsEn_Us
                    }).ToListAsync();
            }
            else
            {
                question = await _qcQuestionRepository.Where(x => x.IsEnable).OrderBy(x => x.ShowOrder).ProjectTo(_mapper.ConfigurationProvider, new
                {
                    isEn_Us = _userInfo.IsEn_Us
                }).ToListAsync();
            }
            var result = question.Where(x => x.ParentId == null).ToList();
            result.ForEach(x =>
            {
                GetQuestionChild(x, question);
            });
            return result;
        }
        private void GetQuestionChild(QCQuestionView parent, List dataList)
        {
            parent.Childrens = dataList.Where(x => x.ParentId == parent.Id).ToList();
            if (parent.Childrens.Count != 0)
            {
                parent.Childrens.ForEach(x =>
                {
                    GetQuestionChild(x, dataList);
                });
            }
        }
    }
}