package com.hz.pm.api.projectlib.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hz.pm.api.performance.model.entity.ProjectCoreBusinessIndicators;
import com.hz.pm.api.performance.service.IProjectCoreBusinessIndicatorsService;
import com.hz.pm.api.projectlib.model.entity.Project;
import com.hz.pm.api.projectlib.model.entity.ProjectApplication;
import com.hz.pm.api.projectlib.mapper.ProjectApplicationMapper;
import com.hz.pm.api.projectlib.service.IProjectApplicationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WendyYang
 * @since 2023-02-05
 */
@Service
@Slf4j
@AllArgsConstructor
public class ProjectApplicationServiceImpl extends ServiceImpl<ProjectApplicationMapper, ProjectApplication>
        implements IProjectApplicationService {

    private final IProjectCoreBusinessIndicatorsService projectCoreBusinessIndicatorsService;

    @Override
    public List<ProjectApplication> getApplicationsByProject(Project project) {
        return this.list(Wrappers.lambdaQuery(ProjectApplication.class)
                .eq(ProjectApplication::getProjectCode, project.getProjectCode()));
    }

    @Override
    public void saveApplication(Project project,Project oldProject,Boolean isConstruct) {
        List<ProjectApplication> apps = list(Wrappers.lambdaQuery(ProjectApplication.class)
                .eq(ProjectApplication::getProjectCode, oldProject.getProjectCode())
                .eq(ProjectApplication::getProjectVersion, oldProject.getVersion()));
        if(CollUtil.isNotEmpty(apps)){
            apps.forEach(app -> {
                Long oldAppId = app.getId();
                app.setProjectVersion(project.getVersion());
                app.setProjectId(project.getId());
                app.setId(null);
                if(Objects.nonNull(isConstruct)){
                    app.setIsConstruct(isConstruct);
                }
                save(app);

                //核心业务
                List<ProjectCoreBusinessIndicators> cores = projectCoreBusinessIndicatorsService.list(Wrappers.lambdaQuery(ProjectCoreBusinessIndicators.class)
                        .eq(ProjectCoreBusinessIndicators::getApplicationId, oldAppId));
                if(CollUtil.isNotEmpty(cores)){
                    cores.forEach(c -> {
                        c.setId(null);
                        c.setApplicationId(app.getId());
                        projectCoreBusinessIndicatorsService.save(c);
                    });
                }
            });
        }
    }
}
