using IRaCIS.Application.Contracts;
using IRaCIS.Application.Interfaces;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Infra.EFCore.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using MiniExcelLibs.OpenXml;
using Newtonsoft.Json;
using System.Collections;
using System.Globalization;

namespace IRaCIS.Core.Application.Service.Common;

#region 模型

/// <summary>
/// 公共影像导表基类（IVUS / OCT 通用）
/// </summary>
public class IVUS_OCTBaseDto
{
    /// <summary>研究标识符</summary>
    public string ResearchProgramNo { get; set; }

    /// <summary>中心编号</summary>
    public string TrialSiteCode { get; set; }

    /// <summary>受试者标识符</summary>
    public string SubjectCode { get; set; }

    /// <summary>受试者唯一标识</summary>
    public string USUBJID => ResearchProgramNo + "_" + SubjectCode;

    /// <summary>访视名称</summary>
    public string? VisitName { get; set; }

    /// <summary>阅片人角色</summary>
    [DictionaryTranslateAttribute("ArmEnum")]
    public Arm ArmEnum { get; set; }

    /// <summary>拍片日期</summary>
    [DateTimeTranaslateAttribute("yyyy-MM-dd")]
    public DateTime? LatestScanDate { get; set; }

    [DateTimeTranaslateAttribute("yyyy-MM-dd")]
    public DateTime? EarliestScanDate { get; set; }

    /// <summary>阅片完成时间</summary>
    [DateTimeTranaslateAttribute("yyyy-MM-dd")]
    public DateTime? SignTime { get; set; }

    /// <summary>
    /// 访视编号 VISITNUM
    /// </summary>
    public decimal? VisitNum { get; set; }

    public string TaskName { get; set; }

    public string UserName { get; set; }

    public Guid VisitTaskId { get; set; }

    public string CriterionName { get; set; }
    #region 查询 导出
    public List<TumorLessionInfo> LesionList { get; set; } = new List<TumorLessionInfo>();

    public List<TumorCommonQustionInfo> QuestionAnswerList { get; set; }

    public List<TumorGlobalQuestionAnserInfo> GlobalResultList { get; set; }


    public DateTime? JudgeSignTime { get; set; }

    public Guid? SourceSubjectVisitId { get; set; }

    public List<decimal> SubjectCriterionReadingPeriodVisitNumList { get; set; }

    public decimal VisitTaskNum { get; set; }

    public ReadingTaskState ReadingTaskState { get; set; }

    public ReadingCategory ReadingCategory { get; set; }

    //裁判选择标记  裁判结果选择的访视或者全局任务Id
    [DictionaryTranslateAttribute("ArmEnum")]
    public Arm? JudgeArmEnum { get; set; }
    [DictionaryTranslate("YesOrNo")]
    public bool? IsJudgeSelect { get; set; }
    //在当前访视触发裁判，或者在截止日期小于等于当前访视的阅片期触发裁判
    [DictionaryTranslate("YesOrNo")]
    public bool? IsTrigerJudge { get; set; }

    //裁判选择原因（如果是访视点裁判，则仅在所选阅片人对应访视 显示；如果是阅片期裁判，则在所选阅片人 阅片期内的所有访视 显示此原因）
    public string JudgeNote { get; set; } = string.Empty;
    /// <summary>访视点备注</summary>
    public string VisitNote { get; set; }

    #endregion


}


/// <summary>
/// IVUS 导表模型
/// </summary>
public class IvusExportDto : IVUS_OCTBaseDto
{
    /// <summary>靶段</summary>
    public string TARGETV { get; set; }

    /// <summary>斑块编号</summary>
    public string PLAQUE { get; set; }

    /// <summary>外弹力膜面积</summary>
    public string EEM { get; set; }

    /// <summary>管腔面积</summary>
    public string LUMEN { get; set; }

    /// <summary>外弹力膜与管腔面积差值</summary>
    public string PA { get; set; }

    /// <summary>回撤中的图像帧数</summary>
    public string PFC { get; set; }

    /// <summary>分析图像帧数</summary>
    public string FC { get; set; }

    /// <summary>总外弹力膜面积 (如无可不填)</summary>
    public string TOTALEEM { get; set; }

    /// <summary>总 PA (如无可不填)</summary>
    public string TOTALPA { get; set; }

    /// <summary>PAV (如无可不填)</summary>
    public string PAV { get; set; }

    public string DOST { get; set; }
}

/// <summary>
/// OCT 导表模型
/// </summary>
public class OctExportDto : IVUS_OCTBaseDto
{
    /// <summary>
    /// 斑块到血管开口的距离
    /// </summary>
    public string DOST { get; set; }

    /// <summary>靶段</summary>
    public string TARGETV { get; set; }

    /// <summary>斑块编号</summary>
    public string PLAQUE { get; set; }

    /// <summary>测量标识</summary>
    public string TestID { get; set; }

    /// <summary>测量参数名称</summary>
    public string TESTCD { get; set; }

    /// <summary>测量参数值</summary>
    public string ORRES { get; set; }

    /// <summary>测量值单位</summary>
    public string ORRESU { get; set; }

    /// <summary>斑块类型</summary>
    public string PLATYPE { get; set; }

    /// <summary>最小纤维帽厚度</summary>
    public string MINFCT { get; set; }

    /// <summary>平均纤维帽厚度</summary>
    public string AVGMFCT { get; set; }

    /// <summary>脂质角度平均值</summary>
    public string LAMEAN { get; set; }

    /// <summary>脂质角度最大值</summary>
    public string LAMAX { get; set; }

    /// <summary>巨噬细胞浸润</summary>
    public string PLAMACRI { get; set; }

    /// <summary>巨噬细胞浸润角度</summary>
    public string PLAMIARC { get; set; }

    /// <summary>微通道</summary>
    public string PLAMC { get; set; }

    /// <summary>胆固醇结晶</summary>
    public string PLACCS { get; set; }
}



#endregion

[ApiExplorerSettings(GroupName = "Common")]
public class IVUS_OCTExportService(IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository, IRepository<VisitTask> _visitTaskRepository,
    IRepository<SubjectVisit> _subjectVisitTaskRepository,
    IMapper _mapper, IUserInfo _userInfo, IRepository<CommonDocument> _commonDocumentRepository, IStringLocalizer _localizer, IWebHostEnvironment _hostEnvironment) : BaseService
{

    private IQueryable<IVUS_OCTBaseDto> GetCIDSCQueryable(VisitTaskQuery inQuery, ArbitrationRule arbitrationRule, Guid trialReadingCriterionId)
    {
        var isEn_Us = _userInfo.IsEn_Us;


        var query = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsAnalysisCreate == false && (t.TaskState == TaskState.Effect || t.TaskState == TaskState.Freeze))

        //访视和全局查询已签名完成的，裁判可以是未签名，未完成的
        .Where(t => (t.ReadingTaskState == ReadingTaskState.HaveSigned && (t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global)) || t.ReadingCategory == ReadingCategory.Judge)
        .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
        .WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)

        .WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
        .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
        .WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
        .WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Subject.Code.Contains(inQuery.SubjectCode))
        .Select(t => new IVUS_OCTBaseDto()
        {
            ResearchProgramNo = t.Trial.ResearchProgramNo,
            TrialSiteCode = t.Subject.TrialSite.TrialSiteCode,
            SubjectCode = t.Subject.Code,
            UserName = t.DoctorUser.UserName,
            ArmEnum = t.ArmEnum,

            TaskName = t.TaskName,
            SignTime = t.SignTime,
            JudgeSignTime = t.ReadingCategory == ReadingCategory.Judge ? t.SignTime : null,
            SourceSubjectVisitId = t.SourceSubjectVisitId,
            VisitTaskNum = t.VisitTaskNum,
            VisitNum = t.VisitTaskNum,
            VisitName = t.SourceSubjectVisit.VisitName,
            EarliestScanDate = t.SourceSubjectVisit.EarliestScanDate,
            LatestScanDate = t.SourceSubjectVisit.LatestScanDate,
            VisitTaskId = t.Id,
            CriterionName = t.TrialReadingCriterion.CriterionName,



            ReadingCategory = t.ReadingCategory,
            ReadingTaskState = t.ReadingTaskState,


            //以最后为准，没法直接获取(涉及到全局，裁判)
            SubjectCriterionReadingPeriodVisitNumList = t.Subject.ReadModuleList.Where(u => u.TrialReadingCriterionId == trialReadingCriterionId && u.ReadingSetType == ReadingSetType.ImageReading).Select(c => c.SubjectVisit.VisitNum).ToList(),

            IsJudgeSelect = null,

            JudgeArmEnum = t.JudgeResultTask.ArmEnum,

            IsTrigerJudge = arbitrationRule == ArbitrationRule.Visit ? t.JudgeVisitTaskId != null :
             (arbitrationRule == ArbitrationRule.Reading ?
             t.Subject.SubjectVisitTaskList.Any(c => c.TaskState == TaskState.Effect && c.IsAnalysisCreate == false && c.ReadingCategory == ReadingCategory.Judge && c.TrialReadingCriterionId == trialReadingCriterionId && t.VisitTaskNum < c.VisitTaskNum) :
             false),
            JudgeNote = t.ReadingCategory == ReadingCategory.Judge ? t.JudgeResultRemark : "",

            //全局 访视上修改会要求填写
            VisitNote = t.ReadingTaskQuestionAnswerList.Where(c => c.ReadingQuestionTrial.QuestionType == QuestionType.AdjustReason).FirstOrDefault()!.Answer,

            GlobalResultList = t.GlobalVisitResultList.Where(t => t.GlobalAnswerType == GlobalAnswerType.Reason || t.GlobalAnswerType == GlobalAnswerType.UpdateType).Select(t => new TumorGlobalQuestionAnserInfo()
            {
                TaskId = t.TaskId,
                GlobalAnswerType = t.GlobalAnswerType,
                Answer = t.Answer
            }).ToList(),



            QuestionAnswerList = t.ReadingTaskQuestionAnswerList
            .OrderBy(u => u.ReadingQuestionTrial.ShowOrder)
            .Select(c => new TumorCommonQustionInfo()
            {
                QuestionType = c.ReadingQuestionTrial.QuestionType,
                OptionTypeEnum = c.ReadingQuestionTrial.OptionTypeEnum,
                QuestionId = c.ReadingQuestionTrial.Id,
                QuestionName = isEn_Us ? c.ReadingQuestionTrial.QuestionEnName : c.ReadingQuestionTrial.QuestionName,
                QuestionValue = c.IsGlobalChange ? c.GlobalChangeAnswer : c.Answer,
                TranslateDicName = c.ReadingQuestionTrial.DictionaryCode,
                ValueType = c.ReadingQuestionTrial.ValueType,
                Unit = c.ReadingQuestionTrial.Unit
            }).ToList(),

            LesionList = t.LesionList.OrderBy(t => t.RowMark).Select(c => new TumorLessionInfo()
            {
                Id = c.Id,
                OrganInfoId = c.OrganInfoId,
                LessionType = c.ReadingQuestionTrial.LesionType,
                LessionCode = c.RowMark,
                SplitRowId = c.SplitRowId,
                DicomModality = c.DicomSeries.DicomStudy.ModalityForEdit,
                NoneDicomModality = c.NoneDicomStudy.Modality,

                LessionAnswerList = c.LesionAnswerList.Select(k => new TumorLessionAnswerInfo()
                {

                    RowId = k.RowId,
                    OptionTypeEnum = k.ReadingTableQuestionTrial.OptionTypeEnum,
                    TranslateDicName = k.ReadingTableQuestionTrial.DictionaryCode,
                    QuestionMark = k.ReadingTableQuestionTrial.QuestionMark,
                    TableQuesionId = k.ReadingTableQuestionTrial.Id,
                    QuestionName = isEn_Us ? k.ReadingTableQuestionTrial.QuestionEnName : k.ReadingTableQuestionTrial.QuestionName,
                    QuestionValue = k.Answer,
                    ShowOrder = k.ReadingTableQuestionTrial.ShowOrder,
                    Unit = k.ReadingTableQuestionTrial.Unit

                }).ToList(),

            }).ToList()

        });

        return query;
    }


    [HttpPost]
    public async Task<IActionResult> GetTumor_CDISC_Export(VisitTaskQuery inQuery,
     [FromServices] IRepository<VisitTaskReReading> _visitTaskReReadingRepository,
    [FromServices] IDictionaryService _dictionaryService,
    [FromServices] IRepository<OrganTrialInfo> _trialOrganRepository,
    [FromServices] IRepository<ReadingQuestionTrial> _trialReadingQuestionRepository,
     [FromServices] IRepository<ReadingTableQuestionTrial> _trialReadingTableQuestionRepository,
    [FromServices] IRepository<Trial> _trialRepository)
    {
        //每次查询必须是单标准的
        var criterion = await _readingQuestionCriterionTrialRepository
             .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.Id == inQuery.TrialReadingCriterionId)
             .WhereIf(inQuery.CriterionType != null, t => t.CriterionType == inQuery.CriterionType)
            .Select(t => new { t.Id, t.CriterionType, t.CriterionGroup, t.IsGlobalReading, t.IsArbitrationReading, t.IsOncologyReading, t.CriterionName, t.ArbitrationRule }).FirstNotNullAsync();

        var arbitrationRule = criterion.ArbitrationRule;

        var isEn_Us = _userInfo.IsEn_Us;

        var query = GetCIDSCQueryable(inQuery, arbitrationRule, criterion.Id);

        //任务排序
        var taskList = await query.OrderBy(t => t.SubjectCode).ThenBy(t => t.VisitTaskNum).ThenBy(t => t.ArmEnum).ToListAsync();

        //重阅信息
        var reReadingList = _visitTaskReReadingRepository.Where(t => t.TrialId == inQuery.TrialId && t.RequestReReadingType == RequestReReadingType.DocotorApply).Select(t => new
        {
            t.OriginalReReadingTask.VisitTaskNum,
            t.OriginalReReadingTask.ArmEnum,
            t.OriginalReReadingTask.DoctorUser.UserName,
            t.RequestReReadingReason
        }).ToList();

        //处理裁判标记
        taskList = DealJudgeMark(criterion.ArbitrationRule, criterion.IsGlobalReading, taskList);



        #region 字典和各个表的数组准备

        var dicNameList = taskList.SelectMany(t => t.QuestionAnswerList).Select(t => t.TranslateDicName)
        .Union(taskList.SelectMany(t => t.LesionList).SelectMany(t => t.LessionAnswerList).Where(t => t.TranslateDicName.IsNotNullOrEmpty()).Select(c => c.TranslateDicName))
        .Union(new List<string>() { "ArmEnum", "ValueUnit" })
        .Distinct().ToArray();


        //翻译字典
        var translateDataList = await _dictionaryService.GetBasicDataSelect(dicNameList);

        var ivusList = new List<IvusExportDto>();

        var octList = new List<OctExportDto>();

        var exportCode = string.Empty;

        var data = new object();

        #endregion


        foreach (var task in taskList)
        {

            if (task.ReadingCategory == ReadingCategory.Judge || task.ReadingCategory == ReadingCategory.Global)
            {
                continue;
            }

            if (criterion.CriterionType == CriterionType.IVUS)
            {
                //一个斑块一条记录
                foreach (var lesion in task.LesionList.Where(t => t.LessionType == LesionType.MatchValues))
                {
                    var ivus = _mapper.Map<IvusExportDto>(task);


                    //靶段
                    var target = task.QuestionAnswerList.Where(t => t.QuestionType == QuestionType.TargetSegment).FirstOrDefault();

                    var itemValue = target?.QuestionValue??string.Empty;
                    //多选
                    int[] enumValues = new int[0];
                    // 1. 反序列化 JSON 数组 (字符串枚举)
                    if (!itemValue.StartsWith("[") || !itemValue.EndsWith("]"))
                    {
                        enumValues = new int[1] { int.Parse(itemValue) };
                    }
                    else
                    {
                        enumValues = JsonConvert.DeserializeObject<int[]>(itemValue) ?? new int[0];

                    }


                    // 2. 翻译每一项并输出逗号拼接字符串
                  var  translatedItemData = string.Join(",",
                        enumValues.OrderBy(t=>t).Select(code =>
                            translateDataList[target?.TranslateDicName]
                                .FirstOrDefault(t =>
                                   string.Equals(code.ToString(), t.Code, StringComparison.OrdinalIgnoreCase)
                                ) is var r && r != null
                                    ? (isEn_Us ? r.Value : r.ValueCN)
                                    : string.Empty
                        ));

                    ivus.TARGETV = translatedItemData;


                    var marks = task.QuestionAnswerList.Where(t => t.QuestionType == QuestionType.TargetSegmentRemarks).FirstOrDefault()?.QuestionValue ?? string.Empty;

                    if (marks.IsNotNullOrEmpty())
                    {
                        ivus.TARGETV = ivus.TARGETV + "_" + marks;
                    }

                    //斑块编号
                    ivus.PLAQUE = lesion.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.PlaqueNumber).FirstOrDefault()?.QuestionValue ?? string.Empty;

                    //外弹力膜面积
                    ivus.EEM = lesion.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.ElasticArea).FirstOrDefault()?.QuestionValue ?? string.Empty;
                    //管腔面积
                    ivus.LUMEN = lesion.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.LumenArea).FirstOrDefault()?.QuestionValue ?? string.Empty;

                    //外弹力膜与管腔面积差值
                    ivus.PA = lesion.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.ElasticAreaDiffValue).FirstOrDefault()?.QuestionValue ?? string.Empty;


                    //回撤中的图像帧数
                    ivus.PFC = task.QuestionAnswerList.Where(t => t.QuestionType == QuestionType.PullbackFrameCount).FirstOrDefault()?.QuestionValue ?? string.Empty;

                    //分析图像帧数
                    ivus.FC = task.QuestionAnswerList.Where(t => t.QuestionType == QuestionType.AnalysisFrameCount).FirstOrDefault()?.QuestionValue ?? string.Empty;

                    var findStatLession = task.LesionList.FirstOrDefault(t => t.LessionType == LesionType.PatchDataStatistics && t.LessionAnswerList.Any(t => t.QuestionMark == QuestionMark.PlaqueNumber && t.QuestionValue == ivus.PLAQUE));
                    var findPAVLession = task.LesionList.FirstOrDefault(t => t.LessionType == LesionType.PAV && t.LessionAnswerList.Any(t => t.QuestionMark == QuestionMark.PlaqueNumber && t.QuestionValue == ivus.PLAQUE));


                    //EEM求和
                    ivus.TOTALEEM = findStatLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.EEMSum).FirstOrDefault()?.QuestionValue ?? string.Empty;

                    //(EEM-Lumen)求和
                    ivus.TOTALPA = findStatLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.EEMSubtractLumenSum).FirstOrDefault()?.QuestionValue ?? string.Empty;
                    //冠状动脉粥样硬化体积百分比（PAV）

                    ivus.PAV = findPAVLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.PAV).FirstOrDefault()?.QuestionValue ?? string.Empty;

                    if (ivus.PAV.IsNotNullOrEmpty())
                    {
                        ivus.PAV = ivus.PAV + "%";
                    }


                    ivus.DOST = findPAVLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.PlaqueToOstiumDistance).FirstOrDefault()?.QuestionValue ?? string.Empty;

                    

                    ivusList.Add(ivus);

                }



            }
            else if (criterion.CriterionType == CriterionType.OCT)
            {
                //找到所有的斑块编号 排序

                var noList = task.LesionList.Where(t => t.LessionType == LesionType.FCT).SelectMany(t => t.LessionAnswerList.Where(a => a.QuestionMark == QuestionMark.PlaqueNumber)
                        .Select(a => a.QuestionValue)).Where(v => !string.IsNullOrEmpty(v)).Distinct()
                        .OrderBy(v => int.Parse(v))   // 按数字排序
                        .ToList();                    // 最终是字符串列表


                foreach (var pNo in noList)
                {
                    var pNoIndex = 0;
                    //一个斑块 一次测量（FCT  脂质角度）一条记录
                    foreach (var fctLesion in task.LesionList.Where(t => t.LessionType == LesionType.FCT
                                      && t.LessionAnswerList.Any(t => t.QuestionMark == QuestionMark.PlaqueNumber && t.QuestionValue == pNo)))
                    {
                        pNoIndex++;

                        foreach (var lessionAnswer in fctLesion?.LessionAnswerList.Where(t => t.QuestionMark != QuestionMark.PlaqueNumber).OrderBy(t => t.ShowOrder))
                        {
                            var mark = string.Empty;
                            switch (lessionAnswer.QuestionMark)
                            {

                                case QuestionMark.FirstFCT:
                                    mark = "FCTMV1";
                                    break;
                                case QuestionMark.SecondFCT:
                                    mark = "FCTMV2";
                                    break;
                                case QuestionMark.ThirdFCT:
                                    mark = "FCTMV3";
                                    break;
                                case QuestionMark.AvgFCT:
                                    mark = "AVGFCT";
                                    break;
                                case QuestionMark.MacrophageInfiltrationMeasurement:
                                    mark = "MACRI";
                                    break;
                                case QuestionMark.MacrophageInfiltrationAngle:
                                    mark = "MIARC";
                                    break;
                                case QuestionMark.MicrochannelMeasurement:
                                    mark = "MC";
                                    break;
                                case QuestionMark.CholesterolCrystalMeasurement:
                                    mark = "CCS";
                                    break;
                                case QuestionMark.LumenAreaMeasurement:
                                    mark = "LUMEN";
                                    break;


                            }

                            if (mark.IsNotNullOrEmpty())
                            {
                                var oct = CreatOCT(task, pNo, translateDataList);

                                //    测量标识 阅片人_斑块号_表格_行号

                                oct.TestID = $"{(task.ArmEnum == Arm.DoubleReadingArm1 ? "R1" : "R2")}_{pNo}_L_{pNoIndex}";

                                //     测量参数名称

                                oct.TESTCD = mark;

                                //    测量参数值  

                                if (lessionAnswer.TranslateDicName.IsNotNullOrEmpty())
                                {
                                    oct.ORRES = translateDataList[lessionAnswer.TranslateDicName].Where(t => t.Code.ToLower() == lessionAnswer.QuestionValue?.ToString().ToLower()).Select(t => isEn_Us ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
                                }
                                else
                                {
                                    oct.ORRES = lessionAnswer?.QuestionValue ?? string.Empty;

                                }


                                //     测量值单位
                                oct.ORRESU = translateDataList["ValueUnit"].Where(t => t.Code.ToLower() == ((int?)lessionAnswer.Unit)?.ToString().ToLower()).Select(t => isEn_Us ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;

                                octList.Add(oct);
                            }
                        }

                        #region 废弃


                        //var findFct1 = fctLesion?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.FirstFCT).FirstOrDefault();

                        //if (findFct1 != null)
                        //{
                        //    var oct = CreatOCT(task, pNo);

                        //    //    测量标识

                        //    oct.TestID = $"{(task.ArmEnum == Arm.DoubleReadingArm1 ? "R1" : "R2")}_{pNo}_L_{pNoIndex}";

                        //    //     测量参数名称

                        //    oct.TESTCD = "FCTMV1";

                        //    //    测量参数值  
                        //    oct.ORRES = findFct1?.QuestionValue ?? string.Empty;

                        //    //     测量值单位
                        //    oct.ORRESU = translateDataList["ValueUnit"].Where(t => t.Code.ToLower() == ((int?)findFct1.Unit)?.ToString().ToLower()).Select(t => isEn_Us ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;

                        //    octList.Add(oct);
                        //}

                        //var findFct2 = fctLesion?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.SecondFCT).FirstOrDefault();

                        //if (findFct2 != null)
                        //{
                        //    var oct = CreatOCT(task, pNo);

                        //    //    测量标识

                        //    oct.TestID = $"{(task.ArmEnum == Arm.DoubleReadingArm1 ? "R1" : "R2")}_{pNo}_L_{pNoIndex}";

                        //    //     测量参数名称

                        //    oct.TESTCD = "FCTMV2";

                        //    //    测量参数值  
                        //    oct.ORRES = findFct2?.QuestionValue ?? string.Empty;

                        //    //     测量值单位
                        //    oct.ORRESU = translateDataList["ValueUnit"].Where(t => t.Code.ToLower() == ((int?)findFct2.Unit)?.ToString().ToLower()).Select(t => isEn_Us ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;

                        //    octList.Add(oct);
                        //}

                        //var findFct3 = fctLesion?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.ThirdFCT).FirstOrDefault();

                        //if (findFct3 != null)
                        //{
                        //    var oct = CreatOCT(task, pNo);

                        //    //    测量标识

                        //    oct.TestID = $"{(task.ArmEnum == Arm.DoubleReadingArm1 ? "R1" : "R2")}_{pNo}_L_{pNoIndex}";

                        //    //     测量参数名称

                        //    oct.TESTCD = "FCTMV3";

                        //    //    测量参数值  
                        //    oct.ORRES = findFct3?.QuestionValue ?? string.Empty;

                        //    //     测量值单位
                        //    oct.ORRESU = translateDataList["ValueUnit"].Where(t => t.Code.ToLower() == ((int?)findFct3.Unit)?.ToString().ToLower()).Select(t => isEn_Us ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;

                        //    octList.Add(oct);
                        //}


                        //var avgFct = fctLesion?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.AvgFCT).FirstOrDefault();

                        //if (avgFct != null)
                        //{
                        //    var oct = CreatOCT(task, pNo);

                        //    //    测量标识

                        //    oct.TestID = $"{(task.ArmEnum == Arm.DoubleReadingArm1 ? "R1" : "R2")}_{pNo}_L_{pNoIndex}";

                        //    //     测量参数名称

                        //    oct.TESTCD = "AVGFCT";

                        //    //    测量参数值  
                        //    oct.ORRES = avgFct?.QuestionValue ?? string.Empty;

                        //    //     测量值单位
                        //    oct.ORRESU = translateDataList["ValueUnit"].Where(t => t.Code.ToLower() == ((int?)avgFct.Unit)?.ToString().ToLower()).Select(t => isEn_Us ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;

                        //    octList.Add(oct);
                        //}

                        #endregion

                    }

                    var lNoIndex = 0;
                    //纸质角度
                    foreach (var liLesion in task.LesionList.Where(t => t.LessionType == LesionType.LipidAngle
                                    && t.LessionAnswerList.Any(t => t.QuestionMark == QuestionMark.PlaqueNumber && t.QuestionValue == pNo)))
                    {
                        lNoIndex++;

                        var findAngle = liLesion?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.LipidAngle).FirstOrDefault();

                        if (findAngle != null)
                        {
                            var oct = CreatOCT(task, pNo, translateDataList);

                            //    测量标识

                            oct.TestID = $"{(task.ArmEnum == Arm.DoubleReadingArm1 ? "R1" : "R2")}_{pNo}_A_{lNoIndex}";

                            //     测量参数名称

                            oct.TESTCD = "LIPIDA";

                            //    测量参数值  
                            oct.ORRES = findAngle?.QuestionValue ?? string.Empty;

                            //     测量值单位
                            oct.ORRESU = translateDataList["ValueUnit"].Where(t => t.Code.ToLower() == ((int?)findAngle.Unit)?.ToString().ToLower()).Select(t => isEn_Us ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;

                            octList.Add(oct);
                        }
                    }
                }




            }



        }



        var exportInfo = (await _trialRepository.Where(t => t.Id == inQuery.TrialId).IgnoreQueryFilters().ProjectTo<ExcelExportInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
        exportInfo.CriterionName = criterion.CriterionName;




        if (criterion.CriterionType == CriterionType.IVUS)
        {
            exportCode = StaticData.Export.IVUS_CDISC_Export;

            data = ivusList;

            data = await TranslateDataList(new { List = data }, _dictionaryService, typeof(IvusExportDto));
        }
        else if (criterion.CriterionType == CriterionType.OCT)
        {
            exportCode = StaticData.Export.OCT_CDISC_Export;

            data = octList;

            data = await TranslateDataList(new { List = data }, _dictionaryService, typeof(OctExportDto));
        }

        var (physicalPath, fileName) = await FileStoreHelper.GetCommonDocPhysicalFilePathAsync(_hostEnvironment, _commonDocumentRepository, exportCode);

        var exportFileNamePrefix = $"{exportInfo.ResearchProgramNo}_{exportInfo.CriterionName}";

        var fileDownloadName = $"{(string.IsNullOrEmpty(exportFileNamePrefix) ? "" : exportFileNamePrefix + "_")}{Path.GetFileNameWithoutExtension(fileName)}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";

        return await DataExportAsync(data, fileDownloadName, physicalPath);




    }

    private OctExportDto CreatOCT(IVUS_OCTBaseDto task, string pNo, Dictionary<string, List<BasicDicSelectCopy>> translateDataList)
    {

        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var oct = _mapper.Map<OctExportDto>(task);



        //靶段

        var target = task.QuestionAnswerList.Where(t => t.QuestionType == QuestionType.TargetSegment).FirstOrDefault();

        var itemValue = target?.QuestionValue ?? string.Empty;
        //多选
        int[] enumValueArray = new int[0];
        // 1. 反序列化 JSON 数组 (字符串枚举)
        if (!itemValue.StartsWith("[") || !itemValue.EndsWith("]"))
        {
            enumValueArray = new int[1] { int.Parse(itemValue) };
        }
        else
        {
            enumValueArray = JsonConvert.DeserializeObject<int[]>(itemValue) ?? new int[0];

        }


        // 2. 翻译每一项并输出逗号拼接字符串
        var translatedItemData = string.Join(",",
              enumValueArray.OrderBy(t => t).Select(code =>
                  translateDataList[target?.TranslateDicName]
                      .FirstOrDefault(t =>
                         string.Equals(code.ToString(), t.Code, StringComparison.OrdinalIgnoreCase)
                      ) is var r && r != null
                          ? (isEn_US ? r.Value : r.ValueCN)
                          : string.Empty
              ));

        oct.TARGETV = translatedItemData;

        var marks = task.QuestionAnswerList.Where(t => t.QuestionType == QuestionType.TargetSegmentRemarks).FirstOrDefault()?.QuestionValue ?? string.Empty;

        if (marks.IsNotNullOrEmpty())
        {
            oct.TARGETV = oct.TARGETV + "_" + marks;
        }

        //斑块编号
        oct.PLAQUE = pNo;

        var findLession = task.LesionList.Where(t => t.LessionType == LesionType.PatchDataStatistics
                       && t.LessionAnswerList.Any(t => t.QuestionMark == QuestionMark.PlaqueNumber && t.QuestionValue == pNo)).FirstOrDefault();

        //    斑块类型    
        var undetermined = findLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.Undetermined).FirstOrDefault();

        if (undetermined?.OptionTypeEnum == OptionType.Multiple)
        {
            var qValue = undetermined?.QuestionValue;
            int[] enumValues = new int[0];
            // 1. 反序列化 JSON 数组 (字符串枚举)
            if (!qValue.StartsWith("[") || !qValue.EndsWith("]"))
            {
                enumValues = new int[1] { int.Parse(qValue) };
            }
            else
            {
                enumValues = JsonConvert.DeserializeObject<int[]>(qValue) ?? new int[0];

            }

            // 2. 翻译每一项并输出逗号拼接字符串
            var tValue = string.Join(",",
                 enumValues.Select(code =>
                     translateDataList[undetermined.TranslateDicName]
                         .FirstOrDefault(t =>
                            string.Equals(code.ToString(), t.Code, StringComparison.OrdinalIgnoreCase)
                         ) is var r && r != null
                             ? (isEn_US ? r.Value : r.ValueCN)
                             : string.Empty
                 ));

            oct.PLATYPE = tValue;
        }
        else
        {
            oct.PLATYPE = translateDataList[undetermined?.TranslateDicName].Where(t => t.Code.ToLower() == undetermined?.QuestionValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;

        }


        //    斑块到血管开口的距离 
        oct.DOST = findLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.PlaqueToOstiumDistance).FirstOrDefault()?.QuestionValue ?? string.Empty;

        //     匹配动脉段最小FCT 
        oct.MINFCT = findLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.MiniMumFCT).FirstOrDefault()?.QuestionValue ?? string.Empty;
        //    平均最小FCT 
        oct.AVGMFCT = findLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.AvgMinFCT).FirstOrDefault()?.QuestionValue ?? string.Empty;
        //     脂质角度平均值 
        oct.LAMEAN = findLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.AvgLipidAngle).FirstOrDefault()?.QuestionValue ?? string.Empty;
        //    脂质角度最大值 
        oct.LAMAX = findLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.MaxAvgLipidAngle).FirstOrDefault()?.QuestionValue ?? string.Empty;
        //    巨噬细胞浸润 

        var macri = findLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.MacrophageInfiltration).FirstOrDefault();
        oct.PLAMACRI = translateDataList[macri?.TranslateDicName].Where(t => t.Code.ToLower() == macri?.QuestionValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
        //   巨噬细胞浸润角度 
        oct.PLAMIARC = findLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.MacrophageExtensionAngle).FirstOrDefault()?.QuestionValue ?? string.Empty;
        //   微通道 

        var mc = findLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.Microchannels).FirstOrDefault();
        oct.PLAMC = translateDataList[mc?.TranslateDicName].Where(t => t.Code.ToLower() == mc?.QuestionValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
        //    胆固醇结晶

        var ccs = findLession?.LessionAnswerList.Where(t => t.QuestionMark == QuestionMark.CholesterolCrystallization).FirstOrDefault();
        oct.PLACCS = translateDataList[ccs?.TranslateDicName].Where(t => t.Code.ToLower() == ccs?.QuestionValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;

        return oct;
    }

    public static async Task<object> TranslateDataList(object data, IDictionaryService _dictionaryService, Type translateType, CriterionType? criterionType = null)
    {
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var needTranslatePropertyList = translateType.GetProperties().Where(t => t.IsDefined(typeof(DictionaryTranslateAttribute), true))
               .SelectMany(c =>
               c.GetCustomAttributes(typeof(DictionaryTranslateAttribute), false).Select(f => (DictionaryTranslateAttribute?)f).Where(t => t?.CriterionType == criterionType || t?.CriterionType == null)
               .Select(k => new { c.Name, k.DicParentCode, k.IsTranslateDenpendOtherProperty, k.DependPropertyName, k.DependPropertyValueStr })
               ).ToList();

        var needFormartPropertyList = translateType.GetProperties().Where(t => t.IsDefined(typeof(DateTimeTranaslateAttribute), true))
               .SelectMany(c =>
               c.GetCustomAttributes(typeof(DateTimeTranaslateAttribute), false).Select(f => (DateTimeTranaslateAttribute?)f)
               .Select(k => new { c.Name, k.Formart })
               ).ToList();

        var dic = data.ConvertToDictionary();

        //翻译字典
        var translateDataList = await _dictionaryService.GetBasicDataSelect(needTranslatePropertyList.Select(t => t.DicParentCode).Distinct().ToArray());

        foreach (var key in dic.Keys)
        {
            //是数组 那么找到对应的属性 进行翻译
            if (dic[key] != null && dic[key].GetType().GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>)))
            {

                var newObjList = new List<object>();
                var no = 1;

                foreach (var item in dic[key] as IList)
                {
                    var itemDic = item.ConvertToDictionary();


                    foreach (var needTranslateProperty in needTranslatePropertyList)
                    {
                        if (itemDic.Keys.Any(t => t == needTranslateProperty.Name))
                        {
                            //翻译的属性依赖其他属性
                            if (needTranslateProperty.IsTranslateDenpendOtherProperty)
                            {
                                if (itemDic[needTranslateProperty.DependPropertyName]?.ToString().ToLower() == needTranslateProperty.DependPropertyValueStr.ToLower())
                                {
                                    var beforeValue = itemDic[needTranslateProperty.Name]?.ToString();

                                    itemDic[needTranslateProperty.Name] = translateDataList[needTranslateProperty.DicParentCode].Where(t => t.Code.ToLower() == beforeValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
                                }
                            }
                            //普通翻译 或者某一标准翻译
                            else
                            {
                                var beforeValue = itemDic[needTranslateProperty.Name]?.ToString();


                                itemDic[needTranslateProperty.Name] = translateDataList[needTranslateProperty.DicParentCode].Where(t => t.Code.ToLower() == beforeValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
                            }
                        }
                    }

                    //根据设置翻译时间
                    foreach (var needFormartProperty in needFormartPropertyList)
                    {
                        if (itemDic.Keys.Any(t => t == needFormartProperty.Name))
                        {
                            var value = itemDic[needFormartProperty.Name];
                            if (value != null && DateTime.TryParse(value.ToString(), out var dt))
                            {
                                itemDic[needFormartProperty.Name] = dt.ToString(needFormartProperty.Formart);
                            }
                        }
                    }

                    itemDic.Add("No", no++);


                    newObjList.Add(itemDic);
                }

                dic[key] = newObjList;

            }

        }

        return dic;
    }


    public static async Task<IActionResult> DataExportAsync(object data, string fileDownloadName, string physicalPath)
    {

        //模板路径
        var tplPath = physicalPath;


        var memoryStream = new MemoryStream();

        var config = new OpenXmlConfiguration()
        {
            IgnoreTemplateParameterMissing = true,
        };

        await MiniExcel.SaveAsByTemplateAsync(memoryStream, tplPath, data, config);

        memoryStream.Seek(0, SeekOrigin.Begin);


        return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            FileDownloadName = fileDownloadName
        };
    }


    private List<T> DealJudgeMark<T>(ArbitrationRule arbitrationRule, bool isGlobalReading, IEnumerable<T> list) where T : IVUS_OCTBaseDto
    {
        //处理访视任务的裁判标记
        var resultExceptJudgeList = list.Where(t => t.ReadingCategory != ReadingCategory.Judge).ToList();

        var judegeList = list.Where(t => t.ReadingCategory == ReadingCategory.Judge).ToList();

        if (arbitrationRule == ArbitrationRule.Visit)
        {

            foreach (var item in resultExceptJudgeList)
            {
                var findJudge = judegeList.FirstOrDefault(t => t.SubjectCode == item.SubjectCode
                && (t.VisitTaskNum - ReadingCommon.TaskNumDic[ReadingCategory.Judge]) == item.VisitTaskNum);

                if (findJudge != null)
                {
                    if (findJudge.ReadingTaskState == ReadingTaskState.HaveSigned)
                    {
                        item.IsJudgeSelect = findJudge.JudgeArmEnum == item.ArmEnum ? true : false;

                        item.JudgeNote = findJudge.JudgeArmEnum == item.ArmEnum ? findJudge.JudgeNote : string.Empty;

                        item.JudgeSignTime = findJudge.JudgeArmEnum == item.ArmEnum ? findJudge.JudgeSignTime : null;
                    }
                    else
                    {
                        //默认也是null 其实不用赋值
                        item.IsJudgeSelect = null;
                    }
                }
                else
                {

                    //两个人都做了
                    if (resultExceptJudgeList.Where(t => t.VisitTaskNum == item.VisitTaskNum && t.SubjectCode == item.SubjectCode).Select(t => t.ArmEnum).Distinct().Count() == 2)
                    {
                        //如果没有产生裁判，默认选择R1
                        if (item.ArmEnum == Arm.DoubleReadingArm1)
                        {
                            item.IsJudgeSelect = true;
                        }
                        else
                        {
                            item.IsJudgeSelect = false;
                        }
                    }
                    else
                    {
                        item.IsJudgeSelect = null;
                        item.IsTrigerJudge = null;
                    }



                }
            }

        }
        else if (arbitrationRule == ArbitrationRule.Reading)
        {
            //处理访视裁判标记
            foreach (var visitItem in resultExceptJudgeList.Where(t => t.ReadingCategory == ReadingCategory.Visit))
            {
                ////默认设置为false  只处理为true 和 空的情况
                //visitItem.IsJudgeSelect = false;

                var subjectJudgeList = judegeList.Where(t => t.SubjectCode == visitItem.SubjectCode).ToList();

                //阅片期访视号
                var subjectReadingPeriondVisitNumList = resultExceptJudgeList.Where(t => t.SubjectCode == visitItem.SubjectCode).FirstOrDefault()?.SubjectCriterionReadingPeriodVisitNumList;

                //两个人完成最大得任务号(访视+全局)
                var subjectMaxFinishedTaskNum = resultExceptJudgeList.Where(t => t.SubjectCode == visitItem.SubjectCode)
                   .GroupBy(t => t.VisitTaskNum).Where(g => g.Count() == 2).Select(g => g.Key).DefaultIfEmpty().Max();

                var addReadingPeriodNum = isGlobalReading ? ReadingCommon.TaskNumDic[ReadingCategory.Global] : 0;

                var finishedGlobalCount = 0;

                //没有配置阅片期
                if (subjectReadingPeriondVisitNumList == null)
                {
                    finishedGlobalCount = 0;
                }
                else
                {
                    //已完成的全局数量
                    finishedGlobalCount = resultExceptJudgeList.Where(t => t.SubjectCode == visitItem.SubjectCode && subjectReadingPeriondVisitNumList.Any(c => (c + addReadingPeriodNum) == t.VisitTaskNum)
                    /*&& t.ReadingCategory == ReadingCategory.Global*/)
                       .Select(t => new { t.VisitTaskNum, t.ArmEnum }).Distinct()
                      .GroupBy(t => t.VisitTaskNum).Where(g => g.Count() == 2).Select(g => g.Key).Count();
                }


                visitItem.IsJudgeSelect = null;
                visitItem.IsTrigerJudge = null;

                if (finishedGlobalCount != 0)
                {
                    //最大的全局是否产生裁判

                    var subjectMaxFinishedGlobalTaskNum = resultExceptJudgeList.Where(t => t.SubjectCode == visitItem.SubjectCode && subjectReadingPeriondVisitNumList.Any(c => (c + addReadingPeriodNum) == t.VisitTaskNum)
                    /*&& t.ReadingCategory == ReadingCategory.Global*/)
                  .Select(t => new { t.VisitTaskNum, t.ArmEnum }).Distinct()
                  .GroupBy(t => t.VisitTaskNum).Where(g => g.Count() == 2).Select(g => g.Key).DefaultIfEmpty().Max();

                    //最大的完成的全局是否产生裁判
                    if (subjectJudgeList.Any(t => t.VisitTaskNum == (subjectMaxFinishedGlobalTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Judge])))
                    {

                        var maxJudge = subjectJudgeList.FirstOrDefault(t => t.VisitTaskNum == (subjectMaxFinishedGlobalTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Judge]));

                        //最大裁判完成了
                        if (maxJudge.ReadingTaskState == ReadingTaskState.HaveSigned)
                        {
                            if (visitItem.VisitTaskNum < maxJudge.VisitTaskNum)
                            {
                                //触发裁判
                                visitItem.IsTrigerJudge = true;

                                if (visitItem.ArmEnum == maxJudge.JudgeArmEnum)
                                {
                                    visitItem.IsJudgeSelect = true;
                                    visitItem.JudgeNote = maxJudge.JudgeNote;

                                    visitItem.JudgeSignTime = maxJudge.JudgeSignTime;
                                }
                                //裁判没选择的人设置为false
                                else
                                {
                                    visitItem.IsJudgeSelect = false;
                                }
                            }
                            else
                            {
                                //后续访视  未知 默认都是null

                            }
                        }
                        else
                        {
                            //找到当前未阅最大裁判之前的已完成的最大裁判任务
                            var maxFinishedJudge = subjectJudgeList.Where(t => t.ReadingTaskState == ReadingTaskState.HaveSigned).OrderByDescending(t => t.VisitTaskNum).FirstOrDefault();

                            if (maxFinishedJudge == null)
                            {
                                // 为空 裁判选择标记默认就是null  不用处理

                                if (visitItem.VisitTaskNum < maxJudge.VisitTaskNum)
                                {
                                    visitItem.IsTrigerJudge = true;
                                }

                            }
                            else
                            {
                                if (visitItem.VisitTaskNum < maxFinishedJudge.VisitTaskNum)
                                {
                                    visitItem.IsTrigerJudge = true;

                                    if (visitItem.ArmEnum == maxFinishedJudge.JudgeArmEnum)
                                    {
                                        visitItem.IsJudgeSelect = true;
                                        visitItem.JudgeNote = maxFinishedJudge.JudgeNote;
                                        visitItem.JudgeSignTime = maxFinishedJudge.JudgeSignTime;
                                    }
                                    //裁判没选择的人设置为false
                                    else
                                    {
                                        visitItem.IsJudgeSelect = false;
                                    }
                                }
                                else if (visitItem.VisitTaskNum > maxFinishedJudge.VisitTaskNum && visitItem.VisitTaskNum < maxJudge.VisitTaskNum)
                                {
                                    //完成裁判 和未完成裁判之间的 裁判选择标记默认是null

                                    visitItem.IsTrigerJudge = true;
                                }
                                else
                                {
                                    //在未完成全局裁判之后的访视  未知   默认都是null


                                }

                            }

                        }


                    }
                    else
                    {
                        //最大的完成的全局未产生裁判

                        if (visitItem.VisitTaskNum <= subjectMaxFinishedGlobalTaskNum)
                        {
                            visitItem.IsTrigerJudge = false;

                            if (visitItem.ArmEnum == Arm.DoubleReadingArm1)
                            {
                                visitItem.IsJudgeSelect = true;

                            }
                            else
                            {
                                visitItem.IsJudgeSelect = false;
                            }
                        }
                        else
                        {
                            //未产生裁判的全局之后的访视 两个标记都是null (后续可能还有全局，但是全局两个人没做完)
                        }


                    }


                }



            }
        }
        else
        {
            foreach (var visitItem in resultExceptJudgeList.Where(t => t.ReadingCategory == ReadingCategory.Visit))
            {
                visitItem.IsJudgeSelect = null;
                visitItem.IsTrigerJudge = null;
            }

        }
        return resultExceptJudgeList.Union(judegeList).OrderBy(t => t.SubjectCode).ThenBy(t => t.VisitTaskNum).ThenBy(t => t.ArmEnum).ToList();
    }

}
