package com.cusc.nirvana.user.rnr.fp.handler.impl;


import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.common.constant.VinCardCheckBussinessDetailType;
import com.cusc.nirvana.user.rnr.fp.dto.*;
import com.cusc.nirvana.user.rnr.fp.handler.VinCardCheckMessageHandler;
import com.cusc.nirvana.user.rnr.fp.service.ISimVehicleRelService;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrCardInfoClient;
import com.cusc.nirvana.user.rnr.mg.constants.RnrStatus;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrCardInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author stayAnd
 * @date 2022/6/1
 * 通用绑卡业务 车卡关系校验实现
 */
@Component("commonUnBindVinCardCheckHandler")
@Slf4j
public class CommonUnBindVinCardCheckHandlerImpl implements VinCardCheckMessageHandler {

	@Resource
	private MgRnrCardInfoClient cardInfoClient;

	@Resource
	private ISimVehicleRelService simVehicleRelService;


	@Override
	public VinCardCheckMessageResultDTO checkVinCard(String vin, List<String> iccidList, VinCardCheckBussinessDetailType type) {
		VinCardCheckMessageResultDTO resultDTO = new VinCardCheckMessageResultDTO();

		MgRnrCardInfoDTO query = new MgRnrCardInfoDTO();
		query.setIccidList(iccidList);
		Response<List<MgRnrCardInfoDTO>> response = cardInfoClient.queryByList(query);
		if (null == response || !response.isSuccess()) {
			throw new CuscUserException("","查询卡信息失败");
		}
		List<MgRnrCardInfoDTO> cardInfoDTOList = response.getData();

		List<String> hasRnrIccidList = cardInfoDTOList.stream()
				.filter(card -> RnrStatus.RNR.getCode() == card.getRnrStatus()).map(MgRnrCardInfoDTO::getIccid)
				.collect(Collectors.toList());

		//失败错误的卡
		List<VinCardCheckMessageFailDTO> failDTOList = new ArrayList<>();

		//非实名的卡
		List<MgRnrCardInfoDTO> notRnrCardList = cardInfoDTOList.stream().filter(card -> !hasRnrIccidList.contains(card.getIccid())).collect(Collectors.toList());

		List<VinCardCheckMessageFailDTO> notRnrErrorList = notRnrCardList.stream().map(card -> {
			VinCardCheckMessageFailDTO failDTO = new VinCardCheckMessageFailDTO();
			failDTO.setIccid(card.getIccid());
			failDTO.setErrorMsg("输入的卡信息存在非实名的卡");
			return failDTO;
		}).collect(Collectors.toList());

		if (!CollectionUtils.isEmpty(notRnrErrorList)) {
			failDTOList.addAll(notRnrErrorList);
		}

		//构建参数
		resultDTO.build(failDTOList);

		return resultDTO;
	}




	protected void checkVin(String vin){
		//子类有特殊判断实现此方法
	}


}
