package org.jeecg.modules.database.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.database.constant.ComponentSearchType;
import org.jeecg.modules.database.dto.*;
import org.jeecg.modules.database.entity.*;
import org.jeecg.modules.database.mapper.ExperimentTestProcessMapper;
import org.jeecg.modules.database.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Description: 测试过程
 * @Author: jeecg-boot
 * @Date: 2024-10-15
 * @Version: V1.0
 */
@Service
public class ExperimentTestProcessServiceImpl extends ServiceImpl<ExperimentTestProcessMapper, ExperimentTestProcess>
        implements IExperimentTestProcessService {
    @Autowired
    private ITestStandardsService        testStandardsService;
    @Autowired
    private IExperimentSampleInfoService experimentSampleInfoService;

    @Autowired
    private IComponentSearchService componentSearchService;

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


    @Override
    public List<ExperimentTestProcess> getByExperimentId(String experimentId) {
        List<ExperimentTestProcess> list = list(
                new LambdaQueryWrapper<ExperimentTestProcess>().eq(ExperimentTestProcess::getExperimentId, experimentId));
        list.forEach(this::assembleDetails);
        return list;
    }

    @Override
    public ExperimentTestProcess getById(Serializable id) {
        ExperimentTestProcess experimentTestProcess = super.getById(id);
        if (Objects.isNull(experimentTestProcess)) {
            return null;
        }
        assembleDetails(experimentTestProcess);
        return experimentTestProcess;
    }

    @Override
    public void assembleDetails(ExperimentTestProcess experimentTestProcess) {
        String testStandardsId = experimentTestProcess.getTestStandardsId();
        if (StringUtils.isNotBlank(testStandardsId)) {
            String[] split = testStandardsId.split(",");
            TestStandards testStandards = testStandardsService.findByRequirements(split[0],split[1]);
            experimentTestProcess.setTestStandards(testStandards);
        }
        String sampleInfoIds = experimentTestProcess.getSampleInfo();
        List<ExperimentSampleInfo> sampleInfoList;
        if (StringUtils.isNotBlank(sampleInfoIds)) {
            sampleInfoList = Arrays.stream(sampleInfoIds.split(",")).map(sampleInfoId -> experimentSampleInfoService.getById(sampleInfoId))
                    .filter(Objects::nonNull).collect(Collectors.toList());
            experimentTestProcess.setSampleInfoList(sampleInfoList);
        }
        String testEquipmentJson = experimentTestProcess.getTestEquipment();
        experimentTestProcess.setTestEquipmentList(new ArrayList<>());
        if (StringUtils.isNotBlank(testEquipmentJson)) {
            try {
                List<TestEquipmentDTO> testEquipmentDTOList = JSON.parseArray(testEquipmentJson, TestEquipmentDTO.class);
                experimentTestProcess.setTestEquipmentList(testEquipmentDTOList);
            }catch (Exception e) {
                // 忽略解析错误并打印错误日志，兼容历史脏数据
                logger.error("解析TestEquipmentDTO失败：" + e.getMessage());
            }

        }

        String testMeteringPointJson = experimentTestProcess.getTestMeteringPoint();
        experimentTestProcess.setTestMeteringPointList(new ArrayList<>());
        if (StringUtils.isNotBlank(testMeteringPointJson)) {
            try {
                List<TestMeteringPointDTO> testEquipmentDTOList = JSON.parseArray(testMeteringPointJson, TestMeteringPointDTO.class);
                experimentTestProcess.setTestMeteringPointList(testEquipmentDTOList);
            }catch (Exception e) {
                // 忽略解析错误并打印错误日志，兼容历史脏数据
                logger.error("解析TestMeteringPointDTO失败：" + e.getMessage());
            }

        }

        String testFluencePointJson = experimentTestProcess.getTestFluencePoint();
        experimentTestProcess.setTestFluencePointList(new ArrayList<>());
        if (StringUtils.isNotBlank(testFluencePointJson)) {
            try {
                List<TestFluencePointDTO> testEquipmentDTOList = JSON.parseArray(testFluencePointJson, TestFluencePointDTO.class);
                experimentTestProcess.setTestFluencePointList(testEquipmentDTOList);
            }catch (Exception e) {
                // 忽略解析错误并打印错误日志，兼容历史脏数据
                logger.error("解析TestFluencePointDTO失败：" + e.getMessage());
            }

        }

        String annealingDurationJson = experimentTestProcess.getAnnealingDuration();
        experimentTestProcess.setAnnealingDurationList(new ArrayList<>());
        if (StringUtils.isNotBlank(annealingDurationJson)) {
            try {
                List<TestAnnealingDurationDTO> testAnnealingDurationDTOList = JSON.parseArray(annealingDurationJson,
                        TestAnnealingDurationDTO.class);
                experimentTestProcess.setAnnealingDurationList(testAnnealingDurationDTOList);
            }catch (Exception e) {
                // 忽略解析错误并打印错误日志，兼容历史脏数据
                logger.error("解析TestAnnealingDurationDTO失败：" + e.getMessage());
            }
        }

    }

    @Override
    public void saveWithDetails(ExperimentTestProcess experimentTestProcess) {
        List<ExperimentSampleInfo> sampleInfoList = experimentTestProcess.getSampleInfoList();
        List<String> sampleInfoIds = new ArrayList<>();
        if (sampleInfoList != null && sampleInfoList.size() > 0) {
            for (ExperimentSampleInfo sampleInfo : sampleInfoList) {
                sampleInfo.setExperimentId(experimentTestProcess.getExperimentId());
                experimentSampleInfoService.saveOrUpdate(sampleInfo);
                sampleInfoIds.add(sampleInfo.getId());
            }
        }
        experimentTestProcess.setSampleInfo(StringUtils.join(sampleInfoIds, ","));
        saveOrUpdate(experimentTestProcess);

        //保存测试参数到搜索数据
        String testParameters = experimentTestProcess.getTestParameters();
        if (StringUtils.isNotBlank(testParameters)) {
            JSONArray jsonObject = JSON.parseArray(testParameters);
            if (jsonObject != null && !jsonObject.isEmpty()) {
                List<String> nameList = jsonObject.stream().map(v -> ((JSONObject) v).getString("name")).collect(Collectors.toList());
                nameList.forEach(name -> {
                    componentSearchService.saveComponentSearchByType(ComponentSearchType.TEST_PARAMS.getCode(), name);
                });
            }

        }
    }

    @Override
    public void copy(String oldId, String newExperimentId) {
        ExperimentTestProcess experiment = new ExperimentTestProcess();
        BeanUtil.copyProperties(getById(oldId), experiment);
        experiment.setExperimentId(newExperimentId);
        experiment.setId(null);
        experiment.setTestStartTime(null);
        experiment.setTestEndTime(null);
        experiment.setCreateTime(new Date());
        List<ExperimentSampleInfo> sampleInfoList = experimentSampleInfoService.getByExperimentId(newExperimentId);
        if (CollUtil.isNotEmpty(sampleInfoList)) {
            experiment.setSampleInfo(sampleInfoList.stream().map(v -> v.getId()).collect(Collectors.joining(",")));
        } else {
            experiment.setSampleInfo(null);
        }
        save(experiment);
    }

}
