package net.northking.cctp.scriptcase.api.scenescript.service.verfiy;

import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.scriptcase.api.scenescript.bean.SceneScript;
import net.northking.cctp.scriptcase.db.entity.AtuSceneInfo;
import net.northking.cctp.scriptcase.db.service.AtuSceneInfoService;
import net.northking.cctp.scriptcase.dto.sceneScript.SceneNameVerifyDto;
import net.northking.cctp.scriptcase.enums.ErrorMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SceneNameVerify  implements IDataVerify<SceneNameVerifyDto> {
    @Autowired
    private AtuSceneInfoService atuSceneInfoService;

    @Override
    public boolean verify(SceneNameVerifyDto sceneNameVerifyDto) throws Exception {//场景明唯一校验
        SceneScript sceneScript = sceneNameVerifyDto.getSceneScript();
        if(sceneScript.getName() == null || "".equals(sceneScript.getName()))
            throw new PlatformRuntimeException(new ErrorMessage("场景名为空！"));
        if(sceneScript.getName().length() > 30)
            throw new PlatformRuntimeException(new ErrorMessage("场景名长度超过30！"));

        //查询当前系统数据库是否存在重名校验
        String sceneScriptId = sceneScript.getId();
        String projectId = sceneNameVerifyDto.getProjectId();
        AtuSceneInfo atuSceneInfo1 = new AtuSceneInfo();
        atuSceneInfo1.setProjectId(projectId);
        atuSceneInfo1.setTenantId(NKSecurityContext.getTenantId());
        atuSceneInfo1.setId(sceneScriptId);
        atuSceneInfo1.setIsDeleted(0);
        long c1 = atuSceneInfoService.count(atuSceneInfo1);
        AtuSceneInfo atuSceneInfo = new AtuSceneInfo();
        atuSceneInfo.setSceneName(sceneScript.getName());
        atuSceneInfo.setProjectId(projectId);
        atuSceneInfo.setIsDeleted(0);
        atuSceneInfo.setTenantId(NKSecurityContext.getTenantId());
        List<AtuSceneInfo> list = atuSceneInfoService.query(atuSceneInfo);
        if(c1 == 1 && ((list.size() == 1 && list.stream().filter(x->x.getId().equals(sceneScriptId)).count() == 0) ||
                list.size() > 1))
            throw new PlatformRuntimeException(new ErrorMessage(sceneScript.getName()+"场景名重名"));
        if(c1 == 0 && list.size() > 0)
            throw new PlatformRuntimeException(new ErrorMessage(sceneScript.getName()+"场景名重名"));
       return true;
    }
}
