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

import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.scriptcase.dto.casedesign.TableHeader;
import net.northking.cctp.scriptcase.dto.sceneScript.UserCaseDataVerifyDto;
import net.northking.cctp.scriptcase.enums.ErrorMessage;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserCaseDataVerify implements IDataVerify<UserCaseDataVerifyDto> {


    @Override
    public boolean verify(UserCaseDataVerifyDto userCaseVerifyDto) throws Exception {
        //duplicate check
        List<TableHeader> headerList = userCaseVerifyDto.getTableHeader();
        Map<String, List<TableHeader>> headerMap =
                headerList.stream().collect(Collectors.toMap(TableHeader::getName, s ->{
                    List<TableHeader> headerList1 = new ArrayList<>();
                    headerList1.add(s);
                    return headerList1;
                }, (List<TableHeader> v1, List<TableHeader> v2)->{
                    v1.addAll(v2);
                    return v1;
                }));

        StringBuilder sb = new StringBuilder();
        for(Map.Entry<String, List<TableHeader>> entry : headerMap.entrySet()) {
            if(entry.getValue().size() > 1)
                sb.append(entry.getKey()).append(",");
        }
        String msg = sb.toString();
        if(StringUtils.hasText(msg)){
            msg = msg.substring(0, msg.length() - 1);
            throw new PlatformRuntimeException(new ErrorMessage("场景脚本输入项表头定义了重名的列名(重名列名是"+msg+")"));
        }

        return true;
    }
}
