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

import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.eiam.dto.OrganizationDTO;
import com.cusc.nirvana.user.rnr.fp.constants.ResultCodeEnum;
import com.cusc.nirvana.user.rnr.fp.dto.FpRnrSmsInfoDTO;
import com.cusc.nirvana.user.rnr.fp.dto.UnbindReceiceSMSDTO;
import com.cusc.nirvana.user.rnr.fp.handler.MessageCallbackHandler;
import com.cusc.nirvana.user.rnr.fp.service.IFpCardUnBindService;
import com.cusc.nirvana.user.rnr.fp.service.IFpChangeTboxService;
import com.cusc.nirvana.user.rnr.fp.service.IOrganService;
import com.cusc.nirvana.user.rnr.fp.service.IRnrService;
import com.cusc.nirvana.user.rnr.fp.service.impl.RnrServiceImpl;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrCardInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgSurplusBindClient;
import com.cusc.nirvana.user.rnr.mg.constants.RnrBizzTypeEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderStatusEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrStatus;
import com.cusc.nirvana.user.rnr.mg.dto.MgCardNoticeDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrCardInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author yubo
 * @since 2022-05-04 16:20
 */
@Service
@Slf4j
public class CardUnBindMessageCallBackHandler implements MessageCallbackHandler {
    @Value("${message.callback.timeout:120}")
    private int timeOut;

    @Resource
    private IFpCardUnBindService cardUnBindService;

    @Autowired
    private IFpChangeTboxService changeTboxService;

    @Resource
    private MgRnrCardInfoClient cardInfoClient;

    @Resource
    private MgSurplusBindClient mgSurplusBindClient;

    @Autowired
    private IRnrService rnrService;

	@Autowired
	private IOrganService organService;

    @Override
    public Response callBack(FpRnrSmsInfoDTO rnrSmsInfoDTOResponseData, UnbindReceiceSMSDTO bean, long receiveTIme) {

        RnrOrderDTO rnrOrderDTO = new RnrOrderDTO();
        rnrOrderDTO.setUuid(rnrSmsInfoDTOResponseData.getOrderId());
        com.cusc.nirvana.common.result.Response<RnrOrderDTO> orderStatus = cardUnBindService.getOrderStatus(rnrOrderDTO);
        log.info("获取解绑工单信息: {}", JSON.toJSONString(orderStatus));
        if (!orderStatus.isSuccess() || orderStatus.getData() == null) {
            return Response.createError(orderStatus.getMsg(), orderStatus.getData());
        }
        long startTime = rnrSmsInfoDTOResponseData.getCreateTime().getTime();
        log.info("当前时间: {},短信发送时间: {}", receiveTIme, toString());
        boolean isTimeOut = receiveTIme - timeOut * 1000 > startTime;
        if (isTimeOut) {
            //更新工单 超时
            RnrOrderDTO orderDTO = orderStatus.getData();
            orderDTO.setOrderStatus(RnrOrderStatusEnum.CANCEL.getCode());
            return cardUnBindService.updateOrder(orderDTO);
        }
        //根据工单id获取工单
        if (!bean.getReplyContent().toLowerCase().equals("y")) {
            //更新工单 失败
            RnrOrderDTO orderDTO = orderStatus.getData();
            orderDTO.setOrderStatus(RnrOrderStatusEnum.NOT_PASS.getCode());
            return cardUnBindService.updateOrder(orderDTO);
        } else {
            //更新工单
            RnrOrderDTO orderDTO = orderStatus.getData();
            orderDTO.setOrderStatus(RnrOrderStatusEnum.PASS.getCode());
			Response<RnrOrderDTO> orderResponse = cardUnBindService.updateOrder(orderDTO);


			//查询卡信息
			MgRnrCardInfoDTO query = new MgRnrCardInfoDTO();
			query.setOrderId(rnrOrderDTO.getUuid());

			//解绑新插入的卡信息
			List<MgRnrCardInfoDTO> cardInfoList = cardInfoClient.queryByList(query).getData();

			//关联的需要解绑卡信息
			List<String> toUnbindCardUuIdList = cardInfoList.stream().map(MgRnrCardInfoDTO::getOldCardId).collect(Collectors.toList());

			//新插入的卡信息和 原先需要解绑卡信息 全部解绑
			List<String> cardInfoUuidList = cardInfoList.stream().map(MgRnrCardInfoDTO::getUuid).collect(Collectors.toList());

			toUnbindCardUuIdList.addAll(cardInfoUuidList);

			log.info("原车主解绑 orderId = {}, toUnbindCardUuIdList = {}",rnrOrderDTO.getUuid(),JSON.toJSONString(toUnbindCardUuIdList));
			List<MgRnrCardInfoDTO> allUnBindCardList = toUnbindCardUuIdList.stream().map(uuid -> {
				MgRnrCardInfoDTO unBindCard = new MgRnrCardInfoDTO();
				unBindCard.setUuid(uuid);
				return unBindCard;
			}).collect(Collectors.toList());

			//解绑所有的卡
			Response unBindCardResult = changeTboxService.unbindCardList(allUnBindCardList);


			String manufacturerOrgId;
			OrganizationDTO organ = new OrganizationDTO();
			organ.setTenantNo(orderDTO.getTenantNo());
			organ.setUuid(orderDTO.getOrgId());
			Response<OrganizationDTO> organResp = organService.getCarSubOrganByOrgId(organ);
			if (organResp != null && organResp.isSuccess() && organResp.getData() != null) {
				manufacturerOrgId = organResp.getData().getUuid();
			} else {
				log.warn("sendCardNoticeByOrderId 获取车企组织失败，{}", JSON.toJSONString(organResp));
				manufacturerOrgId = "0";
			}

			//发送mq通知
			List<MgCardNoticeDTO> mgCardNoticeList = createMqDTO(cardInfoList, orderDTO,manufacturerOrgId);
            mgSurplusBindClient.sendMQ(mgCardNoticeList);

            if (unBindCardResult.isSuccess() && orderResponse.isSuccess()) {
                //将实名结果回传给智网
                rnrService.notifyResult(cardInfoList,RnrBizzTypeEnum.Unbound.getCode().toString(),UUID.randomUUID().toString(),null, ResultCodeEnum.PASS.getCode());
                return com.cusc.nirvana.common.result.Response.createSuccess("解绑卡/更新工单成功");
            } else {
                return com.cusc.nirvana.common.result.Response.createError("解绑卡/更新工单失败");
            }
        }
    }



	private List<MgCardNoticeDTO> createMqDTO(List<MgRnrCardInfoDTO> cardList, RnrOrderDTO orderDTO,
											  String manufacturerOrgId) {
		List<MgCardNoticeDTO> cardNoticeList = new ArrayList<>();
		MgCardNoticeDTO mgCardNoticeDTO;
		for (MgRnrCardInfoDTO cardInfoDTO:cardList) {
			mgCardNoticeDTO = new MgCardNoticeDTO();
			mgCardNoticeDTO.setIccid(cardInfoDTO.getIccid());
			mgCardNoticeDTO.setTenantNo(cardInfoDTO.getTenantNo());
			mgCardNoticeDTO.setVin(cardInfoDTO.getIotId());
			mgCardNoticeDTO.setRnrBizzType(orderDTO.getRnrBizzType());
			mgCardNoticeDTO.setOrderId(orderDTO.getUuid());
			mgCardNoticeDTO.setManufacturerOrgId(manufacturerOrgId);
			mgCardNoticeDTO.setResultCode(orderDTO.getOrderStatus());
			mgCardNoticeDTO.setOrgId(orderDTO.getOrgId());
			cardNoticeList.add(mgCardNoticeDTO);
		}
		return cardNoticeList;
	}

}
