package com.cusc.nirvana.user.rnr.project.handler;

import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.rnr.fp.dto.VehicleCardDTO;
import com.cusc.nirvana.user.rnr.fp.dto.VinCardInfoDTO;
import com.cusc.nirvana.user.rnr.fp.util.RnrFpRestTemplateUtils;
import com.cusc.nirvana.user.rnr.project.dto.ProjectCardExistRequestDTO;
import com.cusc.nirvana.user.rnr.project.dto.ProjectCardExistResponseDTO;
import com.cusc.nirvana.user.rnr.project.dto.ProjectVinCardRequestDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author stayAnd
 * @date 2022/4/8
 */
@Slf4j
public abstract class CuscVinCardHandler implements VinCardHandler {

	@Resource
	protected RestTemplate balancedRestTemplateRnrFp;


    protected VinCardInfoDTO queryVinCard(String url, String vin) {
        List<VehicleCardDTO> list = queryVinCardFromProjectService(url, Collections.singletonList(vin));
        VinCardInfoDTO vinCardInfoDTO = new VinCardInfoDTO();
        vinCardInfoDTO.setVin(vin);
        List<String> iccids = list.stream().filter(dto -> dto.getVin().equals(vin)).map(dto -> dto.getIccid()).collect(Collectors.toList());
        vinCardInfoDTO.setIccidList(iccids);
        return vinCardInfoDTO;
    }


    protected List<VinCardInfoDTO> queryVinCardList(String url, List<String> vinList) {
        List<VehicleCardDTO> vehicleCardDTOS = queryVinCardFromProjectService(url, vinList);

        Map<String,VinCardInfoDTO> vehicleCardDTOMap = new HashMap<>();

        for (VehicleCardDTO vehicleCardDTO : vehicleCardDTOS) {
            if(!vehicleCardDTOMap.containsKey(vehicleCardDTO.getVin())){
                VinCardInfoDTO vinCardInfoDTO = new VinCardInfoDTO();
                vinCardInfoDTO.setVin(vehicleCardDTO.getVin());
                vinCardInfoDTO.setIccidList(new ArrayList<>());
                vehicleCardDTOMap.put(vehicleCardDTO.getVin(),vinCardInfoDTO);
            }
            vehicleCardDTOMap.get(vehicleCardDTO.getVin()).getIccidList().add(vehicleCardDTO.getIccid());
        }
        return new ArrayList<>(vehicleCardDTOMap.values());
    }

    protected Response<ProjectCardExistResponseDTO> isCardExist(String url, String iccid) {
        ProjectCardExistRequestDTO requestDTO = new ProjectCardExistRequestDTO();
        requestDTO.setIccid(iccid);
        return RnrFpRestTemplateUtils.postForResponse(balancedRestTemplateRnrFp, url, requestDTO, ProjectCardExistResponseDTO.class);
    }

	private List<VehicleCardDTO> queryVinCardFromProjectService(String url, List<String> vinList){
		Response<List<VehicleCardDTO>> response = RnrFpRestTemplateUtils.postForResponseList(balancedRestTemplateRnrFp, url,
				new ProjectVinCardRequestDTO().setVins(vinList), VehicleCardDTO.class);
		if (!response.isSuccess() || response.getData() == null) {
			return Collections.emptyList();
		}
		return response.getData();
	}
}
