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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.eiam.dto.OrganizationDTO;
import com.cusc.nirvana.user.exception.CuscUserException;
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.service.IFpCardUnBindService;
import com.cusc.nirvana.user.rnr.fp.service.IOrganService;
import com.cusc.nirvana.user.rnr.fp.service.IRnrService;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrCardInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgSurplusBindClient;
import com.cusc.nirvana.user.rnr.mg.client.RnrOrderClient;
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.MgRnrInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
import com.cusc.nirvana.user.util.DateUtils;
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 org.springframework.transaction.annotation.Transactional;

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

/**
 * @className: EnterpriseUnBindCallBackHandler
 * @description: 企业解绑短信回调
 * @author: jk
 * @date: 2022/6/17 16:36
 * @version: 1.0
 **/
@Slf4j
@Service
public class EnterpriseUnBindCallBackHandler implements MessageCallbackHandler {

    @Resource
    private MgRnrCardInfoClient mgRnrCardInfoClient;

    @Resource
    private MgRnrInfoClient mgRnrInfoClient;

    @Resource
    private RnrOrderClient rnrOrderClient;

    @Resource
    private IFpCardUnBindService cardUnBindService;

    @Value("${message.callback.timeout:120}")
    private int timeOut;

    @Resource
    private MgSurplusBindClient mgSurplusBindClient;

    @Resource
    private IRnrService iRnrService;

    @Autowired
    private IOrganService organService;

    @Transactional
    @Override
    public Response callBack(FpRnrSmsInfoDTO rnrSmsInfoDTOResponseData, UnbindReceiceSMSDTO bean, long receiveTIme) {
        log.warn("rnrSmsInfoDTOResponseData-------{},UnbindReceiceSMSDTO-------{}", JSONObject.toJSONString(rnrSmsInfoDTOResponseData), JSONObject.toJSONString(bean));
        RnrOrderDTO rnrOrderDTO = new RnrOrderDTO();
        rnrOrderDTO.setUuid(rnrSmsInfoDTOResponseData.getOrderId());
        Response<RnrOrderDTO> orderStatus = cardUnBindService.getOrderStatus(rnrOrderDTO);
        if (!orderStatus.isSuccess() || orderStatus.getData() == null) {
            return Response.createError(orderStatus.getMsg(), orderStatus.getData());
        }
        RnrOrderDTO orderDTO = orderStatus.getData();

        long startTime = rnrSmsInfoDTOResponseData.getCreateTime().getTime();
        log.info("当前时间: {},短信发送时间: {}", DateUtils.currentTimeStr(), receiveTIme);
        boolean isTimeOut = receiveTIme - timeOut * 1000 > startTime;
        if (isTimeOut) {
            //更新工单 超时
            orderDTO.setOrderStatus(RnrOrderStatusEnum.CANCEL.getCode());
            return cardUnBindService.updateOrder(orderDTO);
        }

        //获取rnrId
        String rnrId = rnrSmsInfoDTOResponseData.getRnrId();

        MgRnrCardInfoDTO mgRnrCardInfoDTO = new MgRnrCardInfoDTO();
        mgRnrCardInfoDTO.setRnrId(rnrId);
        //根据rnrId查询carInfo信息
        Response<List<MgRnrCardInfoDTO>> mgRnrCardInfoResponse = mgRnrCardInfoClient.queryByList(mgRnrCardInfoDTO);
        if (!mgRnrCardInfoResponse.isSuccess()) {
            throw new CuscUserException(mgRnrCardInfoResponse.getCode(), mgRnrCardInfoResponse.getMsg());
        }
        List<MgRnrCardInfoDTO> mgRnrCardInfoDTOList = mgRnrCardInfoResponse.getData();

        if (!bean.getReplyContent().toLowerCase().equals("y")) {
            RnrOrderDTO rnrOrder = new RnrOrderDTO();
            rnrOrder.setUuid(mgRnrCardInfoDTOList.get(0).getOrderId());
            iRnrService.updateRnrInValid(rnrOrder);
            orderDTO.setOrderStatus(RnrOrderStatusEnum.NOT_PASS.getCode());
            return cardUnBindService.updateOrder(orderDTO);
        }

        //查询车企信息
        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("EnterpriseUnBindCallBackHandler  获取车企组织失败，{}", JSON.toJSONString(organResp));
            manufacturerOrgId = "0";
        }

        List<MgCardNoticeDTO> cardNoticeDTOS = new ArrayList<>();
        MgCardNoticeDTO mgCardNoticeDTO;

        List<MgRnrCardInfoDTO> newCardIdList = new ArrayList<>();
        MgRnrCardInfoDTO cardInfoDTO;
        //新卡uuid
        for (MgRnrCardInfoDTO cardTemp : mgRnrCardInfoDTOList) {
            cardInfoDTO = new MgRnrCardInfoDTO();
            cardInfoDTO.setUuid(cardTemp.getUuid());
            newCardIdList.add(cardInfoDTO);

            //构建消息通知
            mgCardNoticeDTO = new MgCardNoticeDTO();
            mgCardNoticeDTO.setIccid(cardTemp.getIccid());
            mgCardNoticeDTO.setTenantNo(orderDTO.getTenantNo());
            mgCardNoticeDTO.setVin(cardTemp.getIotId());
            mgCardNoticeDTO.setRnrBizzType(orderDTO.getRnrBizzType());
            mgCardNoticeDTO.setOrderId(orderDTO.getUuid());
            mgCardNoticeDTO.setManufacturerOrgId(manufacturerOrgId);
            mgCardNoticeDTO.setResultCode(RnrOrderStatusEnum.PASS.getCode());
            mgCardNoticeDTO.setOrgId(orderDTO.getOrgId());
            cardNoticeDTOS.add(mgCardNoticeDTO);
        }

        //老卡uuid
        List<MgRnrCardInfoDTO> oldCardIdList = mgRnrCardInfoDTOList.stream().map(a -> {
            MgRnrCardInfoDTO mg = new MgRnrCardInfoDTO();
            mg.setUuid(a.getOldCardId());
            return mg;
        }).collect(Collectors.toList());

        //批量更新老数据
        mgRnrCardInfoClient.updateBatch(oldCardIdList);

        //批量更新新数据
        mgRnrCardInfoClient.updateBatch(newCardIdList);

        //更新info
        MgRnrInfoDTO mgRnrInfoDTO = new MgRnrInfoDTO();
        mgRnrInfoDTO.setUuid(rnrId);
        mgRnrInfoDTO.setRnrStatus(RnrStatus.UNBOUND.getCode());
        mgRnrInfoClient.update(mgRnrInfoDTO);

        //更新order
        RnrOrderDTO rnrOrder = new RnrOrderDTO();
        rnrOrder.setUuid(mgRnrCardInfoDTOList.get(0).getOrderId());
        rnrOrder.setOrderStatus(RnrOrderStatusEnum.PASS.getCode());
        rnrOrderClient.updateOrderStatus(rnrOrder);

        mgSurplusBindClient.sendMQ(cardNoticeDTOS);

        return Response.createSuccess("解绑成功");
    }
}
