package org.jeecg.modules.database.controller;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.util.StatusPrinter;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.*;
import org.jeecg.modules.database.constant.ExperimentStatus;
import org.jeecg.modules.database.dto.*;
import org.jeecg.modules.database.entity.*;
import org.jeecg.modules.database.service.*;
import org.jeecg.modules.system.controller.SysDataSourceController;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 试验管理
 * @Author: jeecg-boot
 * @Date: 2024-08-30
 * @Version: V1.0
 */
@Tag(name = "试验管理")
@RestController
@RequestMapping("/database/experiment")
@Slf4j
public class ExperimentController extends JeecgController<Experiment, IExperimentService> {
    @Autowired
    private IExperimentService                 experimentService;
    @Autowired
    private IExperimentLogService              experimentLogService;
    @Autowired
    private IExperimentAnnealProcessService    experimentAnnealProcessService;
    @Autowired
    private IExperimentRadiationProcessService experimentRadiationProcessService;
    @Autowired
    private IExperimentTestProcessService      experimentTestProcessService;
    @Autowired
    private ISysUserService                    userService;
    @Autowired
    private IExperimentUserService             experimentUserService;
    @Autowired
    private IExperimentSequenceService         experimentSequenceService;

    @Autowired
    private IExperimentSampleInfoService         experimentSampleInfoService;
    @Autowired
    private IExperimentDeviationConditionService experimentDeviationConditionService;
    @Autowired
    private IExperimentDeviationEquipmentService experimentDeviationEquipmentService;
    @Autowired
    private IExperimentIrradiationBoardService   experimentIrradiationBoardService;
    @Autowired
    private IExperimentFileService               experimentFileService;
    @Autowired
    private INasaDataRecordService               nasaDataRecordService;
    @Autowired
    private ILocalDatabaseService                localDatabaseService;
    @Autowired
    private SysDataSourceController              sysDataSourceController;

    private static final Logger logger = LoggerFactory.getLogger(ExperimentController.class);

    private static final String ADMIN_NAME = "admin";

    /**
     * 分页列表查询
     *
     * @param experiment
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "试验管理-分页列表查询")
    @Operation(summary = "试验管理-分页列表查询")
    @GetMapping(value = "/list")
    //    @PermissionData(pageComponent="experiment/manage/ExperimentList")
    public Result<IPage<Experiment>> queryPageList(Experiment experiment, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,@RequestParam(name = "pageName", defaultValue = "") String pageName,
                                                   HttpServletRequest req) {
        logger.info("查询页面：{}", pageName);
        // 初始化 Logback
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

        // 打印所有 Logger 的配置（含 Effective Level）
        StatusPrinter.print(lc);
        //Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义duoXuan字段的查询规则为：LIKE_WITH_OR
        //customeRuleMap.put("startDate", QueryRuleEnum.RIGHT_LIKE);
        //
        Map<String, String[]> parameterMap = req.getParameterMap();
        //QueryWrapper<Experiment> queryWrapper = QueryGenerator.initQueryWrapper(experiment, parameterMap, customeRuleMap);
        Page<Experiment> page = new Page<>(pageNo, pageSize);

        experiment.setName(StringUtils.remove(experiment.getName(), "*"));
        experiment.setClientName(StringUtils.remove(experiment.getClientName(), "*"));
        experiment.setSampleType(StringUtils.remove(experiment.getSampleType(), "*"));
        experiment.setSampleModel(StringUtils.remove(experiment.getSampleModel(), "*"));
        experiment.setEquipmentModel(StringUtils.remove(experiment.getEquipmentModel(), "*"));
        experiment.setPageName(pageName);

        String username = JwtUtil.getUserNameByToken(req);
        SysUser currentUser = userService.getUserByName(username);
        currentUser.setPostText("e.index_no asc");
        if (parameterMap.containsKey("column") && StringUtils.isNotBlank(parameterMap.get("column")[0])) {
            String columnObj = parameterMap.get("column")[0];
            if (!StringUtils.equals(columnObj, "createTime")) {
                String column = ReflectHelper.getTableFieldName(experiment.getClass(), columnObj);
                String order = parameterMap.get("order")[0];
                String orderSql = "e." + column + " " + order;
                currentUser.setPostText(orderSql);
            }
        }

        IPage<Experiment> pageList = experimentService.join(page, experiment, currentUser);
        pageList.getRecords().forEach(v -> experimentService.fetchExperimentDetail(v));
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param experiment
     * @return
     */
    @AutoLog(value = "试验管理-添加")
    @Operation(summary = "试验管理-添加",
            description = "添加试验,传sampleInfoList,deviationConditionList,deviationEquipmentList,irradiationBoardList,不用传fileList. </br> "
                    + "experimentUser 用,隔开")
    @RequiresPermissions("database:experiment:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Experiment experiment, HttpServletRequest request) {
        String experimentNo = experiment.getExperimentNo();
        if (!StringUtils.startsWith(experimentNo, "KC")) {
            return Result.error("实验编号格式不正确！");
        }
        //校验试验的基本信息
        String result = validateSampleInfos(experiment);
        if (StringUtils.isNotBlank(result)) {
            return Result.error(result);
        }

        experiment.setStatus(ExperimentStatus.PRE_TEST);
        experimentService.saveWithDetail(experiment);

        ExperimentLog experimentLog = new ExperimentLog();
        experimentLog.setExperimentId(experiment.getId());
        experimentLog.setLogContent("新建实验");
        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);
        experimentLog.setCreateBy(userByName.getRealname());
        experimentLogService.save(experimentLog);

        return Result.OK("添加成功！");
    }

    /**
     * 新增和修改试验时 需要校验样例信息和辐照板信息、偏置条件信息、加偏设备信息是否一致。
     *  检查方法是： 样品信息的ids = 辐照板信息、偏置条件信息、加偏设备信息的样品信息IDs
     * @param experiment 试验信息
     * @return 错误信息， 如果返回为空，则校验通过。
     */
    private String validateSampleInfos(Experiment experiment) {
        List<ExperimentSampleInfo> sampleInfoList = experiment.getSampleInfoList();
        List<ExperimentIrradiationBoard> irradiationBoardList = experiment.getIrradiationBoardList();
        List<ExperimentDeviationCondition> deviationConditionList = experiment.getDeviationConditionList();
        List<ExperimentDeviationEquipment> deviationEquipmentList = experiment.getDeviationEquipmentList();

        Set<String> sampleModelSet = sampleInfoList.stream()
                .map(ExperimentSampleInfo::getSampleModel)
                .collect(Collectors.toSet());

        Set<String> irradiationBoardModels = irradiationBoardList.stream()
                .map(ExperimentIrradiationBoard::getSampleModel)
                .filter(sampleModel -> sampleModel != null && !sampleModel.isEmpty())
                .flatMap(sampleModel -> Arrays.stream(sampleModel.split(",")))
                .map(String::trim)
                .collect(Collectors.toSet());

        if (!sampleModelSet.equals(irradiationBoardModels)) {
            return "辐照板信息不匹配！";
        }

        Set<String> deviationConditionModels = deviationConditionList.stream()
                .map(ExperimentDeviationCondition::getSampleModel)
                .filter(sampleModel -> sampleModel != null && !sampleModel.isEmpty())
                .flatMap(sampleModel -> Arrays.stream(sampleModel.split(",")))
                .map(String::trim)
                .collect(Collectors.toSet());

        if (!sampleModelSet.equals(deviationConditionModels)) {
            return "偏置条件信息不匹配！";
        }

        Set<String> deviationEquipmentModels = deviationEquipmentList.stream()
                .map(ExperimentDeviationEquipment::getSampleModel)
                .filter(sampleModel -> sampleModel != null && !sampleModel.isEmpty())
                .flatMap(sampleModel -> Arrays.stream(sampleModel.split(",")))
                .map(String::trim)
                .collect(Collectors.toSet());

        if (!sampleModelSet.equals(deviationEquipmentModels)) {
            return "加偏设备信息不匹配！";
        }

        return "";
    }

    @AutoLog(value = "试验管理-暂存")
    @Operation(summary = "试验管理-暂存")
    @RequiresPermissions("database:experiment:add")
    @PostMapping(value = "/staging")
    public Result<String> staging(@RequestBody Experiment experiment, HttpServletRequest request) {
        String experimentNo = experiment.getExperimentNo();
        if (!StringUtils.startsWith(experimentNo, "KC")) {
            return Result.error("实验编号格式不正确！");
        }
        //0503: 暂存 去掉状态的判断
        /*if (StringUtils.isNotBlank(experiment.getId())) {
            Experiment dbExp = experimentService.getById(experiment.getId());
            if (!(StringUtils.equals(dbExp.getStatus(), ExperimentStatus.STAGING) || StringUtils.equals(dbExp.getStatus(),
                    ExperimentStatus.PRE_TEST))) {
                return Result.error("实验状态不正确！");
            }
        }*/
        experiment.setStatus(ExperimentStatus.STAGING);
        experimentService.saveWithDetail(experiment);

        return Result.OK("暂存成功！");
    }

    /**
     * 编辑
     *
     * @param experiment
     * @return
     */
    @AutoLog(value = "试验管理-编辑")
    @Operation(summary = "试验管理-编辑",
            description = "编辑试验,传sampleInfoList,deviationConditionList,deviationEquipmentList,irradiationBoardList,不用传fileList \n "
                    + "experimentUser 用逗号隔开,无修改的字段可不传")
    @RequiresPermissions("database:experiment:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody Experiment experiment, HttpServletRequest request) {

        String username = JwtUtil.getUserNameByToken(request);
        SysUser userByName = userService.getUserByName(username);
        // 超级管理不用判断状态和修改状态，只修改数据。 20250511 邓春
        if (!ADMIN_NAME.equals(userByName.getUsername())) {
            Experiment dbExp = experimentService.getById(experiment.getId());
            if (StringUtils.equals(dbExp.getStatus(), ExperimentStatus.COMPLETED) || StringUtils.equals(dbExp.getStatus(),
                    ExperimentStatus.REVIEWED)) {
                return Result.error("试验状态:[" + dbExp.getStatus() + "]不能进行修改！");
            }
            if (StringUtils.equals(dbExp.getStatus(), ExperimentStatus.STAGING)) {
                experiment.setStatus(ExperimentStatus.PRE_TEST);
            } else {
                experiment.setStatus(dbExp.getStatus());
            }
            experiment.setIndexNo(dbExp.getIndexNo());
        }

        //校验试验的基本信息
        String result = validateSampleInfos(experiment);
        if (StringUtils.isNotBlank(result)) {
            return Result.error(result);
        }

        experimentService.saveWithDetail(experiment);
        ExperimentLog experimentLog = new ExperimentLog();
        experimentLog.setExperimentId(experiment.getId());
        experimentLog.setLogContent("修改实验信息");
        experimentLog.setCreateBy(userByName.getRealname());
        experimentLogService.save(experimentLog);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "试验管理-通过id删除")
    @Operation(summary = "试验管理-通过id删除")
    @RequiresPermissions("database:experiment:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        experimentService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "试验管理-试验复制")
    @Operation(summary = "试验管理-试验复制")
    //@RequiresPermissions("database:experiment:delete")
    @PostMapping(value = "/copy")
    public Result<String> copy(@RequestParam(name = "id", required = true) String id) {
        Experiment old = experimentService.getById(id);
        experimentService.fetchExperimentDetail(old);
        Experiment copied = experimentService.copy(old);

        List<ExperimentAnnealProcess> experimentAnnealProcess = experimentAnnealProcessService.getByExperimentId(old.getId());
        if (CollUtil.isNotEmpty(experimentAnnealProcess)) {
            experimentAnnealProcess.forEach(v -> experimentAnnealProcessService.copy(v.getId(), copied.getId()));
        }
        List<ExperimentRadiationProcess> experimentRadiationProcess = experimentRadiationProcessService.getByExperimentId(old.getId());
        if (CollUtil.isNotEmpty(experimentRadiationProcess)) {
            experimentRadiationProcess.forEach(v -> experimentRadiationProcessService.copy(v.getId(), copied.getId()));
        }
        List<ExperimentTestProcess> experimentTestProcess = experimentTestProcessService.getByExperimentId(old.getId());
        if (CollUtil.isNotEmpty(experimentTestProcess)) {
            experimentTestProcess.forEach(v -> experimentTestProcessService.copy(v.getId(), copied.getId()));
        }
        return Result.OK("复制成功!");
    }

    @AutoLog(value = "试验管理-完成试验")
    @Operation(summary = "试验管理-完成试验")
    @PostMapping(value = "/complete")
    public Result<String> complete(@RequestBody Experiment experiment) {
        if (StringUtils.isBlank(experiment.getId())) {
            return Result.error("试验数据不存在！");
        }
        Experiment dbData = experimentService.getById(experiment.getId());
        if (StringUtils.equals(dbData.getStatus(), ExperimentStatus.COMPLETED) ) {
            return Result.error("试验状态:[" + dbData.getStatus() + "]不能进行修改！");
        }
        experimentService.changeStatus(experiment.getId(), ExperimentStatus.COMPLETED);
        LocalDatabase localData = new LocalDatabase();
        localData.setClientName(dbData.getClientName());
        localData.setName(dbData.getName());
        localData.setType(dbData.getType());
        localData.setStartDate(dbData.getStartDate());
        localData.setEndDate(dbData.getEndDate());
        localData.setStatus(ExperimentStatus.COMPLETED);
        localData.setExperimentNo(dbData.getExperimentNo());
        localData.setExperimentId(dbData.getId());
        localData.setTotalCountXhy(dbData.getTotalCountXhy());
        localData.setTotalCountLhs(dbData.getTotalCountLhs());
        List<ExperimentSampleInfo> sampleInfoList = experimentSampleInfoService.getByExperimentId(dbData.getId());
        if (CollUtil.isNotEmpty(sampleInfoList)) {
            String joinStr = String.join(",", sampleInfoList.stream().map(v -> v.getSampleModel()).collect(Collectors.toSet()));
            localData.setSampleModel(joinStr);
        }
        localDatabaseService.save(localData);
        return Result.OK("试验已完成!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "试验管理-批量删除")
    @Operation(summary = "试验管理-批量删除")
    @RequiresPermissions("database:experiment:delete")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.experimentService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "试验管理-通过id查询")
    @Operation(summary = "试验管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Experiment> queryById(@RequestParam(name = "id", required = true) String id) {
        Experiment experiment = experimentService.getById(id);
        if (experiment == null) {
            return Result.error("未找到对应数据");
        }
        experimentService.fetchExperimentDetail(experiment);
        return Result.OK(experiment);
    }

    @Operation(summary = "试验管理-检查能否生成报告")
    @GetMapping(value = "/checkCanReport")
    public Result<Experiment> checkCanReport(@RequestParam(name = "id", required = true) String id) {
        Experiment experiment = experimentService.getById(id);
        if (experiment == null) {
            return Result.error("未找到试验数据!");
        }
        List<ExperimentRadiationProcess> radiationProcessList = experimentRadiationProcessService.getByExperimentId(experiment.getId());
        if (CollUtil.isEmpty(radiationProcessList)) {
            return Result.error("未填写辐照过程!");
        }
        return Result.OK();
    }

    /**
     * 导出excel
     *
     * @param request
     * @param experiment
     */

    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Experiment experiment) {
        //return super.exportXls(request, experiment, Experiment.class, "试验管理");
        String title = "试验管理";
        QueryWrapper<Experiment> queryWrapper = QueryGenerator.initQueryWrapper(experiment, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        // Step.2 获取导出数据
        queryWrapper.orderBy(true, true, "index_no");
        List<Experiment> exportList = experimentService.list(queryWrapper);
        for (Experiment ex : exportList) {
            experimentService.fetchExperimentDetail(ex);
        }
        List<ExperimentExportDTO> resultList = new ArrayList<>();
        for (int i = 0; i < exportList.size(); i++) {
            Experiment ex = exportList.get(i);
            ExperimentExportDTO dto = new ExperimentExportDTO();
            dto.setId(ex.getId());
            dto.setIndexNo(i + 1);
            dto.setExperimentNo(ex.getExperimentNo());
            dto.setName(ex.getName());
            dto.setClientName(ex.getClientName());
            dto.setType(ex.getType());
            dto.setStartDate(ex.getStartDate());
            dto.setEndDate(ex.getEndDate());
            String equipmentStr = ex.getDeviationEquipmentList().stream().map(v -> v.getEquipmentName()).filter(
                            v -> StringUtils.isNotBlank(v))
                    .collect(Collectors.joining("\n"));
            dto.setEquipment(equipmentStr);
            dto.setSupervisorName(ex.getSupervisorName());
            dto.setReportCount(ex.getExperimentReportList().size() + "");
            List<ExperimentRating> experimentRatingList = ex.getExperimentRatingList();
            String rateStr = experimentRatingList.stream().map(v -> v.getRateUserName() + "：" + v.getTotalScore()).collect(
                    Collectors.joining("\n"));
            dto.setRateUserAndScore(rateStr);
            List<ExperimentRadiationProcess> radiationProcessList = experimentRadiationProcessService.getByExperimentId(ex.getId());
            //辐照过程
            List<RadiationProcessExportDTO> detailList = new ArrayList<>();
            //List<ExperimentIrradiationBoard> irradiationBoardList = ex.getIrradiationBoardList();
            if (CollUtil.isNotEmpty(radiationProcessList)) {
                radiationProcessList.forEach(radiationProcess -> {
                    String radiationDetailJson = radiationProcess.getRadiationDetail();
                    if (StringUtils.isNotBlank(radiationDetailJson)) {
                        RadiationMapDTO radiationMap = JSON.parseObject(radiationDetailJson, RadiationMapDTO.class);
                        addIfNotEmpty(detailList, extractedXgy(radiationProcess, radiationMap.getXgy(), ex));
                        addIfNotEmpty(detailList, extractedXgy(radiationProcess, radiationMap.getDgy(), ex));
                        addIfNotEmpty(detailList, extractedXgy(radiationProcess, radiationMap.getX(), ex));
                        addIfNotEmpty(detailList, extractedXgy(radiationProcess, radiationMap.getElectronics(), ex));
                        addIfNotEmpty(detailList, extractedXgy(radiationProcess, radiationMap.getProton(), ex));
                    }
                });
            }

            //退火过程
            //List<AnnealProcessExportDTO> annealProcessList = new ArrayList<>();
            //List<ExperimentAnnealProcess> experimentAnnealProcessList = experimentAnnealProcessService.getByExperimentId(ex.getId());
            //if (CollUtil.isNotEmpty(experimentAnnealProcessList)) {
            //    experimentAnnealProcessList.forEach(v -> {
            //        List<ExperimentSampleInfo> sampleInfoList = v.getSampleInfoList();
            //        List<ExperimentDeviationEquipment> deviationEquipmentList = v.getDeviationEquipmentList();
            //        List<ExperimentDeviationCondition> deviationConditionList = v.getDeviationConditionList();
            //        if (CollUtil.isNotEmpty(sampleInfoList)) {
            //            for (int j = 0; j < sampleInfoList.size(); j++) {
            //                ExperimentSampleInfo sampleInfo = sampleInfoList.get(j);
            //                AnnealProcessExportDTO annealProcessExportDTO = new AnnealProcessExportDTO();
            //
            //                if (CollUtil.isNotEmpty(deviationConditionList) && deviationConditionList.size() > j && ObjUtil.isNotNull(
            //                        deviationConditionList.get(j))
            //                ) {
            //                    BeanUtil.copyProperties(deviationConditionList.get(j), annealProcessExportDTO);
            //                }
            //                if (CollUtil.isNotEmpty(deviationEquipmentList) && deviationEquipmentList.size() > j && ObjUtil.isNotNull(
            //                        deviationEquipmentList.get(j))
            //                ) {
            //                    BeanUtil.copyProperties(deviationEquipmentList.get(j), annealProcessExportDTO);
            //                }
            //
            //                annealProcessExportDTO.setSampleName(sampleInfo.getSampleName());
            //                annealProcessExportDTO.setSampleModel(sampleInfo.getSampleModel());
            //                annealProcessExportDTO.setSampleType(sampleInfo.getSampleType());
            //                annealProcessExportDTO.setAnnealTemperature(v.getAnnealTemperature());
            //                annealProcessExportDTO.setAnnealStartTime(DateUtils.formatDate(v.getAnnealStartTime(), "yyyy-MM-dd HH:mm"));
            //                annealProcessExportDTO.setAnnealEndTime(DateUtils.formatDate(v.getAnnealEndTime(), "yyyy-MM-dd HH:mm"));
            //                annealProcessList.add(annealProcessExportDTO);
            //            }
            //        }
            //    });
            //}
            //
            //dto.setAnnealProcessList(annealProcessList);

            //测试过程
            //List<ExperimentTestProcess> experimentTestProcessList = experimentTestProcessService.getByExperimentId(ex.getId());
            //List<TestProcessExportDTO> testProcessList = new ArrayList<>();
            //if (CollUtil.isNotEmpty(experimentTestProcessList)) {
            //    experimentTestProcessList.forEach(v -> {
            //        TestProcessExportDTO testProcessExportDTO = new TestProcessExportDTO();
            //        testProcessExportDTO.setEnvironmentalTemperature(v.getEnvironmentalTemperature());
            //        testProcessExportDTO.setEnvironmentalHumidity(v.getEnvironmentalHumidity());
            //        testProcessExportDTO.setTestStandards(ObjUtil.isNotNull(v.getTestStandards()) ? v.getTestStandards().getName() : "");
            //        testProcessExportDTO.setTemperatureRequirements(
            //                ObjUtil.isNotNull(v.getTestStandards()) ? v.getTestStandards().getTemperatureRequirements() : "");
            //        testProcessExportDTO.setHumidityRequirements(
            //                ObjUtil.isNotNull(v.getTestStandards()) ? v.getTestStandards().getHumidityRequirements() : "");
            //        String testParameters = v.getTestParameters();
            //        if (StringUtils.isNotBlank(testParameters)) {
            //            List<Map> jsonObject = JSON.parseArray(testParameters, Map.class);
            //            String collect = jsonObject.stream().map(s -> s.getOrDefault("name", "").toString()).collect(
            //                    Collectors.joining(","));
            //            testProcessExportDTO.setTestParameters(collect);
            //        }
            //        List<TestEquipmentDTO> testEquipmentDTOList = v.getTestEquipmentList();
            //        if (CollUtil.isNotEmpty(testEquipmentDTOList)) {
            //            testProcessExportDTO.setEquipmentModel(testEquipmentDTOList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getEquipmentModel()))
            //                    .map(t -> t.getEquipmentModel())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setSampleModel(testEquipmentDTOList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getSampleModel()))
            //                    .map(t -> t.getSampleModel())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setManagementNo(testEquipmentDTOList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getManagementNo()))
            //                    .map(t -> t.getManagementNo())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setLifespan(testEquipmentDTOList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getLifespan()))
            //                    .map(t -> t.getLifespan())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setEquipmentName(testEquipmentDTOList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getEquipmentName()))
            //                    .map(t -> t.getEquipmentName())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setRoomNo(testEquipmentDTOList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getRoomNo()))
            //                    .map(t -> t.getRoomNo())
            //                    .collect(Collectors.joining(",")));
            //        }
            //
            //        List<TestMeteringPointDTO> testMeteringPointList = v.getTestMeteringPointList();
            //        if (CollUtil.isNotEmpty(testMeteringPointList)) {
            //            testProcessExportDTO.setMeteringPoint(testMeteringPointList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getPoint()))
            //                    .map(t -> t.getPoint())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setMeteringStartTime(testMeteringPointList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getStartTime()))
            //                    .map(t -> t.getStartTime())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setMeteringEndTime(testMeteringPointList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getEndTime()))
            //                    .map(t -> t.getEndTime())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setMeteringResult(testMeteringPointList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getResult()))
            //                    .map(t -> t.getResult())
            //                    .collect(Collectors.joining(",")));
            //        }
            //
            //        List<TestFluencePointDTO> testFluencePointList = v.getTestFluencePointList();
            //        if (CollUtil.isNotEmpty(testFluencePointList)) {
            //            testProcessExportDTO.setFluencePoint(testFluencePointList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getPoint()))
            //                    .map(t -> t.getPoint())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setFluenceStartTime(testFluencePointList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getStartTime()))
            //                    .map(t -> t.getStartTime())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setFluenceEndTime(testFluencePointList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getEndTime()))
            //                    .map(t -> t.getEndTime())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setFluenceResult(testFluencePointList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getResult()))
            //                    .map(t -> t.getResult())
            //                    .collect(Collectors.joining(",")));
            //        }
            //
            //        List<TestAnnealingDurationDTO> annealingDurationList = v.getAnnealingDurationList();
            //        if (CollUtil.isNotEmpty(annealingDurationList)) {
            //            testProcessExportDTO.setAnnealingPoint(annealingDurationList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getPoint()))
            //                    .map(t -> t.getPoint())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setAnnealingStartTime(annealingDurationList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getStartTime()))
            //                    .map(t -> t.getStartTime())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setAnnealingEndTime(annealingDurationList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getEndTime()))
            //                    .map(t -> t.getEndTime())
            //                    .collect(Collectors.joining(",")));
            //
            //            testProcessExportDTO.setAnnealingResult(annealingDurationList.stream().filter(
            //                            t -> StringUtils.isNotBlank(t.getResult()))
            //                    .map(t -> t.getResult())
            //                    .collect(Collectors.joining(",")));
            //        }
            //        testProcessExportDTO.setTestResult(v.getTestResult());
            //        testProcessList.add(testProcessExportDTO);
            //    });
            //}
            //dto.setTestProcessList(testProcessList);

            dto.setRadiationProcessList(detailList);
            resultList.add(dto);
        }
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, ExperimentExportDTO.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + Optional.ofNullable(sysUser).map(v -> v.getRealname())
                .orElse("") + ",导出日期:" + DateUtils.formatDate(new Date()), title);
        //exportParams.setImageBasePath(jeecgBaseConfig.getPath().getUpload());
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, resultList);
        return mv;

    }

    private void addIfNotEmpty(List<RadiationProcessExportDTO> detailList, RadiationProcessExportDTO dto) {
        if (dto != null) {
            detailList.add(dto);
        }
    }

    private RadiationProcessExportDTO extractedXgy(ExperimentRadiationProcess radiationProcess, List<RadiationDetailDTO> xgy,
                                                   Experiment experiment) {
        if (CollUtil.isEmpty(xgy)) {
            return null;
        }
        RadiationProcessExportDTO detail = new RadiationProcessExportDTO();
        List<ExperimentSampleInfo> sampleInfoList = radiationProcess.getSampleInfoList();
        detail.setRadiateType(radiationProcess.getRadiationSource());
        if (CollUtil.isNotEmpty(sampleInfoList)) {
            detail.setSampleModel(sampleInfoList.stream().map(s -> s.getSampleModel()).collect(Collectors.joining(",")));
            detail.setSampleType(sampleInfoList.stream().map(s -> s.getSampleType()).collect(Collectors.joining(",")));
            detail.setSampleName(sampleInfoList.stream().map(s -> s.getSampleName()).collect(Collectors.joining(",")));
        }
        detail.setMeasurementRate(
                xgy.stream().filter(v -> StringUtils.isNotBlank(v.getActualMeasurementRate())).map(v -> v.getActualMeasurementRate())
                        .collect(Collectors.joining(",")));
        OptionalDouble maxRate = xgy.stream().map(obj -> obj.getActualMeasurementRate()) // 获取point字段
                .filter(point -> StringUtils.isNotBlank(point))
                .filter(str -> str.matches("-?\\d+(\\.\\d+)?")) // 只保留数字格式的字符串
                .mapToDouble(Double::parseDouble) // 转换为double
                .max();
        detail.setTotalMeasurementRate(maxRate.isPresent() ? String.valueOf(maxRate.getAsDouble()) : "");
        List<ExperimentIrradiationBoard> irradiationBoardList = experiment.getIrradiationBoardList();
        if (CollUtil.isNotEmpty(irradiationBoardList)) {
            detail.setSourceArea(irradiationBoardList.stream().filter(k -> StringUtils.isNotBlank(k.getSourceArea()))
                    .map(s -> s.getSourceArea()).collect(Collectors.joining(",")));
        }

        //String measurementRate = radiationProcess.getMeasurementRate();
        //if (StringUtils.isNotBlank(measurementRate)) {
        //    List<Map<String, String>> maps = JSON.parseObject(measurementRate, new TypeReference<>() {});
        //    List<String> rate = new ArrayList<>();
        //    maps.stream().forEach(v -> rate.add(String.join(",", v.values())));
        //    detail.setMeasurementRate(String.join(",", rate));
        //}

        //detail.setMeasurementRate(radiationProcess.getMeasurementRate());
        //detail.setPlannedMeasurementRate(
        //        xgy.stream().filter(v -> StringUtils.isNotBlank(v.getPlannedMeasurementRate())).map(v -> v.getPlannedMeasurementRate())
        //                .collect(Collectors.joining(",")));
        //detail.setActualMeasurementRate(
        //        xgy.stream().filter(v -> StringUtils.isNotBlank(v.getActualMeasurementRate())).map(v -> v.getActualMeasurementRate())
        //                .collect(Collectors.joining(",")));
        //detail.setPlannedMeasurementPoint(
        //        xgy.stream().filter(v -> StringUtils.isNotBlank(v.getPlannedMeasurementPoint())).map(v -> v.getPlannedMeasurementPoint())
        //                .collect(Collectors.joining(",")));
        //detail.setPoint(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getPoint())).map(v -> v.getPoint())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setSourceDistance(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getSourceDistance())).map(v -> v.getSourceDistance())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setTubeCurrent(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getTubeCurrent())).map(v -> v.getTubeCurrent())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setEnergy(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getEnergy())).map(v -> v.getEnergy())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setCalibrationDistance(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getCalibrationDistance()))
        //        .map(v -> v.getCalibrationDistance())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setIrradiationTime(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getIrradiationTime())).map(v -> v
        // .getIrradiationTime())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setActualInjectionRate(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getActualInjectionRate()))
        //        .map(v -> v.getActualInjectionRate())
        //        .collect(Collectors.joining(",")));
        //detail.setElectronEnergy(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getElectronEnergy())).map(v -> v.getElectronEnergy())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setBeam(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getBeam())).map(v -> v.getBeam())
        //        .collect(Collectors.joining(",")));
        //detail.setPlateSpacing(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getPlateSpacing())).map(v -> v.getPlateSpacing())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setProtonEnergy(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getProtonEnergy())).map(v -> v.getProtonEnergy())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setScanArea(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getScanArea())).map(v -> v.getScanArea())
        //        .collect(Collectors.joining(",")));
        //detail.setEnvironmentSelect(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getEnvironmentSelect()))
        //        .map(v -> v.getEnvironmentSelect())
        //        .collect(Collectors.joining(",")));
        //detail.setXy(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getXy())).map(v -> v.getXy())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setTypeSelect(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getTypeSelect())).map(v -> v.getTypeSelect())
        //        .collect(Collectors.joining(",")));
        //
        //detail.setStartTime(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getStartTime())).map(v -> v.getStartTime())
        //        .collect(Collectors.joining(",")));
        //detail.setEndTime(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getEndTime())).map(v -> v.getEndTime())
        //        .collect(Collectors.joining(",")));
        //detail.setPlannedInjectionRate(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getPlannedInjectionRate()))
        //        .map(v -> v.getPlannedInjectionRate())
        //        .collect(Collectors.joining(",")));
        //detail.setPlannedInjectionPoints(xgy.stream().filter(v -> StringUtils.isNotBlank(v.getPlannedInjectionPoints()))
        //        .map(v -> v.getPlannedInjectionPoints())
        //        .collect(Collectors.joining(",")));
        return detail;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("database:experiment:add")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Experiment.class);
    }

    /**
     * 审核
     *
     * @param experiment
     * @return
     */
    @PostMapping(value = "/audit")
    public Result<String> queryPageList(@RequestBody Experiment experiment) {
        if (Objects.isNull(experiment) || StringUtils.isBlank(experiment.getId())) {
            return Result.OK("请选择试验");
        }
        experiment.setStatus(ExperimentStatus.REVIEWED);
        experimentService.updateById(experiment);
        return Result.OK("审核完成");
    }

}
