
//--------------------------------------------------------------------
//     此代码由liquid模板自动生成  byzhouhang 20240909
//     生成时间 2025-02-21 07:47:30Z 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------
using IRaCIS.Core.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Infrastructure.Extention;
using System.Threading.Tasks;
using IRaCIS.Core.Infra.EFCore;
using MassTransit;
using IRaCIS.Core.Infrastructure;
using Microsoft.Extensions.Options;
namespace IRaCIS.Core.Application.Service;

/// <summary>
/// 项目文件类型
/// </summary>
/// <param name="_trialFileTypeRepository"></param>
/// <param name="_mapper"></param>
/// <param name="_userInfo"></param>
/// <param name="_localizer"></param>
[ApiExplorerSettings(GroupName = "FileRecord")]
public class TrialFileTypeService(IRepository<TrialFileType> _trialFileTypeRepository,
      IOptionsMonitor<ServiceVerifyConfigOption> _verifyConfig,
    IRepository<TrialFile> _trialFileRepository,
    IRepository<SysFileType> _sysFileTypeRepository,
                                  IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, ITrialFileTypeService
{


    [HttpPost]
    public async Task<PageOutput<TrialFileTypeView>> GetTrialFileTypeList(TrialFileTypeQuery inQuery)
    {

        var trialFileTypeQueryable = _trialFileTypeRepository
            .Where(t => t.TrialId == inQuery.TrialId)

            .WhereIf(inQuery.ArchiveTypeEnum != null, t => t.ArchiveTypeEnum == inQuery.ArchiveTypeEnum)
            .WhereIf(inQuery.IsConfirmRecord != null, t => t.IsConfirmRecord == inQuery.IsConfirmRecord)
            .WhereIf(inQuery.SubIdentificationEnum != null, t => t.SubIdentificationEnum == inQuery.SubIdentificationEnum)
            .WhereIf(inQuery.IsEnable != null, t => t.IsEnable == inQuery.IsEnable)
            .WhereIf(inQuery.Name.IsNotNullOrEmpty(), t => t.Name.Contains(inQuery.Name))
            .WhereIf(inQuery.NameCN.IsNotNullOrEmpty(), t => t.NameCN.Contains(inQuery.NameCN))

             .WhereIf(inQuery.IsSelfDefine != null, t => t.IsSelfDefine == inQuery.IsSelfDefine)
            .ProjectTo<TrialFileTypeView>(_mapper.ConfigurationProvider);

        var pageList = await trialFileTypeQueryable.ToPagedListAsync(inQuery);

        return pageList;
    }

    /// <summary>
    /// 获取项目文件类型下拉框
    /// </summary>
    /// <param name="inQuery"></param>
    /// <returns></returns>
    public async Task<List<TrialFileTypeSelectView>> GetTrialFileTypeSelectList(TrialFileTypeSelectQuery inQuery)
    {
        var list = _trialFileTypeRepository
          .Where(t => t.TrialId == inQuery.TrialId)
          .WhereIf(inQuery.ArchiveTypeEnum != null, t => t.ArchiveTypeEnum == inQuery.ArchiveTypeEnum)
         .WhereIf(inQuery.IsSelfDefine != null, t => t.IsSelfDefine == inQuery.IsSelfDefine)
         .WhereIf(inQuery.IsEnable != null, t => t.IsEnable == inQuery.IsEnable)
         .Select(t => new TrialFileTypeSelectView()
         {
             Id = t.Id,
             IsEnable = t.IsEnable,
             Name = _userInfo.IsEn_Us ? t.Name : t.NameCN,
             IsSelfDefine = t.IsSelfDefine,
             ArchiveTypeEnum = t.ArchiveTypeEnum,
         }).ToList();

        return list;

    }



    public async Task<IResponseOutput> AddOrUpdateTrialFileType(TrialFileTypeAddOrEdit addOrEditTrialFileType)
    {



        if (await _trialFileTypeRepository.AnyAsync(u => u.TrialId == addOrEditTrialFileType.TrialId && u.Id != addOrEditTrialFileType.Id && u.IsEnable == addOrEditTrialFileType.IsEnable && (u.Name == addOrEditTrialFileType.Name || u.NameCN == addOrEditTrialFileType.NameCN)))
        {
            throw new BusinessValidationFailedException(_localizer["TrialFileType_NameRepeat"]);
        }

        var entity = await _trialFileTypeRepository.InsertOrUpdateAsync(addOrEditTrialFileType, true);


        return ResponseOutput.Ok(entity.Id.ToString());

    }


    [HttpDelete("{trialFileTypeId:guid}")]
    public async Task<IResponseOutput> DeleteTrialFileType(Guid trialFileTypeId)
    {
        var success = await _trialFileTypeRepository.DeleteFromQueryAsync(t => t.Id == trialFileTypeId, true);
        return ResponseOutput.Ok();
    }


    /// <summary>
    /// 复制系统数据到项目
    /// </summary>
    /// <param name="inDto"></param>
    /// <returns></returns>
    public async Task<IResponseOutput> CopySystemFileTypeToTrial(CopySystemFileTypeToTrialInDto inDto)
    {
        if (!(await _trialFileTypeRepository.AnyAsync(x => x.TrialId == inDto.TrialId)))
        {
            var trialFileTypeList = await _sysFileTypeRepository
                .Where(x=>x.SysTemplateTypeEnum== _verifyConfig.CurrentValue.TemplateType|| x.SysTemplateTypeEnum==SysTemplateType.Both)
                .ProjectTo<TrialFileType>(_mapper.ConfigurationProvider)
                .ToListAsync();

            trialFileTypeList.ForEach(x => {
                x.TrialId = inDto.TrialId;
                x.Id = NewId.NextGuid();
            });

            await _trialFileTypeRepository.AddRangeAsync(trialFileTypeList, true);
        }

        return ResponseOutput.Ok();
    }

    /// <summary>
    /// 获取项目文件类型数据
    /// </summary>
    /// <param name="inDto"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<GetTrialFileTypeDataOutDto> GetTrialFileTypeData(GetTrialFileTypeDataInDto inDto)
    {
        await this.CopySystemFileTypeToTrial(new CopySystemFileTypeToTrialInDto()
        {
            TrialId = inDto.TrialId
        });
        var trialFileTypeList = await _trialFileTypeRepository.Where(x => x.TrialId == inDto.TrialId)
               .WhereIf(inDto.IsEnable, x => x.IsEnable)
               .OrderBy(x => x.ShowOrder)
               .ProjectTo<TrialFileTypeView>(_mapper.ConfigurationProvider)
               .ToListAsync();

        List<TrialFileTypeData> result = new List<TrialFileTypeData>();
        foreach (ArchiveType type in Enum.GetValues(typeof(ArchiveType)))
        {
            result.Add(new TrialFileTypeData()
            {
                ArchiveTypeEnum = type,
                TrialFileTypeList = trialFileTypeList.Where(x => x.ArchiveTypeEnum == type).OrderBy(x => x.SysFileTypeId == null).ThenBy(x => x.ShowOrder).ToList()
            });
        }

        return new GetTrialFileTypeDataOutDto() { TrialFileTypeDataList = result };


    }

    /// <summary>
    /// 修改授权状态
    /// </summary>
    /// <param name="inDto"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<IResponseOutput> SetAuthorizedView(SetAuthorizedViewInDto inDto)
    {
        await _trialFileTypeRepository.UpdatePartialFromQueryAsync(x => x.Id == inDto.Id, x => new TrialFileType() { IsEnable = inDto.IsEnable }, true);
        return ResponseOutput.Ok();
    }


    /// <summary>
    /// 上传同意入项记录
    /// </summary>
    /// <param name="inDto"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<IResponseOutput> UploadTrialFileTypeFile(UploadTrialFileTypeFileInDto inDto)
    {
        var trialFileType = await _trialFileTypeRepository.Where(x => x.Id == inDto.TrialFileTypeId).FirstNotNullAsync();

        if (trialFileType.FileRecordId != null)
        {
            await _trialFileRepository.BatchDeleteNoTrackingAsync(x => x.Id == trialFileType.FileRecordId);
        }

        inDto.FileRecord.TrialFileTypeId = inDto.TrialFileTypeId;
        var entity = await _trialFileRepository.InsertFromDTOAsync(inDto.FileRecord, true);
        await _trialFileTypeRepository.UpdatePartialFromQueryAsync(x => x.Id == inDto.TrialFileTypeId, x => new TrialFileType()
        {

            FileRecordId = entity.Id
        });
        await _trialFileTypeRepository.SaveChangesAsync();
        return ResponseOutput.Ok();
    }

    /// <summary>
    /// 获取入项记录
    /// </summary>
    /// <param name="inDto"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<TrialFileDto> GetTrialFileTypeFile(GetTrialFileTypeFileInDto inDto)
    {
        var trialFileType = await _trialFileTypeRepository.Where(x => x.Id == inDto.TrialFileTypeId).FirstNotNullAsync();
        if (trialFileType.FileRecordId == null)
        {
            return new TrialFileDto() { };    
        }
        var file = await _trialFileRepository.Where(x => x.Id == trialFileType.FileRecordId).ProjectTo<TrialFileDto>(_mapper.ConfigurationProvider).FirstNotNullAsync();
        return file;
    }


    /// <summary>
    /// 删除入项记录
    /// </summary>
    /// <param name="trialFileTypeId"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<IResponseOutput> DeleteTrialTypeFile(Guid trialFileTypeId)
    {
        var trialFileType = await _trialFileTypeRepository.Where(x => x.Id == trialFileTypeId).FirstNotNullAsync();

        await _trialFileRepository.DeleteFromQueryAsync(x => x.Id == trialFileType.FileRecordId, true);
        await _trialFileTypeRepository.UpdatePartialFromQueryAsync(x => x.Id == trialFileTypeId, x => new TrialFileType() { FileRecordId = null }, true);
        return ResponseOutput.Ok();
    }

}



